Heim > Web-Frontend > js-Tutorial > Hauptteil

Kurze Einführung in JavaScript und codeguppy.com

Patricia Arquette
Freigeben: 2024-11-15 01:06:02
Original
127 Leute haben es durchsucht

Quick intro to JavaScript and codeguppy.comJavaScript ist eine der vielseitigsten Programmiersprachen und ein zentrales Werkzeug für kreatives Codieren, Spieleentwicklung und Webentwicklung. Egal, ob Sie Anfänger sind oder Ihre Kenntnisse auffrischen möchten, dieser Leitfaden bietet einen schnellen Überblick über grundlegende JavaScript-Konzepte, der Ihnen den Einstieg erleichtern soll. Außerdem erfahren Sie, wie Sie codeguppy.com, eine einsteigerfreundliche Online-Codierungsplattform, nutzen können, um Ihre Fähigkeiten zu üben. Von Variablen bis hin zu Schleifen und Funktionen dient dieses Artikelbuch als Referenz für den schnellen Einstieg in JavaScript.

Inhaltsverzeichnis

Kapitel 1: JavaScript-Syntax

  • Variablen
  • if-Anweisung
  • For-Schleife
  • While-Schleife
  • While-Schleife ausführen
  • Switch-Anweisung
  • Funktionen
  • Array-Methoden
  • String-Methoden
  • Zufallszahlen
  • Module

Kapitel 2: Zeichnen auf Leinwand mit JavaScript

  • Über Leinwand
  • Die Leinwand freimachen
  • Hintergrundfarbe
  • Formen zeichnen
  • Formeinstellungen
  • Schildkrötengrafiken
  • Farben
  • Winkel
  • Animationen

Kapitel 3: Benutzereingaben

  • keyPressed-Ereignis
  • keyReleased-Ereignis
  • keyTyped-Ereignis
  • mouseClicked-Ereignis
  • mousePressed-Ereignis
  • mouseReleased-Ereignis
  • mouseMoved-Ereignis
  • mouseDragged-Ereignis
  • doubleClicked-Ereignis
  • MouseWheel-Ereignis
  • keyIsPressed
  • Taste
  • Schlüsselcode
  • mouseX
  • MausY
  • pmouseX
  • pmouseY
  • mouseIsPressed
  • Maustaste
  • keyIsDown()
  • keyWentDown()

Kapitel 4: JavaScript-Spieleentwicklung mit codeguppy.com

  • Ebenen zeichnen
  • Hintergrundbilder festlegen
  • Eingebaute Sprites werden geladen
  • Benutzerdefinierte Sprites werden geladen
  • Animierte benutzerdefinierte Sprites werden geladen
  • Sprite-Position festlegen
  • Sprites automatisch verschieben
  • Sprites spiegeln
  • Sprite-Rotation
  • Sprites automatisch drehen
  • Zeichnungstiefe
  • Ändernde Animationen
  • Mausereignisse auf Sprites
  • Sprites ausblenden
  • Sprites entfernen
  • Sprite-Kollisionen
  • Sprite-Gruppen
  • Hintergrundmusik
  • Soundeffekte
  • Kollisionen zwischen Formen
  • Die Spielschleife
  • Assets vorab laden
  • Zeige eine Szene
  • Das Enter-Ereignis
  • Daten an eine Szene übergeben

Kapitel 5: Weitere Codierungshinweise

  • Daten drucken
  • Benutzeroberflächen für die Dateneingabe erstellen

Kapitel 1: JavaScript-Syntax

Beginnen wir unseren Artikel mit der Erkundung der JavaScript-Syntax.

Variablen deklarieren

Variablen werden zum Speichern von Daten wie Zahlen, Zeichenfolgen (Text) oder sogar komplexen Objekten verwendet. Denken Sie daran:

  • Sie können in einem Programm so viele Variablen haben, wie Sie möchten.
  • Sie müssen jeder Variablen einen Namen geben, der die von ihr gespeicherten Daten darstellt.
  • Geben Sie Variablen innerhalb desselben Codeblocks (z. B. was zwischen { ... }) oder sogar innerhalb einer Funktion unterschiedliche Namen

