JavaScript est l'un des langages de programmation les plus polyvalents et un outil essentiel pour le codage créatif, le développement de jeux et le développement Web. Que vous soyez débutant ou que vous cherchiez à rafraîchir vos connaissances, ce guide offre un aperçu rapide des concepts fondamentaux de JavaScript, conçu pour vous aider à démarrer. Vous apprendrez également à tirer parti de codeguppy.com, une plateforme de codage en ligne adaptée aux débutants, pour mettre en pratique vos compétences. Des variables aux boucles et fonctions, cet article-book sert de référence pour démarrer rapidement avec JavaScript.
Commençons notre article par explorer la syntaxe JavaScript.
Variables are used to store data such as numbers, strings (text) or even complex objects. Remember:
let x;
let x = 1;
let s = "Hello, World!";
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.
x = 100;
s = "Hello";
ar = [];
ar = [1, 2, 3];
ar = ["A", "B"];
o = { Type: 'car', x : 100, y : 200 };
sum = a + b;
avg = (a + b) / 2;
sum = sum + 10;
i++;
i += 2;
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.
if (mouseX < width) { }
if (hour < 12) { } else { }
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(let i = 0; i < 5; i++) { println(i); }
for(let i = 10; i >= 0; i--) { println(i); }
for(let i = 0; i <= 100; i+=2) { println(i); }
let ar = [10, 20, 30]; for(let element of ar) { println(element); }
let i = 0; while(i < 10) { println(i); i++; }
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.
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 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
// 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");
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.
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.
let ar = [];
let ar = [10, 20, 30];
let ar = [10, 20, 30]; println("Length of array: ", ar.length);
let ar = [10, 20, 30]; ar.push(100); println(ar);
let ar = [10, 20, 30]; ar.unshift(1); println(ar);
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);
Note: The insert array method is present only in codeguppy.com
let ar = [10, 20, 30]; ar.insert(1, 17); println(ar);
let ar = [10, 20, 30]; println(ar[2]);
let ar = [10, 20, 30]; let sum = 0; for(let element of ar) { sum += element; } println(sum);
let ar = [10, 20, 30]; ar[2] = 100; println(ar);
let ar = [10, 20, 30]; println(ar[0]);
let ar = [10, 20, 30]; let len = ar.length; println(ar[len - 1]);
Note: The peek array method is present only in codeguppy.com
let ar = [10, 20, 30]; println(ar.peek());
let ar = [10, 20, 30]; ar.shift(); println(ar);
let ar = [10, 20, 30]; ar.pop(); println(ar);
let ar = [10, 20, 30]; // 0 -> element index // 1 -> number of elements to remove ar.splice(0, 1); println(ar);
let ar = [10, 20, 30]; // clear() is CodeGuppy specific // use ar.lenght = 0; outside CodeGuppy ar.clear(); println(ar);
// Merge / concatenate 2 arrays let ar1 = ["a", "b", "c"]; let ar2 = ["d", "e", "f"]; let ar = ar1.concat(ar2); println(ar);
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);
let ar = ["a", "b", "c", "d", "e", "f"]; // Join all elements in a string using separator ; let s = ar.join(";"); println(s);
Just like with arrays, you can access and manipulate independent characters within a string.
let txt = "JavaScript"; println(txt.length);
let txt = "JavaScript"; for(let chr of txt) { println(chr); }
let txt = "JavaScript"; for(let i = 0; i < txt.length; i++) { println(txt[i]); }
let txt = "JavaScript"; txt = txt.toUpperCase(); println(txt);
let txt = "JavaScript"; txt = txt.toLowerCase(); println(txt);
let txt = "Coding is cool!"; let search = "cool"; if (txt.includes(search)) { println(search + " was found in " + txt); }
let txt = "JavaScript is cool!"; let search = "JavaScript"; if (txt.startsWith(search)) { println(txt + " starts with " + search); }
let txt = "JavaScript is cool!"; let search = "!"; if (txt.endsWith(search)) { println("It is an exclamation!"); }
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);
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);
let txt = "JavaScript is cool!"; let index1 = 14; let index2 = 18; let txt2 = txt.substring(index1, index2); println(txt2);
let txt = " I love coding ! "; txt = txt.trim(); println("'" + txt + "'");
let txt = " I love coding ! "; txt = txt.trimStart(); println("'" + txt + "'");
let txt = " I love coding ! "; txt = txt.trimEnd(); println("'" + txt + "'");
let no = 3; let txt = no.toString(2).padStart(8, '0'); println(txt);
let n1 = "1"; let n2 = "3"; txt = n1 + "." + n2.padEnd(4, '0'); println(txt);
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); }
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 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.
This is the same as Math.random()
let n = random(); println(n);
let n = random(100); println(n);
let n = random(-100, 100); println(n);
You can use either randomInt or randomNumber
let n = randomInt(0, 10); println(n);
function randomChar(chr1, chr2)
let char = randomChar("A", "Z"); println(char);
let ar = ["J", "a", "v", "a", "S", "c", "r", "i", "p", "t"]; let char = random(ar); println(char);
let ar = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; let ar2 = ar.shuffle(); println(ar2);
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.
const math = require("MathUtils"); let sum = math.add(2, 3); let prod = math.prod(3, 4); println(sum); println(prod);
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.
codeguppy.com is a great environment for graphical based activities using both cartesian and turtle graphics.
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);
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();
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.
background("navy");
background("#F012D3");
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.
circle(400, 300, 200);
ellipse(400, 300, 300, 200);
rect(400, 300, 300, 200);
line(400, 300, 500, 500);
triangle(400, 100, 200, 400, 600, 500);
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);
point(400, 300);
text('JavaScript', 400, 300);
Note: Once set, these settings will be applied to all successive shape drawn on the canvas
textSize(20); text("JavaScript", 400, 300);
fill('Magenta'); circle(400, 300, 100);
stroke('Teal'); circle(400, 300, 100);
strokeWeight(2); circle(400, 300, 100);
noFill(); circle(400, 300, 100);
noStroke(); fill("lightblue"); circle(400, 300, 100);
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).
To use the default turtle, all you need to do is to use the following global instructions.
home();
pencolor("Red");
pensize(2);
pendown();
penup();
setposition(100, 100);
left(30);
right(30);
setheading(180);
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);
Note: The turtle moves in the oposite direction than would move with forward
back(100);
let p = position(); println(p[0]); println(p[1]);
let angle = heading(); println(angle);
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.
let t1 = createTurtle(); let t2 = createTurtle(); t1.pencolor("Red"); t1.forward(100); t2.pencolor("Blue"); t2.right(90); t2.forward(100);
let t = getDefaultTurtle(); t.forward(100);
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.
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);
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);
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);
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);
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);
colorMode(RGB);
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);
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); }
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!
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.
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; }
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; }
frameRate(30); textSize(40); let n = 0; function loop() { clear(); text(n, 400, 300); n++; }
function loop() { clear(); text(frameRate(), 400, 300); }
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.
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.
Executes once when a key is pressed
function keyPressed() { clear(); text(key, 400, 300); text(keyCode, 400, 320); }
Executes when a key is released
function keyReleased() { clear(); text(key, 400, 300); text(keyCode, 400, 320); }
Executes when a key is typed execept for special keys
function keyTyped() { clear(); text(key, 400, 300); text(keyCode, 400, 320); }
Executes once when the mouse is pressed and released
function mouseClicked() { circle(mouseX, mouseY, 10); }
Executes once when the mouse button is pressed
function mousePressed() { stroke("red"); circle(mouseX, mouseY, 10); }
Executes when the mouse button is released
function mouseReleased() { stroke("blue"); circle(mouseX, mouseY, 10); }
Executes when the mouse is moved and button is not pressed
function mouseMoved() { line(mouseX, mouseY, pmouseX, pmouseY); }
Executes when the mouse is moved an a button is pressed
function mouseDragged() { line(mouseX, mouseY, pmouseX, pmouseY); }
Executes when the mouse is double clicked
function doubleClicked() { circle(mouseX, mouseY, 10); }
Executes when the user uses the mouse wheel or touchpad
function mouseWheel() { }
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.
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); }
System variable containing the last typed key.
function keyPressed() { if (key.toLowerCase() === "s") { showScene("Game"); } }
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.
System variable containing the horizontal coordinate of the mouse coursor.
function loop() { if (mouseIsPressed) line(mouseX, mouseY, pmouseX, pmouseY); }
System variable containing the vertical coordinate of the mouse coursor
function loop() { if (mouseIsPressed) line(mouseX, mouseY, pmouseX, pmouseY); }
System variable containing the previous horizontal coordinate of the mouse coursor
function loop() { if (mouseIsPressed) line(mouseX, mouseY, pmouseX, pmouseY); }
System variable containing the previous vertical coordinate of the mouse coursor.
function loop() { if (mouseIsPressed) line(mouseX, mouseY, pmouseX, pmouseY); }
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); }
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); }
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() 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:
/i/code.html?hints/userinput_10
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.
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.
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 by clear() instruction or shape drawing instructions or even 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.
You can load any sprite from the built-in library using the sprite command.
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.
background('Summer'); sprite('plane', 400, 200);
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);
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);
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.
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.
Use img in a string template, or as a function, to convert a custom-sprite text to an image:
/i/code.html?hints/gamedev_10
Custom sprites can also be loaded using the sprite command. In this way you can manipulate them like the rest of built-in sprites:
/i/code.html?hints/gamedev_20
A custom sprite can also be animated. If you need animated sprites, then you need to create multiple frame images for each sprite:
/i/code.html?hints/gamedev_30
You can even pack multiple animations in a custom sprite. This help you change later on the animations using the sprite .show() method:
/i/code.html?hints/gamedev_40
If your program required different colors, you can define a custom palette using setPalette.
/i/code.html?hints/gamedev_41
Note: You can obtain the current palette at any time using the getPalette() function.
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.
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;
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;
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);
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.
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:
/i/code.html?hints/gamedev_50
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.
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.
You can detect mouse clicks on sprites by assigning an event handler (e.g. function) to the following sprite properties:
/i/code.html?hints/gamedev_51
You can hide a sprite in two ways:
let p = sprite('adventure_girl.idle', 400, 300, 0.5); function mouseClicked() { p.visible = !p.visible; }
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).
/i/code.html?hints/gamedev_55
There are 4 different methods to verify if sprites are colliding:
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:
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.
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:
/i/code.html?hints/gamedev_60
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).
music('Rainbow');
Note: If any music was playing before, the music instruction interrupts that before playing the new music.
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('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.
? 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.
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)
/i/code.html?hints/gamedev_61
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)
/i/code.html?hints/gamedev_62
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)
/i/code.html?hints/gamedev_63
Use the following instruction to detect collisions between two circles:
collisionCircleCircle(circle1X, circle1Y, circle1R, circle2X, circle2Y, circle2R)
/i/code.html?hints/gamedev_64
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)
/i/code.html?hints/gamedev_65
Use the following instruction to detect collision between two rectangles:
collisionRectRect(rect1X, rect1Y, rect1Width, rect1Height, rect2X, rect2Y, rect2Width, rect2Height)
/i/code.html?hints/gamedev_66
Use this instruction to detect collisions between two lines:
collisionLineLine(x1, y1, x2, y2, x3, y3, x4, y4)
/i/code.html?hints/gamedev_67
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)
/i/code.html?hints/gamedev_68
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.
To make your character move on the screen, read the keyboard and update character state (e.g. position) inside the loop()
/i/code.html?hints/gamedev_70
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.
/i/code.html?hints/gamedev_80
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!
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); }
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.
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"); }
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; }
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.
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); }
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); }
For a deeper understanding on how to work with sprites in codeguppy.com, please consult these tutorials:
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.
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:
for(let i = 0; i < 10; i++) { println(i); }
/i/code.html?hints/other_10
Note: println is adding a new line character after each print, while print is not.
codeguppy.com offers simple instructions for creating data input user interfaces.
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.
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; }
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:
Example:
https://codeguppy.com/code.html?hints/other_20
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.
以上是JavaScript 和 codeguppy.com 快速介绍的详细内容。更多信息请关注PHP中文网其他相关文章!