Lecture 34 - Gamebox

Lecture Date: Friday, November 13

We start the game project today (well, yesterday in lab) and we’ll look at some of the neat things you can do with PyGame and gamebox! I’ll also explain how to install everything if you were not successful during lab.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# starfield simulation

import pygame
import gamebox
import random
camera = gamebox.Camera(800,600)
stars = []
counter = 0

def tick(keys):
    global counter
    counter += 1

    if counter % 5 == 0:
        numstars = random.randint(0,7)
        for i in range(numstars):
            stars.append(gamebox.from_color(random.randint(5,795),0,"white",3,3))

    camera.clear("black")

    for star in stars:
        # move the star
        star.y += 3
        if(star.y > 600):
            stars.remove(star)
        # draw the star
        camera.draw(star)

    camera.display()

ticks_per_second = 30

# keep this line the last one in your program
gamebox.timer_loop(ticks_per_second, tick)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# infinite jumper

import pygame
import gamebox
import random

camera = gamebox.Camera(800,600)
character = gamebox.from_color(50, 200, "green", 15, 40)
character.yspeed = 0
walls = [
    gamebox.from_color(50,250, "black", 200, 10),
    gamebox.from_color(400,150, "black", 200, 10),
    gamebox.from_color(600,25, "black", 200, 10),
]

counter = 0

def tick(keys):
    # get access to the counter
    global counter
    if pygame.K_RIGHT in keys:
        character.x += 10
    if pygame.K_LEFT in keys:
        character.x -= 10
    character.yspeed += 1
    character.y = character.y + character.yspeed
    camera.clear("cyan")
    camera.draw(character)

    # makes the screen scroll
    camera.y -= 3

    # make random walls appear every time the counter hits a particular number
    # notice how I use the random.randint to vary the height of the platform
    # also I add in the camera.x to the x position because the screen keeps moving
    counter += 1
    if counter % 50 == 0:
        new_wall = gamebox.from_color(random.randint(200,600), camera.y-300,  "black", random.randint(100,250), 10)
        walls.append(new_wall)


    for wall in walls:
        if character.bottom_touches(wall):
            character.yspeed = 0
            if pygame.K_SPACE in keys:
                character.yspeed = -20
        if character.touches(wall):
            character.move_to_stop_overlapping(wall)
        camera.draw(wall)

    camera.display()


ticks_per_second = 30

# keep this line the last one in your program
gamebox.timer_loop(ticks_per_second, tick)