Please enable JavaScript to use CodeHS

Documentation

p5play Library

p5play Reference Guide and Docs

Check out the official p5play reference guide (some pages may require an account) and p5play docs page for additional resources!

Primary Functions

// The setup() function runs once at the beginning of
// the program. Use it to initialize elements like the
// canvas and game components.
function setup() {...}

// The draw() function runs 60 times/sec by default. This
// is your primary game loop. Use it for all interactions
// and sprite changes over time.
function draw() {...}

// OPTIONAL: The preload() function can load elements
// like music and images before the setup() function is
// called.
function preload() {...}
    
JavaScript

Canvas

// Create a new canvas with width 350px and height 450px
new Canvas(350, 450);

// You can remove the arguments to have it fill the window
new Canvas();

// Use an aspect ratio to have it scale to the largest
// possible size of that ratio in the window
new Canvas('3:4');

// Use pixelated mode for retro style pixel games. It
// scales the canvas to fit the screen while retaining
// its aspect ratio.
new Canvas(450, 450, 'pixelated');
// To display all sprites at integer coordinates, set:
allSprites.pixelPerfect = true;

// The variables "width" and "height" store the dimensions
// of the canvas after it is set up
new Canvas(200, 400);
console.log(width); // prints 200
console.log(height); // prints 400

// Set the background color of the canvas
background('lightblue');

// Clear the canvas for each frame
clear();
    
JavaScript

Gravity

// Turn on gravity after you create your canvas
world.gravity.y = 10;

// You can change the direction and strength of gravity
// with the x and y properties
world.gravity.y = 20;
world.gravity.x = 10;
    
JavaScript

Sprites

// A sprite is a graphical object with properties that
// determine how it looks and behaves on the canvas.

// Sprites are used as game components that sit on top
// of the background, like characters and objects.

// To create a new sprite and save it to a variable
let ball = new Sprite();

// Use dot notion to set the sprite properties
ball.x = 300;
ball.y = 200;
ball.radius = 20;
ball.bounciness = 0.5;
ball.mass = 3;
ball.speed = 2;
ball.direction = 30;
ball.rotationDrag = 5;
ball.color = 'purple';

// Another example with a box
let box = new Sprite();
box.width = 100;
box.height = 300;
box.friction = 3;
box.rotation = 20;
box.vel.x = 1;
box.vel.y = 2;
box.color = '#fcba03';

// Another example setting up a static ground
let ground = new Sprite();
ground.width = width; // the width of the canvas
ground.height = 30;
ground.y = height - ground.height / 2;
ground.friction = 1;
ground.layer = 0;
ground.img = loadImage('img URL'); // applies an image
ground.scale = 2; // sets the scale of the image
ground.collider = 'static';

/* Different colliders:
'dynamic': the default collider for sprites
'kinematic': can move by code, but nothing else can move it
'static': can't move
'none': doesn't collide with other sprites
*/

// You can also quickly set up a sprite using arguments
let planet = new Sprite(x,  y,  w,  h, collider);

    
JavaScript
Check out the official p5play reference guide for a complete list of sprite properties and demos!

Boolean Expressions

// ==== Keyboard ==== //        

// This statement will be true at the moment the user presses
// the specified key.
kb.presses(key letter or name)
// This statement will be true the entire time the user is
// pressing the specified key.
kb.pressing(key letter or name)

// Examples:
kb.presses('w'); // pressed "w"
kb.pressing('space');  // pressing and holding "space"

// ==== Mouse ==== //

// This statement will be true at the moment the user clicks
// the mouse button on the sprite.
sprite.mouse.presses()
// This statement will be true the entire time the user is
// pressing the mouse button on the sprite.
sprite.mouse.pressing()
// This statement will be true if the user clicked on the 
// sprite, and with the button down, is trying to drag it around.
sprite.mouse.dragging()

// Examples:
tree.mouse.presses(); // clicks on sprite named "tree"
ball.mouse.dragging(); // dragging sprite named "ball"

// ==== Sprite Interaction ==== //

// This statement will be true at the moment sprite1 begins
// to overlap with sprite2.
sprite1.overlaps(sprite2)
// This statement will be true the entire time sprite1 is
// overlapping with sprite2.
sprite1.overlapping(sprite2)
// This statement will be true at the moment sprite1 collides
// with sprite2
sprite1.collides(sprite2)