Variable x deklarieren

let x;
Nach dem Login kopieren

Deklarieren Sie x und initialisieren Sie es mit einem numerischen Wert

let x = 1;
Nach dem Login kopieren

Deklarieren Sie s und initialisieren Sie es mit einem String

let s = "Hello, World!";
Nach dem Login kopieren

Zuweisen von Werten zu Variablen

Sobald eine Variable mit let deklariert wurde, kann sie beliebig oft mit unterschiedlichen Werten zugewiesen/neu zugewiesen werden.

Sie können es mit einfachen Konstanten oder sogar komplexen Ausdrücken zuweisen, die Konstanten, andere Variablen und sogar dieselbe Variable enthalten! Computer sind sehr gut darin, Ausdrücke auszuwerten.

Weisen Sie der Variablen x die Nummer 100 zu

x = 100;
Nach dem Login kopieren

Weisen Sie der Variablen s die Zeichenfolge „Hallo“ zu

s = "Hello";
Nach dem Login kopieren

Weisen Sie der Variablen ar ein leeres Array zu

ar = [];
Nach dem Login kopieren

Weisen Sie der Variablen ar ein Array mit 3 Zahlen zu

ar = [1, 2, 3];
Nach dem Login kopieren

Weisen Sie der Variablen ar ein Array mit zwei Zeichenfolgen zu

ar = ["A", "B"];
Nach dem Login kopieren

Weisen Sie der Variablen o ein Inline-Objekt zu

o = {   Type: 'car', 
        x : 100, 
        y : 200 
    };
Nach dem Login kopieren

Die Variablensumme ist gleich a b

sum = a + b;
Nach dem Login kopieren

Weisen Sie der Variablen avg einen Ausdruck zu

avg = (a + b) / 2;
Nach dem Login kopieren

Variablensumme wird um 10 erhöht (die neue Summe wird zur älteren Summe 10)

sum = sum + 10;
Nach dem Login kopieren

Variable i wird um 1 erhöht (inkrementiert).

i++;
Nach dem Login kopieren

Variable i wird um 2 erhöht

i += 2;
Nach dem Login kopieren

if-Anweisung

if-Anweisungen eignen sich hervorragend zur Steuerung des Programmflusses. Normalerweise wird ein Programm Anweisung für Anweisung von oben nach unten ausgeführt.

Wenn die Bedingung erfüllt ist, können Sie eine Entscheidung treffen und eine Reihe von Anweisungen ausführen.

Führt den Befehlsblock zwischen {} aus, wenn die Bedingung wahr ist

if (mouseX < width)
{

}
Nach dem Login kopieren

Führt den ersten Befehlsblock aus, wenn die Bedingung wahr ist, andernfalls den zweiten Block

if (hour < 12)
{

}
else
{

}
Nach dem Login kopieren

Verschiedene Blöcke basierend auf unterschiedlichen Bedingungen ausführen

Wenn im folgenden Beispiel die erste Bedingung wahr ist, wird der erste Block ausgeführt und die anderen nicht.

Wenn die erste Bedingung jedoch nicht wahr ist, wird das „else if“ zum Testen einer anderen Bedingung verwendet, und wenn „true“ ist, wird der Block dieses „else if“ ausgeführt.

Der Block nach dem letzten else wird nur ausgeführt, wenn bis zu diesem Zeitpunkt keine andere Bedingung wahr war.

if (minute <= 15)
{
}
else if(minute <= 30)
{
}
else
{
}
Nach dem Login kopieren

Hinweis: Sie können in dieser Art von Ausdruck mehrere else if-Blöcke haben.

for loop

Prints numbers from 0 to 4 using a for loop and println

for(let i = 0; i < 5; i++)
{
    println(i);
}
Nach dem Login kopieren

Prints numbers from 10 down to 0 using a for loop

for(let i = 10; i >= 0; i--)
{
    println(i);
}
Nach dem Login kopieren

Prints even numbers from 0 to 100

for(let i = 0; i <= 100; i+=2)
{
    println(i);
}
Nach dem Login kopieren

