setCanvasSize(640, 360)
Sets the size of the canvas that all drawings are written to. The first parameter specifies the width in pixels and the second the height. The third parameter is optional and specifies the direction of the y-axis. The constant CARTESIAN can be used to specify a y-axis that is used in maths and a constant of JAVASCRIPT can be used to specify the regular javascript y-axis which moves down the screen. If no value is provided as the third parameter, a default of CARTESIAN is used.
setCanvasSize(w, h, yAxisMode)
w - The width of the canvas in pixels.
h - The height of the canvas in pixels.
yAxisMode - Optionally used to set the direction of the y-axis. Use the constants CARTESIAN or JAVASCRIPT. CARTESIAN is used as the default value if this parameter is not supplied.
noCanvas()
Hides the canvas from the page. This may be useful if you are running a text only Python program.
noCanvas()
This function takes no parameters.
setCanvasSize(640, 360) background(220, 220, 220) input("Press ENTER to continue") focusCanvas()
Places the focus back on the canvas. This is necessary if you wish to receive keyboard events that occur on the canvas and the focus has been moved away. The focus can be moved when a user responds to an input function or clicks away from the canvas. The focus can be returned by the user clicking on the canvas but this function gives you a programmatic way to return focus.
focusCanvas()
This function takes no parameters.
# Draw a rectangle at location (10, 20) with a width of 50 and height of 25. setCanvasSize(100, 100) rect(10, 20, 50, 25)
Draws a rectangle on the canvas. By default, the first two parameters set the location of the bottom left corner, the third sets the width, and the fourth sets the height. The way these parameters are interpreted, may be changed with the rectMode() function. If the setCanvasSize() function is called and sets the yAxisMode to JAVASCRIPT, then the first two parameters specify the top left corner of the rectangle.
rect(x, y, w, h)
x - The x coordinate of the rectangle.
y - The y coordinate of the rectangle.
w - The width of the rectangle.
h - The height of the rectangle.
# Draw a circle at location (100, 200) with a radius of 50. setCanvasSize(200, 400) circle(100, 200, 50)
Draws a circle on the canvas. By default, the first two parameters set the location of the center of the circle, and the third sets the radius. The way these parameters are interpreted, may be changed with the circleMode() function.
circle(x, y, radius)
x - The x coordinate of the circle.
y - The y coordinate of the circle.
radius - The radius of the circle.
# Draw an ellipse at location (100, 200) with an X radius of 50 and a Y radius of 100. setCanvasSize(200, 400) ellipse(100, 200, 50, 100)
Draws an ellipse (oval) on the canvas. By default, the first two parameters set the location of the center of the circle, the third sets the X radius, and the fourth sets the Y radius. The way these parameters are interpreted, may be changed with the circleMode() function.
ellipse(x, y, radiusX, radiusY)
x - The x coordinate of the ellipse.
y - The y coordinate of the ellipse.
radiusX - The X radius of the ellipse.
radiusY - The Y radius of the ellipse.
# Draw an arc at location (50, 50) with an X radius of 40 and a Y radius of 30. The arc spans from 0 to 270 degrees. setCanvasSize(100, 100) arc(50, 50, 40, 30, 0, 270)
Draws an arc (a portion of an ellipse) on the canvas. By default, the first two parameters set the location of the center of the circle, the third sets the X radius, and the fourth sets the Y radius. The fifth parameter is the start angle and the sixth is the end angle. The arc is always drawn clockwise from the start angle to the end angle. The way these parameters are interpreted, may be changed with the circleMode() function. By default the start and end angle are specified in degrees. This can be changed to radians with the angleMode() function.
arc(x, y, radiusX, radiusY, startAngle, endAngle)
x - The x coordinate of the arc.
y - The y coordinate of the arc.
radiusX - The X radius of the arc.
radiusY - The Y radius of the arc.
startAngle - The starting angle of the arc.
endAngle - The ending angle of the arc.
# Draw a line starting at (40, 20) and finishing at (60, 40). setCanvasSize(100, 100) line(40, 20, 60, 40)
# Draw 3 lines of different colours that give a 3D effect. setCanvasSize(640, 360) stroke(0, 0, 0) line(40, 30, 95, 30) stroke(120, 120, 120) line(95, 30, 95, 85) stroke(255, 255, 255) line(95, 85, 40, 85)
Draws an line between two points to the screen. By default the line has a width of a single pixel. This can be modified by the strokeWeight() function. The colour of a line can be changed by calling the stroke() function.
line(x1, y1, x2, y2)
x1 - The x coordinate of the starting point.
y1 - The y coordinate of the starting point.
x2 - The x coordinate of the ending point.
y2 - The y coordinate of the ending point.
# Draw a point at (40, 20). setCanvasSize(100, 100) point(40, 20)
# Draw a blue point at (50, 30) that is 20 pixels in size. setCanvasSize(100, 100) stroke(0, 0, 255) strokeWeight(20) point(50, 30)
Draws a pixel to the screen at the position given by the two parameters. The first parameter specifies the x position and the second parameter specifies the y position. By default the pixel has a size of a one pixel. This can be modified by the strokeWeight() function. The colour of a point can be changed by calling the stroke() function.
point(x, y)
x - The x coordinate.
y - The y coordinate.
# Draw a triangle specified by the three points (50, 75), (25, 100), and (75, 100). setCanvasSize(200, 200) triangle(50, 75, 25, 100, 75, 100)
Draws a triangle on the canvas specified by three points.
triangle(x1, y1, x2, y2, x3, y3)
x1 - The x coordinate of the first point.
y1 - The y coordinate of the first point.
x2 - The x coordinate of the second point.
y2 - The y coordinate of the second point.
x3 - The x coordinate of the third point.
y3 - The y coordinate of the third point.
# Draw a quad specified by the four points (50, 75), (25, 100), (75, 100), and (100, 75). setCanvasSize(200, 200) quad(50, 75, 25, 100, 75, 100, 100, 75)
Draws a quadrilateral (a four sided polygon) on the canvas specified by four points.
quad(x1, y1, x2, y2, x3, y3, x4, y4)
x1 - The x coordinate of the first point.
y1 - The y coordinate of the first point.
x2 - The x coordinate of the second point.
y2 - The y coordinate of the second point.
x3 - The x coordinate of the third point.
y3 - The y coordinate of the third point.
x4 - The x coordinate of the fourth point.
y4 - The y coordinate of the fourth point.
setCanvasSize(640, 360) rectMode(CORNER) fill(0, 0, 255) # draw a blue rectangle with rectMode(CORNER) rect(30, 30, 60, 60) rectMode(CORNERS) fill(255, 0, 0) # draw a red rectangle with rectMode(CORNERS) rect(30, 30, 60, 60)
setCanvasSize(640, 360) rectMode(CENTER) fill(0, 0, 255) # draw a blue rectangle with rectMode(CENTER) rect(30, 30, 60, 60) rectMode(CORNER) fill(255, 0, 0, 0.5) # draw a red rectangle with rectMode(CORNER) rect(30, 30, 60, 60)
Changes the way the rect() function uses the paramters passed to it.
The default mode is CORNER, which indicates that the first two parameters are the coordinates of the bottom left corner, and the third and fourth parameters specify the width and the height. If the setCanvasSize() function is called specifying to set the yAxisMode to JAVASCRIPT, then the first two parameters represent the top left corner.
The mode CORNERS indicates the first two parameters are the coordinates of the bottom left corner, and the third and fourth specify the top right coordinate.
The mode CENTER indicates the first two parameters are the coordinates of the center of the rectangle, and the third and fourth specify the width and height.
rectMode(mode)
mode - Can be CORNER, CORNERS, or CENTER
setCanvasSize(640, 360) circleMode(CENTER) fill(0, 0, 255) # draw a blue circle with circleMode(CENTER) circle(100, 100, 50) circleMode(CORNER) fill(255, 0, 0, 0.5) # draw a red circle with circleMode(CORNER) circle(100, 100, 50)
Changes the way the circle(), ellipse(), and arc() functions use the paramters passed to them.
The default mode is CENTER, which indicates that the first two parameters are the coordinates of the center of the shape. The remaining parameters refer to the radius for the circle() function, and the X radius and Y radius for the ellipse() and arc() functions.
The mode CORNER indicates the first two parameters are the coordinates of the bottom left corner of the shape. The meaning of any extra parameters remain unchanged.
circleMode(mode)
mode - Can be CORNER, or CENTER
setCanvasSize(640, 360) strokeWeight(1) line(10, 10, 100, 10) strokeWeight(2) line(10, 20, 100, 20) strokeWeight(4) line(10, 30, 100, 30) strokeWeight(8) line(10, 40, 100, 40)
Sets the width of any lines, points and the border around shapes. All widths are specified in pixels.
strokeWeight(weight)
weight - the weight of the stroke in pixels.
setCanvasSize(400, 400) fill(200, 90, 90) beginShape() vertex(10, 10) vertex(20, 100) vertex(60, 110) vertex(50, 50) vertex(200, 5) endShape()
The beginShape(), vertex(), and endShape() functions allow you to create more complex shapes. The beginShape() function starts recording vertices that are added via the vertex() function.
beginShape()
setCanvasSize(400, 400) fill(200, 90, 90) beginShape() vertex(10, 10) vertex(20, 100) vertex(60, 110) vertex(50, 50) vertex(200, 5) endShape()
The vertex() function adds a point to the list of vertices that will be connected when the endShape() function is called. It takes two parameters, the x and y coordinates of the vertex to add.
vertex(x, y)
x - The x coordinate of the vertex to add.
y - The y coordinate of the vertex to add.
setCanvasSize(400, 400) fill(200, 90, 90) beginShape() vertex(10, 10) vertex(20, 100) vertex(60, 110) vertex(50, 50) vertex(200, 5) endShape()
setCanvasSize(400, 400) fill(200, 90, 90) beginShape() vertex(10, 10) vertex(20, 100) vertex(60, 110) vertex(50, 50) vertex(200, 5) endShape(OPEN)
Draws a shape specified by the list of vertices added by calling beginShape() followed by any number of vertex() function calls. By default the entire shape is closed by linking the last vertex back to the first. This can be changed by passing the constant OPEN as a parameter.
endShape(mode)
mode - CLOSE or OPEN. CLOSE specifies the shape should be closed and is the default where OPEN does not connect the last vertex to the first.
Colour(value: int[, alpha: float]) // Greyscale 0–255, optional alpha 0.0–1.0 Colour(r: int, g: int, b: int[, a: float]) // RGB channels 0–255, optional alpha 0.0–1.0 Colour(css: str) // CSS hex, rgb()/rgba(), or named colour Colour(arr: list[int] | tuple[int]) // Python list or tuple of length 3 or 4
The Colour
class represents an RGBA colour. You can create one by:
#RGB
, #RRGGBB
), rgb()
, rgba()
, or any named colour.list
or tuple
of length 3 ([r, g, b]) or 4 ([r, g, b, a]).
c.namedColours
: list<str> – a read-only property on instances that returns all supported CSS colour names.
To inspect:
c = Colour('red') print(c.namedColours) # ['aliceblue', 'antiquewhite', 'aqua', ...]Use these names in
background()
, fill()
, stroke()
, etc.
.red
— Red channel (0–255).green
— Green channel (0–255).blue
— Blue channel (0–255).alpha
— Alpha (0.0–1.0).css(): str
— Returns a CSS-style string "rgba(r, g, b, a)"
.# Numeric RGB c1 = Colour(255, 100, 100) # CSS string c2 = Colour('#f80') c3 = Colour('rgba(10,20,30,0.5)') # Named colour c4 = Colour('hotpink') # Greyscale + alpha c5 = Colour(128, 0.25) # From Python list c6 = Colour([10,20,30,1.0]) print(c4.css()) # "rgba(255, 105, 180, 1.00)" print(len(c1.namedColours), "named colours available")
background(r, g, b[, a]) | background(name: str) | background(col: Colour)
Sets the entire canvas background colour. Accepts three forms:
r, g, b[, a]
: numeric channels (0–255), optional alpha (0.0–1.0).name
: a CSS-named colour string (e.g. 'lavender'
), from a Colour
instance’s namedColours
list.col
: an existing Colour
instance.setCanvasSize(400, 300) # Grey background background(200) # Named-colour background background('lavender') # Using a Colour instance c = Colour('midnightblue', 0.2) background(c) # Draw on top fill('black') text('Hello!', 20, 30)
fill(r, g, b[, a]) | fill(name: str) | fill(col: Colour)
Sets the fill colour for subsequent shapes. Accepts three forms:
r, g, b[, a]
: numeric channels (0–255), optional alpha (0.0–1.0).name
: a CSS-named colour string (e.g. 'red'
), from an Colour
instance’s namedColours
list.col
: an existing Colour
instance.setCanvasSize(640, 360) # RGB fill fill(100, 220, 100) rect(50, 50, 100, 100) # Named-colour fill fill('hotpink') ellipse(200, 200, 80, 80) # Colour-instance fill c = Colour('navy', 0.5) fill(c) rect(300, 50, 80, 120)
noFill()
Disables filling of shapes. After calling noFill()
, shapes will be drawn with transparent interiors.
Use stroke()
to set the outline colour.
setCanvasSize(300, 200) stroke('blue') noFill() rect(50, 50, 200, 100)
stroke(r, g, b[, a]) | stroke(name: str) | stroke(col: Colour)
Sets the outline (stroke) colour for shapes and lines. Accepts three forms:
r, g, b[, a]
: numeric channels (0–255), optional alpha (0.0–1.0).name
: a CSS-named colour string.col
: an existing Colour
instance.setCanvasSize(300, 200) # Black outline by default stroke(0) noFill() ellipse(150, 100, 100, 100) # Semi-transparent red outline stroke('red', 0.5) rect(50, 50, 200, 100)
noStroke()
Disables drawing outlines for shapes. After calling noStroke()
, shapes will only fill interiors.
Use fill()
to set the fill colour.
setCanvasSize(300, 200) fill('green') noStroke() rect(50, 50, 200, 100)
pyangelo = Image("/samples/images/PyAngelo.png") setCanvasSize(640, 360) x = width/2 - 64 y = height/2 - 48 while True: background(255, 255, 0) drawImage(pyangelo, x, y) text("Use the WASD keys to move me around!", 20, 30) if isKeyPressed(KEY_W): y -= 1 if isKeyPressed(KEY_A): x -= 1 if isKeyPressed(KEY_S): y += 1 if isKeyPressed(KEY_D): x += 1 sleep(0.005)
Returns True if the key specified by the first parameter is currently pressed, otherwise returns False. Once the key has been pressed the function will continue to return True each time it is called until the key is released. There is a list of constants that can be used in PyAngelo to represent each key for clarity.
isKeyPressed(code)
code - The code representing a key on the keyboard. See a list of codes.
pyangelo = Image("/samples/images/PyAngelo.png") setCanvasSize(640, 360) x = width/2 - 64 y = height/2 - 48 while True: background(255, 255, 0) drawImage(pyangelo, x, y) text("Use the WASD keys to move me around!", 20, 30) if wasKeyPressed(KEY_W): y -= 1 if wasKeyPressed(KEY_A): x -= 1 if wasKeyPressed(KEY_S): y += 1 if wasKeyPressed(KEY_D): x += 1 sleep(0.005)
Returns True if the key specified by the first parameter has been pressed and not yet released before this function is called. Otherwise, it returns False. Once the key has been pressed and the function has been called, the function will then return False until the key is either pressed again, or if it is being held down the operating system sends another keypressed event. This is different from the isKeyPressed() function which continues to return True when called until the key is released. There is a list of constants that can be used in PyAngelo to represent each key for clarity.
wasKeyPressed(code)
code - The code representing a key on the keyboard. See a list of codes.
This variable holds the current horizontal position of the mouse. The value is the number of pixels from the origin (0, 0) of the canvas.
mouseX
This variable holds the current vertical position of the mouse. The value is the number of pixels from the origin (0, 0) of the canvas.
mouseY
This boolean variable is True when the mouse is currently pressed, otherwise it is False.
mouseIsPressed
setCanvasSize(400, 400) forever: if wasMousePressed(): print("Mouse was pressed") sleep(0.005)
Returns True if the mouse has been pressed and not yet released before this function is called. Otherwise, it returns False. Once the mouse has been pressed and the function has been called, the function will then return False until the mouse is pressed again. This is different from the mouseIsPressed inbuilt boolean variable which continues to be set to True until the mouse is released.
wasMousePressed()
This function takes no parameters.
setCanvasSize(400, 100) background(220, 220, 220) text("I love PyAngelo!", 20, 30)
setCanvasSize(800, 100) background(220, 220, 220) text("I'm a new font that is big!", 20, 30, 50, 'Times New Roman')
Draws text to the screen. The first 3 parameters are mandatory. The first specified the text to display. The second is the x position and the third is the y position. The fourth parameter is optional and is the size of the text. This defaults to 20 pixels. The fifth parameter is optional is the font to use. The font defaults to Arial.
text(text, x, y, fontSize, fontName)
text - The text to display.
x - The x position of the top left of the text.
y - The y position of the top left of the text.
fontSize - The size of the text in pixels.
fontName - The type of font to use when displaying the text.
setCanvasSize(300, 300) hero = Image("/samples/images/PyAngelo.png") hero.draw(50, 100) hero.dispose()
Loads an image into memory which can later be displayed with the draw(), drawRegion(), or drawFrame() methods. Use dispose() to unload the image and free its resources when no longer needed.
file - The location of the image file to load.
Alias for Image(file)
.
alpha - Number between 0 (transparent) and 1 (opaque).
angle - Rotation angle in radians (or degrees if angleMode is set to DEGREES).
scaleX - Horizontal scale factor.
scaleY - Vertical scale factor (optional; defaults to scaleX).
flag - 0 to disable smoothing (pixel-art style), 1 to enable.
frameW - Width of each frame in a sprite sheet.
frameH - Height of each frame.
flag - 0 or false to disable horizontal flip, 1 or true to enable.
flag - 0 or false to disable vertical flip, 1 or true to enable.
ox - X coordinate of the pivot point or the string "center".
oy - Y coordinate of the pivot point or "center" (optional; defaults to ox).
x - X coordinate where the image’s origin will be placed.
y - Y coordinate where the image’s origin will be placed.
width - Optional drawing width (defaults to image.width).
height - Optional drawing height (defaults to image.height).
sx, sy - Source x and y of the sub-region.
sw, sh - Width and height of the source sub-region.
dx, dy - Destination x and y on the canvas.
dw, dh - Optional destination width and height (defaults to sw and sh).
index - Frame index in the sprite sheet (0-based).
x, y - Destination coordinates on the canvas.
scaleW, scaleH - Optional scaling of the frame (defaults to frameWidth and frameHeight).
Release the image’s underlying resources and remove it from memory.
Each image object has the following public properties:
# Example 1: Rotating and scaling an image setCanvasSize(400, 400) hero = Image("/samples/images/PyAngelo.png") hero.setRotation(90) hero.setPivot('center') hero.setScale(1.5) hero.draw(150, 150) hero.dispose() # Example 2: Drawing a sprite sheet frame setCanvasSize(400, 400) sprites = Image("/samples/images/alien-spritesheet.png") sprites.setFrameSize(16, 20) sprites.setSmoothing(False) sprites.drawFrame(4, 100, 200, 160, 200) sprites.dispose() # Example 3: Drawing a sub-region of a larger image setCanvasSize(400, 400) bg = Image("/samples/endless-runner/gameOverBackground.png") bg.drawRegion(50, 50, 100, 100, 300, 300) bg.dispose()
setCanvasSize(640, 360) background(220, 220, 220) translate(width/2, height/2) # translate to the center of the screen rectMode(CENTER) angleMode(RADIANS) rotate(1) rect(0, 0, 50, 50)
Sets the type of angle to use in many functions. This takes 1 parameter and it is suggested to use the constants of DEGREES and RADIANS when calling this function for clarity.
angleMode(mode)
mode - an integer where 1 represents RADIANS and 2 represents DEGREES.
setCanvasSize(640, 360) background(220, 220, 220) rect(0, 0, 50, 50) # Draw rect at original 0,0 translate(50, 50) rect(0, 0, 50, 50) # Draw rect at new 0,0 translate(25, 10) rect(0, 0, 50, 50) # Draw rect at new 0,0
Moves the position of the origin. The first parameter specifies the number of pixels along the x axis, and the second paramter specifies the number of pixels along the y axis.
If tranlate is called twice, the effects are cumulative. So calling translate(10, 10) followed by translate(20, 20) is the same as calling translate(30, 30). The saveState() and restoreState() functions can be used to save and restore transformations.
translate(x, y)
x - The number of pixels to move the origin along the x axis.
y - The number of pixels to move the origin along the y axis.
setCanvasSize(640, 360) background(220, 220, 220) translate(width/2, height/2) # translate to the center of the screen rectMode(CENTER) rotate(45) rect(0, 0, 50, 50)
Rotates the shape by the angle specified in the only parameter. By default, the angle is in degrees. This can be changed to radians by using the angleMode() function.
Shapes are rotated around the origin. Positive numbers rotate in a clockwise direction. Rotations are cumulative so calling rorate(45) followed by rotate(30) is the same as calling rotate(75). The saveState() and restoreState() functions can be used to save and restore transformations.
rotate(angle)
angle - The number of of degrees or radians to rotate the shape depending on the angleMode.
setCanvasSize(640, 360) fill(100, 220, 100, 0.5) for i in range(5): applyMatrix(1, i*0.1, i*-0.1, 1, i*30, i*10) rect(0, 0, 250, 100)
The applyMatrix() method lets you scale, rotate, move, and skew the current context.
applyMatrix(a, b, c, d, e, f)
a - Horizontal scaling
b - Horizontal skewing
c - Vertical skewing
d - Vertical scaling
e - Horizontal moving
f - Vertical moving
setCanvasSize(640, 360) translate(250, 200) shearX(45) rect(0, 0, 30, 30)
Skews the shape around the x-axis by the angle specified in the only parameter. By default, the angle is in degrees. This can be changed to radians by using the angleMode() function. The skew is relative to the origin.
shearX(angle)
angle - The number of of degrees or radians to shear the shape around the x-axis depending on the angleMode.
setCanvasSize(640, 360) translate(250, 200) shearY(45) rect(0, 0, 30, 30)
Skews the shape around the y-axis by the angle specified in the only parameter. By default, the angle is in degrees. This can be changed to radians by using the angleMode() function. The skew is relative to the origin.
shearY(angle)
angle - The number of of degrees or radians to shear the shape around the y-axis depending on the angleMode.
setCanvasSize(640, 360) background(220, 220, 220) saveState() translate(width/2, height/2) # translate to the center of the screen rectMode(CENTER) rotate(45) rect(0, 0, 50, 50) restoreState() rectMode(CORNER) rect(0, 0, 50, 50)
Saves the current drawing style settings and transformations. These can be restored using the restoreState() function. This allows you to change the style and transformation settings and then return to the previous version of these settings.
This function saves the settings of the fill(), stroke(), strokeWeight(), translate(), and rotate() functions.
saveState()
setCanvasSize(640, 360) background(220, 220, 220) saveState() translate(width/2, height/2) # translate to the center of the screen rectMode(CENTER) rotate(45) rect(0, 0, 50, 50) restoreState() rectMode(CORNER) rect(0, 0, 50, 50)
Restores the latest version of the drawing style settings and transformations. To save these settings the saveState() function must be used. This allows you to change the style and transformation settings and then return to the previous version of these settings.
This function restores the previously saved settings of the fill(), stroke(), strokeWeight(), translate(), and rotate() functions.
restoreState()
setConsoleSize(SMALL_SCREEN)
setConsoleSize(MEDIUM_SCREEN)
setConsoleSize(LARGE_SCREEN)
Sets the size of the console in pixels. The first and only parameter is an integer that must be between between 100 and 2000. The PyAngelo constants of SMALL_SCREEN (100), MEDIUM_SCREEN (500), and LARGE_SCREEN (1000) can be used.
setConsoleSize(size)
size - The height of the console in pixels.
setTextSize(SMALL_FONT)
setTextSize(MEDIUM_FONT)
setTextSize(LARGE_FONT)
Sets the size of the text printed to the console in pixels. The first and only parameter is an integer that must be between between 8 and 128. The PyAngelo constants of SMALL_FONT (8), MEDIUM_FONT (16), and LARGE_FONT (24) can be used.
setTextSize(size)
size - The size of the text in pixels.
setTextColour(RED) print("I am red.")
Sets the text colour for any print statements which will be output on the console. The following constants should be used as a parameter:
setTextColour()
colour - An integer between 1 and 22 represeting the colour. The above constants should be used for clarity.
setTextColour(RED) setHighlightColour(WHITE) print("I am red text on a white background.")
Sets the highlight or background colour for any print statements which will be output on the console. The following constants should be used as a parameter:
setHighlightColour()
colour - An integer between 1 and 22 represeting the colour. The above constants should be used for clarity.
print("I am displayed but will be removed after 1 second. Help!") sleep(1) clear()
clear(RED)
Clears the console.
clear(colour)
colour - The colour of the console after the screen is cleared. This is an optional parameter. If no colour is specified, a black colour will be displayed. The parameter is an integer from 1 to 22 but the following constants should be used for clarity:
To use the sprite library you need to import it using the following code:
from sprite import *
from sprite import * setCanvasSize(500, 400) pyangelo = Sprite("/samples/images/PyAngelo.png", 100, 75) imposter = Sprite("/samples/images/PyAngelo.png", 300, 75) while True: background(220, 220, 220) pyangelo.draw() imposter.draw() pyangelo.moveBy(1, 1) imposter.moveBy(-1, 1) if pyangelo.overlaps(imposter): text("I found you imposter!", 0, 0, fontSize=30) sleep(0.005)
The Sprite class loads an image specified as the first parameter at a starting position specified by the second and third parameters. You can also specify the optional parameters of width, height, and opacity for the image.
The image specifies the location on the Internet of the image to use. This is the only mandatory parameter, the rest are optional. The x and y parameters specify the starting position of the Sprite. The width and height parameters can adjust the size of the image and the opacity will change the transparency of the image. The angle will rotate the sprite with a positive angle indicating a clockwise rotation and a negative number an anti-clockwise rotation.
Draws the Sprite's image to the canvas at the Sprite's X and Y position.
Updates the Sprite's position by x pixels along the x axis, and y pixels along the y axis.
Updates the Sprite's position to the (x, y) coordinate.
Returns True if this Sprite overlaps with the "other" Sprite passed in as the first parameter. If the two Sprites do not overlap then False is returned. The overlap method uses the bounding rectangle principle to check if the Sprites are overlapping.
Returns True if the point passed in as the first parameter is inside the area occupied by this Sprite, otherwise it returns False.
Rotates the sprite around its centre by the angle specified. By default the angle is specified in degrees. This can be changed to radians with the angleMode() function.
from sprite import * setCanvasSize(500, 400) hello = TextSprite("Hello", 100, 75) hello.setColour(255, 100, 200) smiley = TextSprite("☺️", 300, 75, fontSize=50) while True: background(220, 220, 220) hello.draw() smiley.draw() hello.moveBy(1, 1) smiley.moveBy(-1, 1) if hello.overlaps(smiley): text("Hello there good friend", 0, 0, fontSize=30) sleep(0.005)
The TextSprite class inherits from the Sprite class and so it has the same methods draw(), moveBy(), moveTo(), contains(), overlaps(), and rotate(). However the first parameter passed to a TextSprite is the text to display. This text can also be an emoji.
The text parameter specifies what text will be displayed by the draw() method. This is the only mandatory parameter, the rest are optional. The x and y parameters specify the starting position of the Sprite. The fontSize specified the size of the text, the fontName specifies the type of font to use, and the r, g, b, and a parameters specify the colour and transparency of the text. The angle will rotate the text with a positive angle indicating a clockwise rotation and a negative number an anti-clockwise rotation.
This method sets the colour and transparency of the text.
from sprite import * setCanvasSize(500, 400) r = RectangleSprite(100, 100, 50, 50) r.setColour(255, 10, 170) r.noStroke() xSpeed = 1 ySpeed = 1 while True: background(220, 220, 220) r.draw() r.moveBy(xSpeed, ySpeed) if r.x >= width - r.width: r.x = width - r.width xSpeed *= -1 elif r.x <= 0: r.x = 0 xSpeed *= -1 if r.y >= height - r.height: r.y = height - r.height ySpeed *= -1 elif r.y <= 0: r.y = 0 ySpeed *= -1 sleep(0.005)
The RectangleSprite class inherits from the TextSprite class and so it has the same methods draw(), setColour(), moveBy(), moveTo(), contains(), overlaps(), and rotate(). However the first four parameter passed to a RectangleSprite are the x and y coordinates and the width and height of the rectangle.
The first four parameter specify the x and y coordinates and the width and height of the rectangle. The first four parameters are mandatory, the rest are optional. The r, g, b, and a parameters specify the colour and transparency of the rectangle. The angle will rotate the rectangle with a positive angle indicating a clockwise rotation and a negative number an anti-clockwise rotation.
This updates the rectangle so no border will be drawn when the draw() method is called.
This method ensures the rectangle is drawn with a border of the colour and transparency specified by the r, g, b, and a parameters.
Specifies in pixels, how thick the border should be around the rectangle.
from sprite import * setCanvasSize(500, 400) c = CircleSprite(100, 100, 50) c.setColour(255, 10, 170) c.noStroke() xSpeed = 1 ySpeed = 1 while True: background(100, 100, 200) c.draw() c.moveBy(xSpeed, ySpeed) if c.x >= width - c.radius: c.x = width - c.radius xSpeed *= -1 elif c.x <= c.radius: c.x = c.radius xSpeed *= -1 if c.y >= height - c.radius: c.y = height - c.radius ySpeed *= -1 elif c.y <= c.radius: c.y = c.radius ySpeed *= -1 sleep(0.005)
The CircleSprite class inherits from the RectangleSprite class and so it has the same methods draw(), stroke(), noStroke(), strokeWeight(), setColour(), moveBy(), moveTo(), contains(), and overlaps(). However the first three parameter passed to a CircleSprite are the x and y coordinates of the center of the circle, and the radius of the circle.
The first three parameter specify the x and y coordinates of the center of the circle and the radius of the circle. The first three parameters are mandatory, the rest are optional. The r, g, b, and a parameters specify the colour and transparency of the circle.
from sprite import * setCanvasSize(500, 400) e = EllipseSprite(100, 100, 50, 25) e.setColour(255, 10, 170) e.stroke(255, 0, 0) xSpeed = 1 ySpeed = 1 while True: background(100, 100, 200) e.draw() e.moveBy(xSpeed, ySpeed) if e.x >= width - e.radiusX: e.x = width - e.radiusX xSpeed *= -1 elif e.x <= e.radiusX: e.x = e.radiusX xSpeed *= -1 if e.y >= height - e.radiusY: e.y = height - e.radiusY ySpeed *= -1 elif e.y <= e.radiusY: e.y = e.radiusY ySpeed *= -1 sleep(0.005)
The EllipseSprite class inherits from the RectangleSprite class and so it has the same methods draw(), stroke(), noStroke(), strokeWeight(), setColour(), moveBy(), moveTo(), contains(), overlaps(), and rotate(). However the first four parameter passed to a EllipseSprite are the x and y cooridinates of the center of the circle, and the X radius and Y radius of the ellipse.
The first four parameter specify the x and y coordinates of the center of the ellipse and the X radius and Y radius of the ellipse. The first four parameters are mandatory, the rest are optional. The r, g, b, and a parameters specify the colour and transparency of the ellipse. The angle will rotate the ellipse with a positive angle indicating a clockwise rotation and a negative number an anti-clockwise rotation.
setCanvasSize(640, 360) x = 0 radius = 50 sleepSeconds = 0.005 noStroke() fill(255, 255, 0, 0.7) while True: background(0, 0, 0) circle(x, 180, radius) x += 1 if x > width + radius: x = -radius sleep(sleepSeconds)
The sleep() function causes the program to suspend for the number of seconds specified by the first parameter. This is extremely useful for animation purposes inside a while loop as shown in the example above. Try changing some of the variables in the program to see the effect it has.
sleep(delay)
delay - The number of seconds to delay the program for.
# Load a sound file and keep the object music = Sound("/samples/music/Myth.mp3") # Play, pause, and stop control: music.play() music.pause() music.stop()
Creates a new Sound
instance for the given file URL. You can then call methods on that instance to control playback, volume, looping, etc.
filename
– A string URL to the sound file.sound.play() # start or resume playback
Starts or resumes the sound. If the sound was paused, it picks up from where it left off; otherwise it begins at the current seek position (default 0.0).
sound.pause() # temporarily halt playback
Pauses the sound at its current position. A subsequent play()
will resume from this point.
sound.stop() # halt and reset position to 0.0
Stops playback and resets the playhead to the start (0.0 seconds). Loop and volume settings remain unchanged.
Returns True
if the sound is currently playing (not paused), otherwise False
.
Without arguments, returns the current playhead position in seconds (0.0 before play). With a position
argument (in seconds), jumps to that time and returns None
.
When called without arguments, returns the current playback rate (a multiplier, default 1.0). With speed
> 0, sets a new rate (e.g. 2.0 for double speed) and returns None
.
Without arguments, returns the current volume (0.0–1.0). With level
between 0.0 and 1.0, sets the volume and returns None
.
With no arguments, returns whether looping is currently enabled. With state
=True
or False
, toggles looping and returns None
.
Without arguments, returns current mute state. With a boolean state
, mutes or unmutes the sound.
Fade volume from from
→to
(both 0.0–1.0) over duration
seconds.
Returns the total length of the sound in seconds.
Stops playback (if any), unloads the audio from memory, and removes the instance from internal registries.
# static call on the class: Sound.stopAll() # or from an instance: music.stopAll()
Stops every Sound
instance currently registered, no matter what file they’re playing.
# Create and configure a Sound music = Sound("/samples/music/Myth.mp3") music.volume(0.5) # half volume music.loop(True) # repeat forever music.play() # …later, pause and inspect… music.pause() print("At", music.seek(), "seconds") # and finally stop everything Sound.stopAll()
This variable holds the width of the canvas. The default width of the canvas is 500 pixels and can be changed by calling the setCanvasSize() function.
width
This variable holds the height of the canvas. The default height of the canvas is 400 pixels and can be changed by calling the setCanvasSize() function.
height
This variable holds the width of the web browser's window minus 15 pixels.
windowWidth
This variable holds the height of the web browser's window minus 15 pixels.
windowHeight
setCanvasSize(100, 100) forever: background(200) leftWall = 25 rightWall = 75 # xm is just the mouseX, while # xc is the mouseX, but constrained # between the leftWall and rightWall! xm = mouseX xc = constrain(mouseX, leftWall, rightWall) # Draw the walls. stroke(150, 150, 150) line(leftWall, 0, leftWall, height) line(rightWall, 0, rightWall, height) # Draw xm and xc as circles. noStroke() fill(150, 150, 150) ellipse(xm, 33, 9, 9) # Not Constrained fill(0, 0, 0) ellipse(xc, 66, 9, 9) # Constrained
Constrains a value between a minimum and maximum value.
constrain(n, low, high)
n - The number to constrain
low - The minimum limit
high - The maximum limit
from math import * setCanvasSize(500, 400) fill(0, 0, 0) x1 = 20 y1 = height - 50 angleMode(RADIANS) while True: saveState() background(220, 220, 220) x2 = mouseX y2 = mouseY line(x1, y1, x2, y2) circle(x1, y1, 5) circle(x2, y2, 5) d = int(dist(x1, y1, x2, y2)) # Let's write d along the line we are drawing translate((x1+x2)/2, (y1+y2)/2) rotate(atan2(y2-y1, x2 - x1)) text(d, 0, -20) restoreState()
Calculates the distance between two points.
dist(x1, y1, x2, y2)
x1 - The x coordinate of the first point.
y1 - The y coordinate of the first point.
x2 - The x coordinate of the second point.
y2 - The y coordinate of the second point.
from math import * setCanvasSize(500, 400) while True: r = mapToRange(mouseX, 0, width, 0, 255) fill(int(r), 0, 0) circle(width/2, height/2, 50) sleep(0.005)
Re-maps a number from one range to another.
mapToRange(value, start1, stop1, start2, stop2, withinBounds)
value - The incoming value to be converted.
start1 - The lower bound of the current range.
stop1 - The upper bound of the current range.
start2 - The lower bound of the target range.
stop2 - The upper bound of the target range.
withinBounds - Should the value be constrained to the target range.
QUARTER_PI is a mathematical constant with a value of 0.7853982.
HALF_PI is a mathematical constant with a value of 1.57079632679489661923.
PI is a mathematical constant with a value of 3.14159265358979323846.
TWO_PI is a mathematical constant with a value of 6.28318530717958647693.
TAU is a mathematical constant with a value of 6.28318530717958647693. It is equal to TWO_PI.
DEGREES is a constant that is used with the angleMode() function to inform PyAngelo to use degrees for the rotate() and arc() functions.
RADIANS is a constant that is used with the angleMode() function to inform PyAngelo to use radians for the rotate() and arc() functions.
CARTESIAN is a constant that is used with the setCanvasSize() function to inform PyAngelo to use a maths based y-axis where the y value increases as you move up the canvas.
JAVASCRIPT is a constant that is used with the setCanvasSize() function to inform PyAngelo to use a JavaScript based y-axis where the y value increases as you move down the canvas.
KEY_A through to KEY_Z are constants that can be used with the isKeyPressed function to check if the A through to the Z key has been pressed. In addition there is also KEY_SPACE, KEY_ENTER, KEY_ESCAPE, KEY_DEL, KEY_BACKSPACE, KEY_TAB, KEY_LEFT, KEY_RIGHT, KEY_UP and KEY_DOWN.