//Examples:
cookie.overlaps(monster);
shoe.overlapping(ice);
ball.collides(stick); 
    
JavaScript

Movement

// There are a few different ways to move your p5play sprites

// ==== Sprite Movement Properties ==== //

// Set the sprite's speed and direction properties
sprite.speed = 5;
sprite.direction = 90; // angle, clockwise from +x direction

// Set the sprite's X and Y velocities
sprite.vel.x = 3;
sprite.vel.y = 5;


// ==== Movement Methods ==== //

// Move the sprite a fixed distance
sprite.move(30, 0, 5);  // (distance, direction, speed)

// Move the sprite toward sprite, mouse, or position
sprite.moveTowards(mouse, 0.1);   // (sprite or mouse, rate)
// Or
sprite.moveTowards(100, 50, 0.1)  // (x, y, rate)

// Apply a force to a sprite in a direction
sprite.bearing = 90;    // sets the angle direction of the force
sprite.applyForce(5);   // applies a force of magnitude 5

// Make the sprite attracted to a sprite or position
sprite.attractTo(sprite2, 5);   // (sprite, magnitude)
// Or
sprite.attractTo(100, 50, 5);   // (x, y, magnitude)

// Rotate the sprite a number of degrees at a rate
sprite.rotate(5, 10)    // (angle, rotation rate)`
    
JavaScript

Colors

Click here to access a simple online HEX color picker.
// Can use color strings, HEX, or rgb to set colors
'blue'          // string
'#7cd4f7'       // HEX
124, 212, 247   // RGB

// Set the background color of the canvas
background('#7cd4f7');

// Set the color of a sprite
spriteName.color = '#7cd4f7';
    
JavaScript

JavaScript Basics

Printing to Console


// Using the console.log() function will print the text
// to the console and create a line break 

console.log("Hello World.");
console.log("How are you?");
// prints:
// Hello World.
// How are you?

// Concatenate strings and variables using the "+" sign

console.log("Greetings " + "Earthling."); 
// prints:
// Greetings Earthling

let species = "Martian";
console.log("Greetings " + species); 
// prints: 
// Greetings Martian


JavaScript

Variables


// Declare a variable
let myVarName;

// Declare and initialize a variable
let myVarName = 5;

// Assign value to an existing variable
myVarName = 10;

// Print a variable
console.log(myVarName);
console.log("The value is: " + myValue);

// If a variable isn't going to change its value, it is
// best to use the keyword 'const'

// Variables defined with const:
//   * cannot be redeclared
//   * cannot be reassigned
//   * must be assigned a value when they are declared

// Example:
const PI = 3.141592653589793;
PI = 5;      // This will give an error
JavaScript

User Input


// Read a string
// Strings are a series of characters - ex) Hello World
let choice = readLine("What would you like? ");

// Read an integer
// Integers are numbers without a decimal point - ex) 3
let num = readInt("Enter a number: ");

// Read a float
// Float are numbers with a decimal point - ex) 3.14
let cost = readFloat("Enter the cost: ");

// Read a boolean
// Boolean are true/false
let workIsDone = readBoolean("Did you finish your work? ");

JavaScript

Asynchronous User Input


/* In addition to the blocking input methods that receive input via 
popup, there are additional asynchronous input methods. readLineAsync, 
readIntAsync, readFloatAsync, and readBooleanAsync are non-blocking 
functions that can be used in combination with the `await` keyword to 
receive input asynchronously.
*/

let name = await readLineAsync("What's your name? ");
console.log("Nice to meet you, " + name);
        
JavaScript
To read more about asynchronous user input, see this tutorial.

Math

/* Operators:
    +   Addition
    -   Subtraction
    *   Multiplication
    /   Division
    **  Exponentiation
    %   Modulus (Remainder)
    ()  Parentheses (For order of operations)
*/

// Examples
let z = x + y;
let w = x * y;

// Increment (add one)
x++

// Decrement (subtract one)
x--

// Shortcuts
x = x + y;      x += y;
x = x - y;      x -= y;
x = x * y;      x *= y;
x = x / y;      x /= y;

// Exponentiation
let squared = 5 ** 2;
console.log(squared);   // prints out 25