Print all elements of an array

let ar = [10, 20, 30];

for(let element of ar)
{
    println(element);
}
Nach dem Login kopieren

while loop

Print numbers from 0 to 9 using a while loop

let i = 0;

while(i < 10)
{
    println(i);
    i++;
}
Nach dem Login kopieren

do while

Print numbers from 0 to 10 using a do while loop

let i = 0;

do
{
    println(i);
    i++;
}
while(i < 10)
Nach dem Login kopieren

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:
        //...
}
Nach dem Login kopieren

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");
Nach dem Login kopieren

Functions that return values

function addNumbers(x, y)
{
    return x + y;
}

// Call a function
var sum = addNumbers(100, 200);
println(sum);
Nach dem Login kopieren

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 = [];
Nach dem Login kopieren

Declaring and initializing ar to an array of 3 numbers

let ar = [10, 20, 30];
Nach dem Login kopieren

Length of an array

let ar = [10, 20, 30];
println("Length of array: ", ar.length); 
Nach dem Login kopieren

Append an element at the end of the array

let ar = [10, 20, 30];
ar.push(100);

println(ar);
Nach dem Login kopieren

Insert an element at the beginning of an array

let ar = [10, 20, 30];
ar.unshift(1);

println(ar);
Nach dem Login kopieren

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);
Nach dem Login kopieren

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);
Nach dem Login kopieren

Read the value of element 2 of an array

let ar = [10, 20, 30];
println(ar[2]);
Nach dem Login kopieren

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);
Nach dem Login kopieren

Assign a different value to al element of an array

let ar = [10, 20, 30];
ar[2] = 100;

println(ar); 
Nach dem Login kopieren

Accesing the first element

let ar = [10, 20, 30];
println(ar[0]);
Nach dem Login kopieren

Accessing the last element

let ar = [10, 20, 30];
let len = ar.length;
println(ar[len - 1]); 
Nach dem Login kopieren

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()); 
Nach dem Login kopieren

Remove the first element of the array

let ar = [10, 20, 30];
ar.shift();

println(ar);
Nach dem Login kopieren

Remove the last element of the array

let ar = [10, 20, 30];
ar.pop();

println(ar);
Nach dem Login kopieren

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);
Nach dem Login kopieren

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);
Nach dem Login kopieren

Concatenate two arrays

// Merge / concatenate 2 arrays
let ar1 = ["a", "b", "c"];
let ar2 = ["d", "e", "f"];

let ar = ar1.concat(ar2);
println(ar);
Nach dem Login kopieren

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);
Nach dem Login kopieren

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);
Nach dem Login kopieren

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);
Nach dem Login kopieren

Iterating all characters of a string

let txt = "JavaScript";

for(let chr of txt)
{
    println(chr);
}
Nach dem Login kopieren

Accessing string characters by position

let txt = "JavaScript";

for(let i = 0; i < txt.length; i++)
{
    println(txt[i]);
}
Nach dem Login kopieren

Converting text to uppercase

let txt = "JavaScript";

txt = txt.toUpperCase();
println(txt);
Nach dem Login kopieren

Converting text to lowercase

let txt = "JavaScript";

txt = txt.toLowerCase();
println(txt);
Nach dem Login kopieren

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);
}
Nach dem Login kopieren

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);
}
Nach dem Login kopieren

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!");
}
Nach dem Login kopieren

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);
Nach dem Login kopieren

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);
Nach dem Login kopieren

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);
Nach dem Login kopieren

Remove whitespaces from beginning and end of the string

let txt = "    I love coding !    ";

txt = txt.trim();
println("'" + txt + "'");
Nach dem Login kopieren

Remove whitespaces from beginning of the string

let txt = "    I love coding !    ";

txt = txt.trimStart();
println("'" + txt + "'");
Nach dem Login kopieren

Remove whitespaces from the end of the string

let txt = "    I love coding !    ";

txt = txt.trimEnd();
println("'" + txt + "'");
Nach dem Login kopieren

Pads the start of the string with another string

let no = 3;

