Scene Switching

Goals

  • Use if statements to draw different scenes depending on a scene variable.

  • Use keys to change the scenes

Starter code

Pygame Template

Video Tutorial

What you need to do

  • Add another scene

  • When the last scene has been reached, wrap back to the first scene.

  • Implement the ability for the left arrow key to go to the previous scene.

  • Factor out each scene into its own function

Final Code

 1# Scene Switching - Final
 2
 3import pygame
 4from pygame.locals import K_ESCAPE, KEYDOWN, QUIT, K_RIGHT, K_LEFT
 5
 6pygame.init()
 7pygame.font.init()
 8
 9WIDTH = 640
10HEIGHT = 480
11SIZE = (WIDTH, HEIGHT)
12
13screen = pygame.display.set_mode(SIZE)
14clock = pygame.time.Clock()
15
16# ---------------------------
17# Initialize global variables
18
19circle_x = 200
20circle_y = 200
21scene_title_font = pygame.font.SysFont('Arial', 50)
22current_screen = 0
23 
24# ---------------------------
25
26running = True
27while running:
28    # EVENT HANDLING
29    for event in pygame.event.get():
30        if event.type == KEYDOWN:
31            if event.key == K_ESCAPE:
32                running = False
33            elif event.key == K_RIGHT:
34                current_screen += 1
35                print(current_screen)
36        elif event.type == QUIT:
37            running = False
38    
39    # GAME STATE UPDATES
40    # All game math and comparisons happen here
41
42    # DRAWING
43    screen.fill((255, 255, 255))  # always the first drawing command
44
45    if current_screen == 0:
46        # Scene 1 (Menu screen)
47        screen.fill((0, 0, 128))  # always the first drawing command
48        scene_title = scene_title_font.render('Menu Screen', True, (255, 255, 255))
49        screen.blit(scene_title, (0, 0))
50    elif current_screen == 1:
51        # Scene 2 (Instructions screen)
52        screen.fill((128, 0, 0)) 
53        scene_title = scene_title_font.render('Instructions Screen', True, (255, 255, 255))
54        screen.blit(scene_title, (0, 0))
55
56    # Must be the last two lines
57    # of the game loop
58    pygame.display.flip()
59    clock.tick(30)
60    #---------------------------
61
62
63pygame.quit()