// Modulus
let z = 14 % 4;     // 14 รท 4 = 3 with a remainder of 2
console.log(z);     // prints out 2

// Absolute value
let abs = Math.abs(x);

// Square root
let sqrt = Math.sqrt(x);

// Rounding
// Math.round() can be used to round numbers
const PI = 3.14;
let roundedPi = Math.round(PI);
console.log(roundedPi);     // prints out: 3

const GOLDEN_RATIO = 1.618;
let roundedGoldenRatio = Math.round(GOLDEN_RATIO);
console.log(roundedGoldenRatio);        // prints out: 2

// Floor Division
// Math.floor() can be used to perform floor
// division. With floor division, only the
// integer portion of the quotient is returned.

// For example, 5/2 is 2.5, but with floor division,
// the result is 2 and the .5 is discarded.
let result = Math.floor(5/2);
console.log(result);        // prints out: 2


// Geometry
// Note input is in radians, not degrees

Math.sin(radians); // Returns value between -1 and 1
Math.cos(radians); // Returns value between -1 and 1
Math.tan(radians); // Returns value

JavaScript

Random Numbers


// There are several different random methods
Randomizer.nextInt(low, high);
Randomizer.nextBoolean();
Randomizer.nextFloat(low, high);
Randomizer.nextColor();

// Example rolling a dice to get a random roll
let roll = Randomizer.nextInt(1, 6);

JavaScript

Functions


// A function is a reusable block of code that
// performs a specific task when called.

// To call a function, write the function name,
// followed by parentheses:
printGreeting();

// To define what a function does, use the "function"
// keyword and put the task inside the {} brackets:
function printGreeting() {
    console.log("Hi there!");
}

// Functions can take in values, called parameters.

// The function below takes in a parameter called 
// 'name' and prints it in a greeting.
function printGreeting(name) {
    console.log("Hi there " + name);
}

// To call a function that has a parameter, you need
// to include a value, or arguement, when calling it:
printGreeting("Sami");

// Functions can also return a value.

// The function below takes in a value,
// adds two to it, and returns it.
function addTwo(number) {
    return number + 2;
}
JavaScript

Strings


// str.length returns the length of a string

// Example
let str = "hello";
let len = str.length; // equals 5

// str.indexOf(search) returns the first index of the search
// or -1  if not found. It is case sensitive.

//Examples
let str = "hello";
let pos1 = str.indexOf("l"); // returns 2
let pos2 = str.indexOf("H"); // returns -1

// str.substring(start) returns a substring including the
// character at start to the end of the string

//Examples
let str = "hello";
let sub1 = str.substring(1); // equals "ello"
let sub2 = str.substring(3); // equals "lo"

// str.substring(start, end) returns a substring including the
// character at start, but not including the character at end

//Examples
let str = "hello";
let sub1 = str.substring(0,2); // equals "he"
let sub2 = str.substring(1,4); // equals "ell"

JavaScript
To read more about string methods, see this tutorial.

Control Structures

Booleans


// A boolean is either true or false
let myBoolean = true;

let anotherBoolean = false;

let result = readBoolean("Question? ");

// Not Operator
let x = !y;     // x gets the opposite of y

// And Operator
let andExp = x && y;

// Or Operator
let orExp = x || y;

// You can combine many booleans!
let boolExp = x && (y || z);
JavaScript

If Statements, If/Else, If/Else If/Else


if (BOOLEAN_EXPRESSION) {
    // code to execute if the experession is true
}

if (BOOLEAN_EXPRESSION) {
    // code to execute if the expression is true
} else {
    // code to execute if the expression is false
}

if (x < 0) {
    console.log("x is negative.");
}

if (color == "red" || color == "blue" || color == "yellow") {
    console.log("Primary color.");
} else {
    console.log("Not a primary color.");
}

// You can use else if you have multiple
// conditions, but only one should happen.
if (condition_1) {

} else if (condition_2) {

} else if (condition_3) {

} else {

}

// You can always write these using nested
// if/else. For example:
if (condition_1) {
    // code here runs if condition 1 is true
} else {
    if (condition_2) {
        // if condition 2 is true
    } else {
        // and here if condition 2 is false
    }
}
JavaScript