let txt = no.toString(2).padStart(8, '0');
println(txt);
Nach dem Login kopieren

Pads the end of the string with another string

let n1 = "1";
let n2 = "3";

txt = n1 + "." + n2.padEnd(4, '0');
println(txt);
Nach dem Login kopieren

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);
}
Nach dem Login kopieren

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);
}
Nach dem Login kopieren

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);
Nach dem Login kopieren

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);
Nach dem Login kopieren

Random floating point number between 0 and n (n not included)

let n = random(100);
println(n);
Nach dem Login kopieren

Random floating point number between n1 and n2 (n2 not included)

let n = random(-100, 100);
println(n);
Nach dem Login kopieren

Random int between min and max (both included)

You can use either randomInt or randomNumber

let n = randomInt(0, 10);
println(n);
Nach dem Login kopieren

Random char between chr1 and chr2 (both included)

function randomChar(chr1, chr2)

let char = randomChar("A", "Z");
println(char);
Nach dem Login kopieren

Random element of an array

let ar = ["J", "a", "v", "a", "S", "c", "r", "i", "p", "t"];

let char = random(ar);
println(char);
Nach dem Login kopieren

Shuffle an array

let ar = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let ar2 = ar.shuffle();

println(ar2);
Nach dem Login kopieren

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);
Nach dem Login kopieren

Module MathUtils content

function add(a, b)
{
    return a + b;
}

function prod(a, b)
{
    return a * b;
}
Nach dem Login kopieren

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);
Nach dem Login kopieren

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();
Nach dem Login kopieren

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");
Nach dem Login kopieren

Set the background color to a color specified as a hex "#RRGGBB" string

background("#F012D3");
Nach dem Login kopieren

Set the background color to a gray color (0 - black, 255 - white)

background(255);
Nach dem Login kopieren

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);
Nach dem Login kopieren

Draw an ellipse at coordinates 400 x 300 and width and height of 300 x 200 pixels

ellipse(400, 300, 300, 200);
Nach dem Login kopieren

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);
Nach dem Login kopieren

Draw a line between coordinates 400 x 300 and 500 x 500

line(400, 300, 500, 500);
Nach dem Login kopieren

Draw a triangle by specifying each corner coordinates

triangle(400, 100, 200, 400, 600, 500);
Nach dem Login kopieren

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);
Nach dem Login kopieren

Draw a point at coordinates 400 x 300

point(400, 300);
Nach dem Login kopieren

Draw text JavaScript at coordinates 400 x 300

text('JavaScript', 400, 300);
Nach dem Login kopieren

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);
Nach dem Login kopieren

Set "Magenta" as the color to fill shapes

fill('Magenta');

circle(400, 300, 100);
Nach dem Login kopieren

Set "Teal" as the color to draw shapes

stroke('Teal');

circle(400, 300, 100);
Nach dem Login kopieren

Set the line thickness to 2 px

strokeWeight(2);

circle(400, 300, 100);
Nach dem Login kopieren

Draw empty shapes, without fill color

noFill();

circle(400, 300, 100);
Nach dem Login kopieren

Draw shapes without an outline

noStroke();

fill("lightblue");
circle(400, 300, 100);
Nach dem Login kopieren

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();
Nach dem Login kopieren

Sets to Red the pen color of the default turtle

pencolor("Red");
Nach dem Login kopieren

Sets to 2 the pen size of the default turtle

pensize(2);
Nach dem Login kopieren

Put the pen on the paper. The turtle will draw.

pendown();
Nach dem Login kopieren

Raise the pen from the paper. The turtle will advance but not draw

penup();
Nach dem Login kopieren

Move the turtle to an arbitrary position on the canvas

setposition(100, 100);
Nach dem Login kopieren

Turns the default turtle to the left by the number of specified degrees

left(30);
Nach dem Login kopieren

Turns the default turtle to the right by 30 degrees

right(30);
Nach dem Login kopieren

Sets the turtle heading (direction) to an arbitrary angle

setheading(180);
Nach dem Login kopieren

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);
Nach dem Login kopieren

Moves the turtle back by number of specified pixels.

