Quick intro to JavaScript and codeguppy.com
JavaScript is one of the most versatile programming languages and a core tool for creative coding, game development and web development. Whether you are a beginner or looking to refresh your knowledge, this guide offers a quick overview of fundamental JavaScript concepts, designed to help you hit the ground running. You'll also learn how to leverage codeguppy.com, a beginner-friendly online coding platform, to practice your skills. From variables to loops and functions, this article-book serves as a reference to get started quickly with JavaScript.
Table of Contents
Chapter 1: JavaScript Syntax
- Variables
- if statement
- For loop
- While loop
- Do While loop
- Switch statement
- Functions
- Array methods
- String methods
- Random numbers
- Modules
Chapter 2: Drawing on canvas using JavaScript
- About canvas
- Clearing the canvas
- Background color
- Drawing shapes
- Shape settings
- Turtle Graphics
- Colors
- Angles
- Animations
Chapter 3: User Input
- keyPressed event
- keyReleased event
- keyTyped event
- mouseClicked event
- mousePressed event
- mouseReleased event
- mouseMoved event
- mouseDragged event
- doubleClicked event
- mouseWheel event
- keyIsPressed
- key
- keyCode
- mouseX
- mouseY
- pmouseX
- pmouseY
- mouseIsPressed
- mouseButton
- keyIsDown()
- keyWentDown()
Chapter 4: JavaScript Game Development with codeguppy.com
- Drawing layers
- Setting Background Images
- Loading built-in sprites
- Loading custom sprites
- Loading animated custom sprites
- Set sprite position
- Moving sprites automatically
- Mirroring Sprites
- Sprite rotation
- Rotate sprites automatically
- Drawing depth
- Changing animations
- Mouse events on sprites
- Hiding sprites
- Removing sprites
- Sprite Collisions
- Sprite Groups
- Background Music
- Sound Effects
- Collisions between shapes
- The Game Loop
- Preloading assets
- Showing a scene
- The enter event
- Passing data to a scene
Chapter 5: Other coding hints
Chapter 1: JavaScript Syntax
Let's start our article by exploring the JavaScript syntax.
Declaring variables
Variables are used to store data such as numbers, strings (text) or even complex objects. Remember:
- You can have as many variables as you want inside a program.
- You need to name each variable with a name that represents the data it stores.
- Give different names to variables inside the same code block (e.g. whats between
{ ... }
) or even inside a function
Declare variable x
let x;
Declare x and initialize it with a numerical value
let x = 1;
Declare s and initialize it with a string
let s = "Hello, World!";
Assigning values to variables
Once a variable has been declared with let
it can be assigned / reassigned with different values as many times as you want.
You can assign it with simple constants or even complex expressions that include constants, other variables and even the same variable! Computers are very good at evaluating expressions.
Assign number 100 to variable x
x = 100;
Assign string "Hello" to variable s
s = "Hello";
Assign an empty array to variable ar
ar = [];
Assign an array of 3 numbers to variable ar
ar = [1, 2, 3];
Assign and array of 2 strings to variable ar
ar = ["A", "B"];
Assign an inline object to variable o
o = { Type: 'car',
x : 100,
y : 200
};
Variable sum is equal to a + b
sum = a + b;
Assign an expression to variable avg
avg = (a + b) / 2;
Variable sum is increased by 10 (the new sum becomes the older sum + 10)
sum = sum + 10;
Variable i is increased (incremented) by 1
i++;
Variable i is incremented by 2
i += 2;
if statement
if
statements are great for controlling the flow of the program. Normally a program is executed one instruction at a time, from top to bottom.
if
allow to take a decision and execute a set of instructions if the condition is met.
Executes the block of instructions between {} if condition is true
if (mouseX < width)
{
}
Executes the first block of instructions if condition is true, otherwise the second block
if (hour < 12)
{
}
else
{
}
Executing different blocks based on different conditions
In the following example, if the first condition is true, then the first block will be executed and the others not.
However, if the first condition is not true, the else if
is used to test another condition, and if is true, the block of that else if
is executed.
The block after the last else
is executed only if no other condition was true until that point.
if (minute <= 15)
{
}
else if(minute <= 30)
{
}
else
{
}
Note: You can have multiple else if
blocks in this kind of experessions.
for loop
Prints numbers from 0 to 4 using a for loop and println
for(let i = 0; i < 5; i++)
{
println(i);
}
Prints numbers from 10 down to 0 using a for loop
for(let i = 10; i >= 0; i--)
{
println(i);
}
Prints even numbers from 0 to 100
for(let i = 0; i <= 100; i+=2)
{
println(i);
}
Print all elements of an array
let ar = [10, 20, 30];
for(let element of ar)
{
println(element);
}
while loop
Print numbers from 0 to 9 using a while
loop
let i = 0;
while(i < 10)
{
println(i);
i++;
}
do while
Print numbers from 0 to 10 using a do while
loop
let i = 0;
do
{
println(i);
i++;
}
while(i < 10)
Note: do while
loop places condition after the code block, therefore the block can execute at least once even if the condition is false.
switch Statement
A switch
statement is another instruction besides if
/ else if
for controlling the flow of a program. You can use switch to compare an expression against different values and then run the coresponding set of instructions based if that expression is equal to any case
value.
Usually switch
is used less often than if
/ else if
/ else
.
switch(myExpresion)
{
case 100:
//...
break;
case 200:
//...
break;
case 300:
//...
break;
default:
//...
}
Functions
Functions are great for creating new language instructions
that you can use over and over again in a program.
Once you define a new instruction, it becomes indistinguishable from the built-in instructions present in JavaScript and codeguppy.com
Defining and calling the function balloon
// Function balloon draws a balloon using simple shapes such as circle and line
// It expects as arguments the coordinates for balloon center and the color of the balloon
function balloon(x, y, shapeColor)
{
let r = 30;
let stringLen = 100;
fill(shapeColor);
stroke(shapeColor);
circle(x, y, r);
line(x, y + r, x, y + r + stringLen);
}
// Call function balloon with different parameters
balloon(100, 100, "red");
balloon(300, 300, "blue");
balloon(500, 200, "yellow");
Functions that return values
function addNumbers(x, y)
{
return x + y;
}
// Call a function
var sum = addNumbers(100, 200);
println(sum);
Note: codeguppy.com includes a big number of built-in functions such as circle
, rect
, etc. You can call these functions in the same way you're calling your own custom function.
Array methods
Use an array to conveniently store a series of values using a single variable name. An array has properties and methods that allow to manipulate its elements.
Declaring and initializing ar
to an empty array
let ar = [];
Declaring and initializing ar
to an array of 3 numbers
let ar = [10, 20, 30];
Length of an array
let ar = [10, 20, 30];
println("Length of array: ", ar.length);
Append an element at the end of the array
let ar = [10, 20, 30];
ar.push(100);
println(ar);
Insert an element at the beginning of an array
let ar = [10, 20, 30];
ar.unshift(1);
println(ar);
Insert an element at an arbitrary position
let ar = [10, 20, 30];
// 1 -> after element with potion 1
// 0 -> delete 0 elements
// 15 -> insert number 15
ar.splice(1, 0, 15);
println(ar);
Insert an element at an arbitrary position (easy mode)
Note: The insert
array method is present only in codeguppy.com
let ar = [10, 20, 30];
ar.insert(1, 17);
println(ar);
Read the value of element 2
of an array
let ar = [10, 20, 30];
println(ar[2]);
Calculate the sum of elements of an array
let ar = [10, 20, 30];
let sum = 0;
for(let element of ar)
{
sum += element;
}
println(sum);
Assign a different value to al element of an array
let ar = [10, 20, 30];
ar[2] = 100;
println(ar);
Accesing the first element
let ar = [10, 20, 30];
println(ar[0]);
Accessing the last element
let ar = [10, 20, 30];
let len = ar.length;
println(ar[len - 1]);
Accessing the last element (easy way)
Note: The peek
array method is present only in codeguppy.com
let ar = [10, 20, 30];
println(ar.peek());
Remove the first element of the array
let ar = [10, 20, 30];
ar.shift();
println(ar);
Remove the last element of the array
let ar = [10, 20, 30];
ar.pop();
println(ar);
Remove an element at an arbitrary position
let ar = [10, 20, 30];
// 0 -> element index
// 1 -> number of elements to remove
ar.splice(0, 1);
println(ar);
Remove all elements of an array
let ar = [10, 20, 30];
// clear() is CodeGuppy specific
// use ar.lenght = 0; outside CodeGuppy
ar.clear();
println(ar);
Concatenate two arrays
// Merge / concatenate 2 arrays
let ar1 = ["a", "b", "c"];
let ar2 = ["d", "e", "f"];
let ar = ar1.concat(ar2);
println(ar);
Extract a slice of an array
slice()
is an interesting method that can be used to extract a "slice" from an array. The "slice" will be retured as an independent array. The method receives as arguments the index of the first element (inclusive) and the index of the last element that we want in the slice (exclusive):
let ar = ["a", "b", "c", "d", "e", "f"];
// Extracting a 'slice' from an array
let arSlice = ar.slice(2, 4);
println(arSlice);
Joining elements of an array
let ar = ["a", "b", "c", "d", "e", "f"];
// Join all elements in a string using separator ;
let s = ar.join(";");
println(s);
String methods
Just like with arrays, you can access and manipulate independent characters within a string.
Length of a string
let txt = "JavaScript";
println(txt.length);
Iterating all characters of a string
let txt = "JavaScript";
for(let chr of txt)
{
println(chr);
}
Accessing string characters by position
let txt = "JavaScript";
for(let i = 0; i < txt.length; i++)
{
println(txt[i]);
}
Converting text to uppercase
let txt = "JavaScript";
txt = txt.toUpperCase();
println(txt);
Converting text to lowercase
let txt = "JavaScript";
txt = txt.toLowerCase();
println(txt);
Determine if the string contains another substring
let txt = "Coding is cool!";
let search = "cool";
if (txt.includes(search))
{
println(search + " was found in " + txt);
}
Determine if the string starts with a specified prefix
let txt = "JavaScript is cool!";
let search = "JavaScript";
if (txt.startsWith(search))
{
println(txt + " starts with " + search);
}
Determine if the string ends with a specified sufix
let txt = "JavaScript is cool!";
let search = "!";
if (txt.endsWith(search))
{
println("It is an exclamation!");
}
Find the position of a substring. Search starts at the beginning
let txt = "JavaScript is cool!";
let search = "cool";
let foundAt = txt.indexOf(search);
if (foundAt < 0)
println("Not found!");
else
println("Found at position " + foundAt);
Find the position of a substring. Search starts at specified index.
let txt = "JavaScript is cool! Super cool!";
let search = "cool";
let startAt = 18;
let foundAt = txt.indexOf(search, startAt);
if (foundAt < 0)
println("Not found!");
else
println("Found at position " + foundAt);
Extract a substring from the string
let txt = "JavaScript is cool!";
let index1 = 14;
let index2 = 18;
let txt2 = txt.substring(index1, index2);
println(txt2);
Remove whitespaces from beginning and end of the string
let txt = " I love coding ! ";
txt = txt.trim();
println("'" + txt + "'");
Remove whitespaces from beginning of the string
let txt = " I love coding ! ";
txt = txt.trimStart();
println("'" + txt + "'");
Remove whitespaces from the end of the string
let txt = " I love coding ! ";
txt = txt.trimEnd();
println("'" + txt + "'");
Pads the start of the string with another string
let no = 3;
let txt = no.toString(2).padStart(8, '0');
println(txt);
Pads the end of the string with another string
let n1 = "1";
let n2 = "3";
txt = n1 + "." + n2.padEnd(4, '0');
println(txt);
Codes of characters
let txt = "JavaScript";
for(let chr of txt)
{
// Obtain the Unicode code point value
// ... identical to ASCII code for the range of ASCII values
let code = chr.codePointAt(0);
let line = chr + "\t" + code.toString() + "\t" + code.toString(16).toUpperCase() + "\t" + code.toString(2).padStart(7, "0");
println(line);
}
Characters from codes
let msg = "73 32 76 79 86 69 32 67 79 68 73 78 71"
let base = 10;
let arMsg = msg.split(" ");
for(let i = 0; i < arMsg.length; i++)
{
if (!arMsg[i])
continue;
let code = parseInt(arMsg[i], base);
// Obtain the character from the Unicode code point
// (the Unicode code point is the same with ASCII code for the range of ASCII values)
let chr = String.fromCodePoint(code);
println(chr);
}
Random numbers
Random numbers are extremly useful in coding.
To obtain a random number in JavaScript between 0
(inclusive) and 1
(exclusive) you can use Math.random()
function.
let r = Math.random();
println(r);
codeguppy.com extends the support for random numbers with additional instructions that let you quickly pick a random number in the prefered range.
Random floating point number between 0 and 1 (1 not included)
This is the same as Math.random()
let n = random();
println(n);
Random floating point number between 0 and n (n not included)
let n = random(100);
println(n);
Random floating point number between n1 and n2 (n2 not included)
let n = random(-100, 100);
println(n);
Random int between min and max (both included)
You can use either randomInt
or randomNumber
let n = randomInt(0, 10);
println(n);
Random char between chr1 and chr2 (both included)
function randomChar(chr1, chr2)
let char = randomChar("A", "Z");
println(char);
Random element of an array
let ar = ["J", "a", "v", "a", "S", "c", "r", "i", "p", "t"];
let char = random(ar);
println(char);
Shuffle an array
let ar = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let ar2 = ar.shuffle();
println(ar2);
Modules
To better organize your code, especially in bigger programs, codeguppy.com introduces the concept of modules.
Instead of writing all the functions of a program in a single code page, you can split them into several code pages, each code page becoming in this way a module.
A module provides strong encapsulation for variables and functions defined inside. This encapsulation allows you to define functions / variables with same name in different modules.
To use the functions inside a module, you need first to require
that module.
Main program
const math = require("MathUtils");
let sum = math.add(2, 3);
let prod = math.prod(3, 4);
println(sum);
println(prod);
Module MathUtils
content
function add(a, b)
{
return a + b;
}
function prod(a, b)
{
return a * b;
}
Note: Another use for code pages is for defining game scenes. codeguppy.com has a built-in game scene manager. Please refer to the Game Development article for more details.
Chapter 2: Drawing on canvas using JavaScript
codeguppy.com is a great environment for graphical based activities using both cartesian and turtle graphics.
About canvas
In codeguppy.com, the graphical canvas is 800 x 600 pixels.
The system is automatically initializing the width
and height
variables with the dimensions of the canvas
It is recommended to use these variables in your program instead of hardcoding constants (whenever is possible).
println(width);
println(height);
Clearing the canvas
clear() is used to clear the drawing canvas. This function is very useful for animations, inside the loop()
event, to clear the frame before the next draw.
clear();
Background color
The background
command is used to set the background color of the canvas.
💡 The background
command is not erasing the shapes drawn on the canvas. To erase the canvas, use clear()
instead.
Set the background color to a built-in color specified as a string
background("navy");
Set the background color to a color specified as a hex "#RRGGBB" string
background("#F012D3");
Set the background color to a gray color (0 - black, 255 - white)
background(255);
Note: In codeguppy.com you can set even an image as the background. Please refer to the "Games" page for more details about how to set an image as a background.
Drawing shapes
Draw a circle at coordinates 400 x 300 and radius of 200 pixels
circle(400, 300, 200);
Draw an ellipse at coordinates 400 x 300 and width and height of 300 x 200 pixels
ellipse(400, 300, 300, 200);
Draw a rectangle having the top-left corner at coordinates 400 x 300 and width and height of 300 x 200 pixels
rect(400, 300, 300, 200);
Draw a line between coordinates 400 x 300 and 500 x 500
line(400, 300, 500, 500);
Draw a triangle by specifying each corner coordinates
triangle(400, 100, 200, 400, 600, 500);
Draw an arc
To draw an arc, you specify the coordinates as for an ellipse (center position, width and height) and in addition you specify the start and end angle.
arc(400, 300, 300, 200, 0, 180);
Draw a point at coordinates 400 x 300
point(400, 300);
Draw text JavaScript at coordinates 400 x 300
text('JavaScript', 400, 300);
Shape settings
Note: Once set, these settings will be applied to all successive shape drawn on the canvas
Set the size of text to 20
textSize(20);
text("JavaScript", 400, 300);
Set "Magenta" as the color to fill shapes
fill('Magenta');
circle(400, 300, 100);
Set "Teal" as the color to draw shapes
stroke('Teal');
circle(400, 300, 100);
Set the line thickness to 2 px
strokeWeight(2);
circle(400, 300, 100);
Draw empty shapes, without fill color
noFill();
circle(400, 300, 100);
Draw shapes without an outline
noStroke();
fill("lightblue");
circle(400, 300, 100);
Turtle Graphics
codeguppy.com allows you to combine cartesian graphics with turtle graphics.
When working with Turtle Graphics, you can use the default turtle (recommended for beginners and regular programs) or create additional turtles (for complex programs).
Working with the default Turtle
To use the default turtle, all you need to do is to use the following global instructions
.
Reset the default turtle to home position
home();
Sets to Red
the pen color of the default turtle
pencolor("Red");
Sets to 2 the pen size of the default turtle
pensize(2);
Put the pen on the paper. The turtle will draw.
pendown();
Raise the pen from the paper. The turtle will advance but not draw
penup();
Move the turtle to an arbitrary position on the canvas
setposition(100, 100);
Turns the default turtle to the left by the number of specified degrees
left(30);
Turns the default turtle to the right by 30 degrees
right(30);
Sets the turtle heading (direction) to an arbitrary angle
setheading(180);
Moves the turtle forward by number of specified pixels.
Note: The turtle moves in the direction that was previosly set with left
, right
or setheading
. If the pen is on the paper, the turtle will draw.
forward(100);
Moves the turtle back by number of specified pixels.
Note: The turtle moves in the oposite direction than would move with forward
back(100);
Retrieve the x and y position of the default turtle as an array of 2 numbers
let p = position();
println(p[0]);
println(p[1]);
Retrieve the default turtle direction in degrees
let angle = heading();
println(angle);
Working with multiple turtles
In complex programs, you may find useful to work with multiple turtles, since each of them maintains their own state such as position, color, etc.
Create multiple turtles
let t1 = createTurtle();
let t2 = createTurtle();
t1.pencolor("Red");
t1.forward(100);
t2.pencolor("Blue");
t2.right(90);
t2.forward(100);
Get the default turtle
let t = getDefaultTurtle();
t.forward(100);
Colors
As observed in the above examples, codeguppy.com allow users to specify colors in a variaty of ways. In this way, you can use the most convenient method for your program.
Named colors
There are a variaty of colors with predefined names in codeguppy.com You can explore all of them on the "Backgrounds" pallete.
fill("Red");
circle(400, 300, 100);
RGB / HTML style colors
When predefined colors are not enough, you can create any color by specifying the Red
, Green
and Blue
ammounts. You can pass these colors as strings to fill
and stroke
functions using the #RRGGBB
format:
fill("#F3E2B5");
circle(400, 300, 100);
Quick gray colors
If you need to quickly create a shade of gray, just pass a number from 0
to 255
to any function that expects a color such as fill
or stroke
fill(100);
circle(400, 300, 100);
Colors using the color()
function
Another way to create a color is by using the color
function and the R, G, B ammounts. These ammounts are in the range of 0
to 255
let myColor = color(100, 200, 150);
fill(myColor);
circle(400, 300, 100);
Changing to HSB
mode
By default, codeguppy.com color system is using the RGB mode, where colors are specified by R, G, B ammounts (as seen above).
However, advanced users can switch to HSB
mode, where colors are specified by Hue, Saturation and Brightness.
In HSB
mode, the values for color
function are in the interval 0
- 360
colorMode(HSB);
let c1 = color(100, 50, 300);
fill(c1);
circle(300, 300, 50);
let c2 = color(100, 300, 300);
fill(c2);
circle(500, 300, 50);
Changing back to RGB
mode
colorMode(RGB);
Angles
All the trigonometric functions, as well as certain drawing functions such as arc
are working with angles.
To appeal to young coders and beginners, all angles in codeguppy.com are in "DEGREES" by default.
However, advanced users can switch to "RADIANS" mode by using angleMode
. Don't forget to switch back to "DEGREES" when done working with RADIANS.
angleMode(RADIANS);
arc(400, 150, 300, 200, 0, PI);
angleMode(DEGREES);
arc(400, 350, 300, 200, 0, 180);
Using trigonometric functions
Via the p5.js library, codeguppy.com offers users a series of easy to use trigonometric functions such as sin
, cos
, etc.
textSize(40);
let x = 0;
function loop()
{
let y = 300 + 50 * sin(frameCount);
x++;
clear();
text("Hello, World", x, y);
}
Animations
To implement animations, codeguppy.com offers users a method similar to the one use by "cartoons": think of your animation as a series of frames! All you have to do is to draw the first frame, then erase and draw the second frame in a slightly different position, and so on!
loop() is at the base of animations
In codeguppy.com, function loop()
is special. All you have to do is to define this function in your code, and the codeguppy.com engine will run it for you up to 60 times per second! There is no need to call it yourself.
Move an horizontal line on the screen
let y = 0;
function loop()
{
// Clear the frame
clear();
// Draw the frame
line(0, y, 800, y);
// Update the state
y++;
if (y > 600)
y = 0;
}
Bounce a circle on the screen
let x = 400;
let y = 300;
let dx = 1;
let dy = 1;
let speed = 3;
function loop()
{
// Clear the frame
clear();
// Draw the frame
circle(x, y, 10);
// Update the state
x += speed * dx;
y += speed * dy;
if (x < 0 || x > width)
dx *= -1;
if (y < 0 || y > height)
dy *= -1;
}
Change the default frame rate
frameRate(30);
textSize(40);
let n = 0;
function loop()
{
clear();
text(n, 400, 300);
n++;
}
Obtain the frame rate
function loop()
{
clear();
text(frameRate(), 400, 300);
}
Chapter 3: User Input
There are two main ways to get keyboard/ mouse user input into a codeguppy.com program: via events or via the loop()
function by reading built-in system variables and functions.
Events
codeguppy.com engine can notify your program when a keyboard or mouse event occurs. All you have to do is to define the appropriate function (e.g. event handler
) in your program and the system will call it automatically when that event appears.
keyPressed event
Executes once when a key is pressed
function keyPressed()
{
clear();
text(key, 400, 300);
text(keyCode, 400, 320);
}
keyReleased event
Executes when a key is released
function keyReleased()
{
clear();
text(key, 400, 300);
text(keyCode, 400, 320);
}
keyTyped event
Executes when a key is typed execept for special keys
function keyTyped()
{
clear();
text(key, 400, 300);
text(keyCode, 400, 320);
}
mouseClicked event
Executes once when the mouse is pressed and released
function mouseClicked()
{
circle(mouseX, mouseY, 10);
}
mousePressed event
Executes once when the mouse button is pressed
function mousePressed()
{
stroke("red");
circle(mouseX, mouseY, 10);
}
mouseReleased event
Executes when the mouse button is released
function mouseReleased()
{
stroke("blue");
circle(mouseX, mouseY, 10);
}
mouseMoved event
Executes when the mouse is moved and button is not pressed
function mouseMoved()
{
line(mouseX, mouseY, pmouseX, pmouseY);
}
mouseDragged event
Executes when the mouse is moved an a button is pressed
function mouseDragged()
{
line(mouseX, mouseY, pmouseX, pmouseY);
}
doubleClicked event
Executes when the mouse is double clicked
function doubleClicked()
{
circle(mouseX, mouseY, 10);
}
mouseWheel event
Executes when the user uses the mouse wheel or touchpad
function mouseWheel()
{
}
System variables
Besides events, the system also populates automatically some system variables with appropriate event data.
You can access these variables from within the event handlers or from within the main animation / game loop()
.
This is usually the prefered way of getting user input when building games.
keyIsPressed
Boolean system variable that indicates if a key is pressed.
noStroke();
text("Press any key to change color", 10, 10);
function loop()
{
let color = keyIsPressed ? "Red" : "Green";
clear();
fill(color);
circle(400, 300, 100);
}
key
System variable containing the last typed key.
function keyPressed()
{
if (key.toLowerCase() === "s")
{
showScene("Game");
}
}
keyCode
System variable containing the code of the last key pressed.
The following constasts can be used instead of a numeric key code: LEFT_ARROW
, RIGHT_ARROW
, UP_ARROW
, DOWN_ARROW
. Use them without quotes.
function keyPressed()
{
let ENTER_KEYCODE = 13;
if (keyCode === ENTER_KEYCODE)
{
showScene("Game");
}
}
Note: To find the keyCodes you can write a test program or use a site such as keycode.info.
mouseX
System variable containing the horizontal coordinate of the mouse coursor.
function loop()
{
if (mouseIsPressed)
line(mouseX, mouseY, pmouseX, pmouseY);
}
mouseY
System variable containing the vertical coordinate of the mouse coursor
function loop()
{
if (mouseIsPressed)
line(mouseX, mouseY, pmouseX, pmouseY);
}
pmouseX
System variable containing the previous horizontal coordinate of the mouse coursor
function loop()
{
if (mouseIsPressed)
line(mouseX, mouseY, pmouseX, pmouseY);
}
pmouseY
System variable containing the previous vertical coordinate of the mouse coursor.
function loop()
{
if (mouseIsPressed)
line(mouseX, mouseY, pmouseX, pmouseY);
}
mouseIsPressed
Boolean system variable indicating if any mouse button is pressed.
To detect which button is pressed check mouseButton
variable.
function loop()
{
if (mouseIsPressed)
line(mouseX, mouseY, pmouseX, pmouseY);
}
mouseButton
System variable containing the pressed mouse button. It has one of these values LEFT
, RIGHT
, CENTER
.
To detect if mouse is pressed check mouseIsPressed
.
function loop()
{
let drawColor = mouseButton === LEFT ? "Red" : "Blue";
stroke(drawColor);
if (mouseIsPressed)
line(mouseX, mouseY, pmouseX, pmouseY);
}
Functions
keyIsDown()
Use keyIsDown()
function inside the loop()
event to detect if the specified key is pressed. You need to specify the key code.
The following constasts can be used instead of a numeric key code: LEFT_ARROW
, RIGHT_ARROW
, UP_ARROW
, DOWN_ARROW
. Use them without quotes.
let shipX = width / 2;
function loop()
{
if (keyIsDown(LEFT_ARROW))
shipX -= 10;
else if (keyIsDown(RIGHT_ARROW))
shipX += 10;
draw();
}
function draw()
{
clear();
noStroke();
fill("Black");
text("Use LEFT and RIGHT arrows to move the ship", 10, height - 5);
fill("Magenta");
rect(shipX, height - 40, 100, 20);
}
Note: To find key codes you can use a site such as keycode.info
keyWentDown()
keyWentDown()
is also intended for loop()
event and is similar to keyIsDown()
.
The difference is that this function returns true
just once per key pressed. To retrigger the function, the user need to release the key and press it again:
Chapter 4: JavaScript Game Development with codeguppy.com
Game development is extremely easy and fun with codeguppy.com. The system comes with built-in background images, sprites, music and sound effects to allow you to focus on the code rather than searching for assets.
Drawing Layers
codeguppy.com has a layered drawing architecture. There are up to 5 drawing layers on top of the canvas at any time as shown in the following diagram:
The engine combines automatically all the layers and displays the final image on the screen.
Setting Background Images
The background
command was also presented in the "Drawing" section as a way to set the background color of the canvas, like this:
background('LightBlue');
However, background command can do more than just setting a plain color as a background.
Using the same function, you can set any image from the codeguppy.com library as background:
background('Summer');
💡 To set the background to an image, open the "Backgrounds" palette, and drag and drop an image in the code area. The system will write the appropriate code for you.
The
background
commands sets the image in the Background layer as presented in the above diagram. In this way the background image won't be erased or altered byclear()
instruction or shape drawing instructions or even sprites.
Sprites
Sprites are small images, often animated, that you can load and manipulate through the code. Sprites are an essential ingredient of a succesful game.
codeguppy.com contains a big library of built-in sprites, and in the same time it offers the user the ability to define custom sprites.
Loading Built-in Sprites
You can load any sprite from the built-in library using the sprite
command.
Loading a sprite
The sprite
instruction will load the built-in sprite plane
and place it in the middle of the screen.
background('Summer');
sprite('plane');
💡 Open the Sprites palette and browse all the included built-in sprites. When you find one that you like, drag and drop it in the code editor and the system will write the code automatically.
Loading and positioning a sprite
background('Summer');
sprite('plane', 400, 200);
Loading and scaling a sprite
In the following code snippet, the sprite plane
is scalled to 0.5
before being placed in the middle of the screen
background('Summer');
sprite('plane', 0.5);
Loading, positioning and scaling of a sprite
In the following code snippet, the sprite plane
is scalled to 0.5
before being placed in the middle of the screen
background('Summer');
sprite('plane', 400, 150, 0.5);
Loading a particular animation of a sprite
For multi-animation sprites, you can specify the default animation at load time by including it in the same string as the sprite name using a .
symbol (e.g. plane.shoot
)
💡 You can discover what animations are supported by each sprite, by hovering the mouse over sprites in the "Sprites" palette. Check the information provided in the tooltip.
background('Summer');
sprite('plane.shoot', 400, 150, 0.5);
Note: For sprites with multiple animations, you can also change the displayed animation later-on using the sprite
.show()
method.
Loading custom sprites
For games that required custom graphics, users can define additional custom sprites directly in the code. codeguppy.com uses the Microsoft MakeCode Arcade format for custom sprites with up to 16 colors.
From text to images
Use img
in a string template, or as a function, to convert a custom-sprite text to an image:
From images to sprites
Custom sprites can also be loaded using the sprite
command. In this way you can manipulate them like the rest of built-in sprites:
Animated custom sprites
A custom sprite can also be animated. If you need animated sprites, then you need to create multiple frame images for each sprite:
Custom sprites with multiple animations
You can even pack multiple animations in a custom sprite. This help you change later on the animations using the sprite .show()
method:
Custom palette for custom sprites
If your program required different colors, you can define a custom palette using setPalette
.
Note: You can obtain the current palette at any time using the getPalette()
function.
Manipulating sprite properties
At runtime, the custom sprites are indistinguishable from the built-in sprites. No matter how you loaded / created the sprite, you can manipulate it in the same way through the code.
The sprite
command is returning a reference to an object on which you can invoke methods and properties.
Set sprite position
The sprite
command is returning a reference to a sprite object. Use the .x
and .y
properties to update the sprite position on the screen.
let player = sprite('adventure_girl.idle', 400, 300, 0.5);
player.x = 100;
player.y = 100;
Moving sprites automatically
Instead of changing the .x
and .y
coordinates yourself, you can let the engine move the sprite automatically on x or y axes by specifying a value for the appropriate .velocity
.
let plane = sprite('plane.fly', 0, 100, 0.5);
plane.velocity.x = 1;
Mirroring Sprites
Sometimes you need to flip a sprite on either .x
axis or .y
axis.
To mirror a sprite use the .mirror
method with -1
as argument. To mirror it to the original direction use 1
as argument.
plane.mirrorX(-1);
Sprite rotation
In certain games and programs, you may want to rotate your sprites at an arbitrary angle. You can do this using the .rotation
property which allow you to specify a rotation angle.
Rotate sprites automatically
If you want the sprite to rotate automatically for an indefinite time, you can put it on autorotate by giving a greater than zero value to .rotationSpeed
property:
Drawing depth
Normally, newly added sprites are drawn on top of the previous ones.
To control which sprite is drawn on top, and which one is drawn behind, you can make use of the .depth
property. Sprites with lower depth are drawn behind the ones with higher depth.
You can also combine sprites with classical shaped drawn using graphical APIs (circle
, rect
, etc.).
If you want sprites to appear behind the graphical plane, make sure you give sprites a negative depth, otherwise they will be drawn on top of the graphical plane.
Changing animations
If the sprite you selected contains multiple animations, you can specify what animation you want to display initially by adding the animation name with a .
in the string of the first parameter:
let player = sprite('adventure_girl.idle', 400, 300, 0.5);
However, later one, you can change the animation of that sprite using the .show
method:
player.show('run');
💡 Please check carefully the animations supported by a sprite by hovering over the sprite thumbnail in the Sprites palette.
Mouse events on sprites
You can detect mouse clicks on sprites by assigning an event handler (e.g. function) to the following sprite properties:
.onMousePressed
.onMouseReleased
.onMouseOver
.onMouseOut
Hiding sprites
You can hide a sprite in two ways:
- Setting the
.visible
property to false - Setting the
.x
and / or.y
coordinates outside of the visible canvas
let p = sprite('adventure_girl.idle', 400, 300, 0.5);
function mouseClicked()
{
p.visible = !p.visible;
}
Removing sprites
To permanently remove a sprite from the program, use the .remove()
method on the sprite. This is useful for sprites just as destroyed enemies, collected items, etc.
You can also make a sprite auto-remove after a certain number of frames using the .life
property. This is useful for objects such as bullets, rockets, etc. that you shoot and forget about them. Collectibles can make use of this property. By default this property has value -1
(disabled).
Sprite Collisions
There are 4 different methods to verify if sprites are colliding:
sprite.collide(target, callback);
sprite.displace(target, callback);
sprite.overlap(target, callback);
sprite.bounce(target, callback);
When called, some of these methods are automatically displacing the sprites, others are impacting their trajectories. They all return a Boolean indicating if the collision happened.
Experiment with these methods to discover their behaviors!
Parameters:
target
– this is a reference to the other sprite or group of sprites (more about groups later)callback
– this is optional, but useful in some cases. Callback is a function with the following signature, that gets called automatically in case of collision:
function onCollide(spr, target)
{
score++;
}
Note: Another way to check collisions between sprites, or between sprites and other shapes is by using the following shape collision functions.
Sprite groups
In games with multiple sprites of the same kind, it is sometimes useful to group various sprites in a single group created with new Group()
Main methods of a group are:
.add(sprite)
- Add a sprite to the group.remove(sprite)
– Removes a sprite from the group.clear()
- Removes sprites from group. Does not remove sprites from program..contains(sprite)
- Check if the specified sprite is in the group
Note: Certain methods, such as sprite collision methods can operate on an entire group of sprites, rather than on a single sprite (as explained on the previous page).
Background Music
Play music named Rainbow
music('Rainbow');
Note: If any music was playing before, the music
instruction interrupts that before playing the new music.
Play music named "Fun Background" at volume 0.1
music('Fun Background', 0.1);
💡 Use the "Music and Sounds" palette to discover music. When you find something that you like, drag and drop the song in the code area. The system will write the appropriate code for you.
Sound Effects
Play sound zap1
sound('zap1');
Note: The system plays in parallel all sounds triggered with the sound
command.
💡 Use the "Music and Sounds" palette to discover sound effects. When you find something that you like, drag and drop the song in the code area. The system will write the appropriate code for you.
Collisions between shapes
💡 If your game is using only sprites, then we recommend you to use sprite collision methods.
However, if you are not using sprites, or if you use sprites in combination with regular shapes, you can use the following methods to detect collisions. They take as arguments the parameters of the two shapes and return true
if the two shapes collide.
Note: For convenience, some instructions are define twice, with the arguments describing the shaped inversed.
Detect collision between point and circle
Use any of these instructions to detect the collision between a point and a circle:
collisionPointCircle(pointX, pointY, circleX, circleY, circleR)
collisionCirclePoint(circleX, circleY, circleR, pointX, pointY)
Detect collision between point and line
Use any of these two instructions to detect the collision between a point and a line:
collisionPointLine(pointX, pointY, lineX1, lineY1, lineX2, lineY2)
collisionLinePoint(lineX1, lineY1, lineX2, lineY2, pointX, pointY)
Detect collision between a point and a rectangle
Use any of the following two instructions to detect collisions between a point and a rectangle:
collisionPointRect(pointX, pointY, rectX, rectY, rectWidth, rectHeight)
collisionRectPoint(rectX, rectY, rectWidth, rectHeight, pointX, pointY)
Detect collision between two circles
Use the following instruction to detect collisions between two circles:
collisionCircleCircle(circle1X, circle1Y, circle1R, circle2X, circle2Y, circle2R)
Detect collision between a circle and a rectangle
Use any of the following two instructions to detect collisions between a circle and a rectangle:
collisionCircleRect(circleX, circleY, circleR, rectX, rectY, rectWidth, rectHeight)
collisionRectCircle(rectX, rectY, rectWidth, rectHeight, circleX, circleY, circleR)
Detect collision between two rectangles
Use the following instruction to detect collision between two rectangles:
collisionRectRect(rect1X, rect1Y, rect1Width, rect1Height, rect2X, rect2Y, rect2Width, rect2Height)
Detect collision between two lines
Use this instruction to detect collisions between two lines:
collisionLineLine(x1, y1, x2, y2, x3, y3, x4, y4)
Detect collision between a line and a rectangle
Use any of the following two instructions to detect collisions between a line and a rectangle:
collisionLineRect(x1, y1, x2, y2, x3, y3, w, h)
collisionRectLine(x3, y3, w, h, x1, y1, x2, y2)
The Game Loop
In virtually all games, you have to define a "game loop" - a special function that continously gets the user input, updates the game state and renders the game graphics.
In codeguppy.com you can easily implement the "game loop" using the loop()
function. This is the same function described on the "Drawings" page in the "Animations" section. All you have to do is to define this function in your code, and the codeguppy.com engine will run it for you up to 60 times per second! There is no need to call it yourself.
If your game is using only sprites
To make your character move on the screen, read the keyboard and update character state (e.g. position) inside the loop()
If your games is using sprites and shapes
If your game uses also classical shapes, then you need to re-render those inside the loop
function. Sprites are rendered automatically when you change their properties.
Think of your games as a series of frames! Start by drawing the first frame, then erase it and draw the second frame in a slightly different position, and so on!
Preloading Assets
codeguppy.com engine automatically scans your code prior to execution to identify what assets (e.g. background, sprites, music, sound effects) need to be loaded. The engine identify these by looking into the corrsponding background
, sprite
, music
and sound
commands you used.
If these commands don't specify the asset as a constant, then you need to preload the required assets using the preload
function. Just list all required assets comma separated:
preload("adventure_girl", "knight", 'Fun Background');
myMusic = "Fun" + " " + "Background";
music(myMusic);
createPlayer("adventure_girl");
createPlayer("knight");
function createPlayer(spriteName)
{
return sprite(spriteName, random(width), 300, 0.5);
}
Multi-Scene Games
Support for building multi-scene games is one of the main highlight of codeguppy.com environment!
By adding more scenes to a game, you're game will appear more polished. In the typical game, you may want to create an "Intro" scene to explain how to play the game, the actual "Game" scene and the "Congrats" scene that shows the congratulations / score after you finish the game.
Each scene is created in a new code page. Make sure you name the code pages appropriately since we need to refer to them later.
Showing a scene
When the program starts it will always run the first scene you define. To show other scene you need to use the showScene
method:
function mouseClicked()
{
showScene("Game");
}
The enter event
If your scene contains a function named enter
, then the engine will automatically run this function when a scene is entered / shown. In a typical game a scene may be shown more than once during the game. For instance the "Game" scene will be shown each time the user restarts the game from the "Intro" scene.
This gives you the ability to set the scene state appropriately.
Note: The loose code outside functions is executed just once per scene. Successive displays of the scene won't trigger that code anymore.
background("Red");
let score;
function enter()
{
score = 0;
}
Passing data to a scene
In certain cases, it is useful to pass data to a scene via the showScene
method. For instance you can pass the game options from the "Intro" scene to the "Game" scene, or the player score from the "Game" scene to the "Congrats" scene.
Passing a number (e.g. score) to "Congrats" scene
showScene("Congrats", 1000);
Inside the "Congrats" scene, you can retrieve this passed data in the following way:
function enter()
{
let score = sceneArgs;
text(score, 400, 300);
}
Passing a complex structure to "Congrats" scene
let data = {
score : 1000,
time : 10,
bonusPoints : 100
}
showScene("Congrats", data);
Inside the "Congrats" scene, you can retrieve this passed data in the following way:
function enter()
{
let data = sceneArgs;
text("Score: " + data.score, 400, 300);
text("Time: " + data.time, 400, 320);
text("Bonus Points: " + data.bonusPoints, 400, 340);
}
Further reading
For a deeper understanding on how to work with sprites in codeguppy.com, please consult these tutorials:
- Working with built-in sprites playground and tutorial
- Working with custom sprites playground and tutorial
Chapter 5: Other coding hints
codeguppy.com can also be used to practice algorithms or implement programs with basic data input UI. This article describes the support for this kind of programs.
Printing data
Use the print
and println
instructions to quickly print numbers, strings and other information on top of the canvas. These instructions operates on a separate scrollable text layer.
These instructions are perfect for debugging programs, for practicing language elements or algorithms:
Print the numbers from 0 to 9
for(let i = 0; i < 10; i++)
{
println(i);
}
Print the first 10 prime numbers
Note:
println
is adding a new line character after each print, while
Building data input UIs
codeguppy.com offers simple instructions for creating data input user interfaces.
Creating input boxes
To create a single-line input box, use the createEdit
instruction, specifying the control position and width.
text("Your name", 300, 90);
let nameBox = createEdit(300, 100, 200);
To create a multi-line input box, you also need to specify the height. If you omit the height parameter, then the system will automatically build a single-line input box.
text("Comments", 300, 190);
let commentsBox = createEdit(300, 200, 300, 100);
Note that the createEdit
instruction is returning a reference to the edit box object. You can use the following properties to manipulate edit box content.
.text
.readonly
.visible
.width
.height
.onchange
Example:
noStroke();
fill(0);
text("Your name", 300, 90);
let nameBox = createEdit(300, 100, 200);
text("Comments", 300, 190);
let commentsBox = createEdit(300, 200, 300, 100);
nameBox.onchange = handleNameChange;
function handleNameChange()
{
commentsBox.text = "Hello " + nameBox.text;
}
Creating buttons
Another UI element that you can create in the UI layer is a regular push button.
let btn = createButton(505, 100, 60, 20);
btn.text = "Enter";
The createButton
instruction is returning a reference to the created button object. You can use this reference to access properties such as:
.text
.visible
.disabled
.width
.height
.onclick
Example:
JavaScript is an essential tool for building interactive and dynamic applications, and understanding its core concepts is the first step toward mastering this powerful language. This guide introduced key JavaScript fundamentals, offering a quick, practical reference for variables, loops, functions, and more. By practicing on codeguppy.com, learners can take their newfound knowledge and apply it directly to coding exercises, deepening their understanding through hands-on experience. As you continue exploring JavaScript, remember that consistent practice and experimentation are key to becoming proficient and unlocking the full potential of creative coding.
Read more blog articles Browse JavaScript projectsAbout codeguppy
CodeGuppy is a FREE coding platform for schools and independent learners. If you don't have yet an account with codeguppy.com, you can start by visiting the registration page and sign-up for a free account. Registered users can access tons of fun projects!
Follow @codeguppy on Twitter for coding tips and news about codeguppy platform. For more information, please feel free to contact us.