Logical Operators


// Logical operators return booleans (true/false values)
x && y  // AND operator -- true if BOTH x and y are true
x || y  // OR operator -- true if x OR y are true
! x     // NOT operator -- true if x is false (and false if x is true)

// Logical operators in if statements
if (x && y) {
    console.log("x and y are both true");
}

if (x || y) {
    console.log("x and/or y are true");
}

if (!x && y) {
    console.log("x is false and y is true");
}
JavaScript

Comparison Operators


// Comparison operators return booleans (true/false values)
x == y      // is x equal to y
x != y      // is x not equal to y
x > y        // is x greater than y
x >= y       // is x greater than or equal to y
x < y        // is x less than y
x <= y       // is x less than or equal to y

// Comparison operators in if statements
if (x == y) {
    console.log("x and y are equal");
}

if (x > 5) {
    console.log("x is greater than 5.");
}
JavaScript

For Loops


// for loops repeat code a specific number of times

const COUNT = 5;

for (let i = 0; i < COUNT; i++) {
    /* Repeat code betweeen the brackets 5 times,
     * as the COUNT variable is 5. */
}

// Print numbers 0-9
for (let i = 0; i < 10; i++) {
    console.log(i);
}
JavaScript

While Loops


// while loops repeat until a boolean expression becomes false

while(boolean expression){
    /* Repeat code betweeen brackets while
     * 'boolean expression' is true */
}

// Countdown from from 15 to 10
let i = 15;
while (i > 9) {
    console.log(i);
    i--;
}

// Use a break statement to exit out of a loop
while (true) {
    // code to repeat
    if (condition) {
        break;      // breaks out of while loop
    }
}
JavaScript

Data Structures

Arrays


// Create an empty array
let arr = [];

// Create an array with values
let arr = [1, 2, 4];

// An array can have any type of data (x is a variable)
let arr = [4, "hello", x];

// Access an element in an array with arr[index];
let firstElem = arr[0];

// Set an element in an array
arr[4] = 9;

// length of an array
let length = arr.length;

// Looping over an array
for (let i = 0; i < arr.length; i++) {
    let cur = arr[i];
    // process cur
}

// Can also use for...of loops
for (let element of arr) {
    console.log(element);
}

// Add to an array
arr.push(elem);

// Remove last element from array
let last = arr.pop();

// Finding the index of an element
let index = arr.indexOf(5);

// Remove an element at an index i
arr.remove(i)
JavaScript

Objects


// Object literal
let obj = {
    name: "Jeremy",
    color: "blue"
};

// Objects have a collection of key-value pairs

// Set a value
obj["Jeremy"] = "123-4567";

// Get a value for a key
let phone = obj["Jeremy"];

// Dot notation
let phone = obj.Jeremy;

// Loop over an object
for (let key in obj) {
    let val = obj[key];
    // process key and val
}
JavaScript

Sets


// Make a new set named "newSet"
let newSet = new Set();

// Add to a set
newSet.add(5);

// Does a set contain a value
newSet.contains(5); // returns a boolean

// Number of elements in the set
let count = newSet.size; // returns an integer

// Make a new set named "setA"
let setA = new Set();

// Add 2 numbers to the set
setA.add(1);
setA.add(2);

// Make a new set named "setB"
let setB = new Set();

// Add 2 numbers to the set
setB.add(2);
setB.add(3);

// Call the intersect function on "setA" and pass in "setB", store the resulting
// set in a new variable named "mutualSet"
let mutualSet = setA.intersect(setB);
JavaScript

Grids


// Create a grid named "newGrid"
let newGrid = new Grid(rows, cols);

// Get a value in a grid
let elem = newGrid.get(row, col);

// Set a value in a grid
newGrid.set(row, col, val);

// Getting dimensions
let rows = newGrid.numRows();
let cols = newGrid.numCols();

// Is a row, col pair inbounds
newGrid.inBounds(row, col);

// Set all values in grid to initial value
newGrid.init(0); // sets all grid values to 0

// Initialze a grid from an array
newGrid.initFromArray([
    [6, 3, 2],  // 0th row
    [2, 5, 1],  // 1st row
    [4, 3, 9],  // 2nd row
    [1, 5, 1]   // 3rd row
]);
JavaScript