Note: The turtle moves in the oposite direction than would move with forward

back(100);
Nach dem Login kopieren

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]);
Nach dem Login kopieren

Retrieve the default turtle direction in degrees

let angle = heading();

println(angle);
Nach dem Login kopieren

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);
Nach dem Login kopieren

Get the default turtle

let t = getDefaultTurtle();
t.forward(100);
Nach dem Login kopieren

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);
Nach dem Login kopieren

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);
Nach dem Login kopieren

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);
Nach dem Login kopieren

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);
Nach dem Login kopieren

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);
Nach dem Login kopieren

Changing back to RGB mode

colorMode(RGB);
Nach dem Login kopieren

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);
Nach dem Login kopieren

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);
}
Nach dem Login kopieren

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;
}
Nach dem Login kopieren

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;
}
Nach dem Login kopieren

Change the default frame rate

frameRate(30);
textSize(40);

let n = 0;

function loop()
{
    clear();
    text(n, 400, 300);

    n++;
}
Nach dem Login kopieren

Obtain the frame rate

function loop()
{
    clear();
    text(frameRate(), 400, 300);
}
Nach dem Login kopieren

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);
}
Nach dem Login kopieren

keyReleased event

Executes when a key is released

function keyReleased()
{
    clear();
    text(key, 400, 300);
    text(keyCode, 400, 320);
}
Nach dem Login kopieren

keyTyped event

Executes when a key is typed execept for special keys

function keyTyped()
{
    clear();
    text(key, 400, 300);
    text(keyCode, 400, 320);
}
Nach dem Login kopieren

mouseClicked event

Executes once when the mouse is pressed and released

function mouseClicked()
{
    circle(mouseX, mouseY, 10);
}
Nach dem Login kopieren

mousePressed event

Executes once when the mouse button is pressed

function mousePressed()
{
    stroke("red");
    circle(mouseX, mouseY, 10);
}
Nach dem Login kopieren

mouseReleased event

Executes when the mouse button is released

function mouseReleased()
{
    stroke("blue");
    circle(mouseX, mouseY, 10);
}
Nach dem Login kopieren

mouseMoved event

Executes when the mouse is moved and button is not pressed

function mouseMoved()
{
    line(mouseX, mouseY, pmouseX, pmouseY);
}
Nach dem Login kopieren

mouseDragged event

Executes when the mouse is moved an a button is pressed

function mouseDragged()
{
    line(mouseX, mouseY, pmouseX, pmouseY);
}
Nach dem Login kopieren

doubleClicked event

Executes when the mouse is double clicked

function doubleClicked()
{
    circle(mouseX, mouseY, 10);
}
Nach dem Login kopieren

mouseWheel event

Executes when the user uses the mouse wheel or touchpad

function mouseWheel()
{

}
Nach dem Login kopieren

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);
}
Nach dem Login kopieren

key

System variable containing the last typed key.

function keyPressed()
{
    if (key.toLowerCase() === "s")
    {
        showScene("Game");
    }
}
Nach dem Login kopieren

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");
    }
}
Nach dem Login kopieren

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);
}
Nach dem Login kopieren
Nach dem Login kopieren
Nach dem Login kopieren
Nach dem Login kopieren
Nach dem Login kopieren

mouseY

System variable containing the vertical coordinate of the mouse coursor

function loop()
{
    if (mouseIsPressed)
        line(mouseX, mouseY, pmouseX, pmouseY);
}
Nach dem Login kopieren
Nach dem Login kopieren
Nach dem Login kopieren
Nach dem Login kopieren
Nach dem Login kopieren

pmouseX

System variable containing the previous horizontal coordinate of the mouse coursor

function loop()
{
    if (mouseIsPressed)
        line(mouseX, mouseY, pmouseX, pmouseY);
}
Nach dem Login kopieren
Nach dem Login kopieren
Nach dem Login kopieren
Nach dem Login kopieren
Nach dem Login kopieren

pmouseY

System variable containing the previous vertical coordinate of the mouse coursor.

