You can download this code by clicking the button below.
This code is now available for download.
This code uses the Pyglet library to randomly draw circles, rectangles, triangles, and ellipses in a window. The user can close the window by pressing a key.
Technology Stack : Pyglet
Code Type : Graphics drawing
Code Difficulty : Intermediate
import random
import pyglet
from pyglet.window import key
from pyglet.window import Window
from pyglet.graphics import draw
def draw_random_shapes(window):
shapes = ['circle', 'rectangle', 'triangle', 'ellipse']
color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
shape = random.choice(shapes)
x = random.randint(50, window.width - 50)
y = random.randint(50, window.height - 50)
size = random.randint(50, 100)
if shape == 'circle':
draw_circle(window, x, y, size, color)
elif shape == 'rectangle':
draw_rectangle(window, x, y, size, color)
elif shape == 'triangle':
draw_triangle(window, x, y, size, color)
elif shape == 'ellipse':
draw_ellipse(window, x, y, size, color)
def draw_circle(window, x, y, size, color):
points = [x + size/2, y - size/2,
x - size/2, y - size/2,
x - size/2, y + size/2,
x + size/2, y + size/2]
draw(points, 'v', color=color)
def draw_rectangle(window, x, y, size, color):
points = [x, y,
x + size, y,
x + size, y + size,
x, y + size]
draw(points, 'v', color=color)
def draw_triangle(window, x, y, size, color):
points = [x, y,
x + size/2, y + size,
x + size, y]
draw(points, 'v', color=color)
def draw_ellipse(window, x, y, size, color):
points = [x - size/2, y - size/2,
x - size/2, y + size/2,
x + size/2, y + size/2,
x + size/2, y - size/2]
draw(points, 'v', color=color)
def main():
window = Window(width=800, height=600, caption='Random Shapes')
window.on_draw = draw_random_shapes
window.on_key_press = lambda symbol: window.close()
pyglet.app.run()
if __name__ == '__main__':
main()