function loop()
{
    if (mouseIsPressed)
        line(mouseX, mouseY, pmouseX, pmouseY);
}
Nach dem Login kopieren
Nach dem Login kopieren
Nach dem Login kopieren
Nach dem Login kopieren
Nach dem Login kopieren

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);
}
Nach dem Login kopieren
Nach dem Login kopieren
Nach dem Login kopieren
Nach dem Login kopieren
Nach dem Login kopieren

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);
}
Nach dem Login kopieren

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);
}
Nach dem Login kopieren

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:

/i/code.html?hints/userinput_10

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:

Quick intro to JavaScript and codeguppy.com

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');
Nach dem Login kopieren

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');
Nach dem Login kopieren

? 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

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');
Nach dem Login kopieren

? 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);
Nach dem Login kopieren

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);
Nach dem Login kopieren

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);
Nach dem Login kopieren

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);
Nach dem Login kopieren

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:

/i/code.html?hints/gamedev_10

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:

/i/code.html?hints/gamedev_20

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:

/i/code.html?hints/gamedev_30

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:

/i/code.html?hints/gamedev_40

Custom palette for custom sprites

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.

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;
Nach dem Login kopieren

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;
Nach dem Login kopieren

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);
Nach dem Login kopieren

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:

/i/code.html?hints/gamedev_50

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);
Nach dem Login kopieren

However, later one, you can change the animation of that sprite using the .show method:

player.show('run');
Nach dem Login kopieren

? 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

/i/code.html?hints/gamedev_51

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;
}
Nach dem Login kopieren

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).

/i/code.html?hints/gamedev_55

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++;
}
Nach dem Login kopieren

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

/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).

Background Music

Play music named Rainbow

music('Rainbow');
Nach dem Login kopieren

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);
Nach dem Login kopieren

? 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');
Nach dem Login kopieren

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)
Nach dem Login kopieren

/i/code.html?hints/gamedev_61

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)
Nach dem Login kopieren

/i/code.html?hints/gamedev_62

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)
Nach dem Login kopieren

/i/code.html?hints/gamedev_63

Detect collision between two circles

Use the following instruction to detect collisions between two circles:

collisionCircleCircle(circle1X, circle1Y, circle1R, circle2X, circle2Y, circle2R)
Nach dem Login kopieren

/i/code.html?hints/gamedev_64

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)
Nach dem Login kopieren

/i/code.html?hints/gamedev_65

Detect collision between two rectangles

Use the following instruction to detect collision between two rectangles:

collisionRectRect(rect1X, rect1Y, rect1Width, rect1Height, rect2X, rect2Y, rect2Width, rect2Height)
Nach dem Login kopieren

/i/code.html?hints/gamedev_66

Detect collision between two lines

Use this instruction to detect collisions between two lines:

collisionLineLine(x1, y1, x2, y2, x3, y3, x4, y4)
Nach dem Login kopieren

/i/code.html?hints/gamedev_67

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)
Nach dem Login kopieren

/i/code.html?hints/gamedev_68

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()

/i/code.html?hints/gamedev_70

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.

/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!

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);
}
Nach dem Login kopieren

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");
}
Nach dem Login kopieren

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;
}
Nach dem Login kopieren

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);
Nach dem Login kopieren

Inside the "Congrats" scene, you can retrieve this passed data in the following way:

function enter()
{
    let score = sceneArgs;
    text(score, 400, 300);
}
Nach dem Login kopieren

Passing a complex structure to "Congrats" scene

let data = {
    score : 1000,
    time : 10,
    bonusPoints : 100
}

showScene("Congrats", data);
Nach dem Login kopieren

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);
}
Nach dem Login kopieren

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);
}
Nach dem Login kopieren

Print the first 10 prime numbers

/i/code.html?hints/other_10

Note: println is adding a new line character after each print, while print is not.

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);
Nach dem Login kopieren

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);
Nach dem Login kopieren

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;
}
Nach dem Login kopieren

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";
Nach dem Login kopieren

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:

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.

Das obige ist der detaillierte Inhalt vonKurze Einführung in JavaScript und codeguppy.com. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Quelle:dev.to
Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Neueste Artikel des Autors
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage