Pygame

Grey overlay

Pink

Green

Blue

Cream

Liliac

Purple

Yellow

Keyboard events

Download It

Learn It

  • As we are making a game for the PC platform, the keyboard is a very important input tool.
  • We are going to control the moment of a player on the screen with the arrow keys. Add these lines of code inside the game loop, inside your for loop.
  • Put the code immediately underneath the gameState = "exit" line.
  • Note: As always, you'll need to ensure the code is indented for it to work.
if event.type == pygame.KEYDOWN:
    if event.key == pygame.K_LEFT:
	print("Left")
    if event.key == pygame.K_RIGHT:
	print("Right")
  • The code will look like this:

4-0.PNG

  • If you run this code and look in the interpreter window, you'll be able to see the program letting you know when you press left and right. You might be able to add up and down for yourself too.

Learn It

  • Let's now get the shape moving around on the screen when left/right keys are pressed.
  • Our pseudocode for this will be…
Set up variables: XPos=100 and YPos=100 for the player's position.

BEGIN LOOP
    IF player presses the left arrow THEN
        player1XPos = player1XPos - 5
    ELSE IF player presses the right arrow THEN
        player1XPos = player1XPos + 5
    END IF

    Re-draw the sprite at player1XPos, player1YPos.
END LOOP

Try It

  • We'll start by adding our variables.
  • Add these lines of code directly below the gameState="running" line.
player1XPos = 100
player1YPos = 100
  • The code will look like this:

4-1.png

  • We then create event listeners in the game loop.
  • To do this, change the lines that say print("left") and print("right") to say…
if event.type == pygame.KEYDOWN:
    if event.key == pygame.K_LEFT:
	player1XPos -= 5
    elif event.key == pygame.K_RIGHT:
	player1XPos += 5
  • Your code should look like this:

4-2.PNG

  • Run the program. You will find the player moves each time the key is pressed.
  • This is good for some games but other times it is desirable to keep the player moving until another key is pressed (like in snake-type games). Currently the Event Listener and the Event Handler are in the same block of code.
  • We will separate the two out for continous movement
  • We will need 2 new variables outside of the game loop to hold the player's speed and direction.
  • The pseudocode for our new movement program is:
Set up variables:
   player1Direction = "nothing"
   player1Speed = 5
   player1XPos = 100
   player1YPos = 100

BEGIN LOOP
    Has the player used the mouse or keyboard?
       YES: Has the player pushed the left arrow?
               YES: player1Direction is left
            Has the player pushed the right arrow?
               YES: player1Direction is right

    Is the player1Direction left?
        YES: Decrease the player1XPos variable by 5.
    Is the player1Direction right?
        YES: Increase the player1XPos variable by 5.

    Clear the screen, and draw the player1 shape at player1XPos, player1YPos. 
END LOOP
  • Let's implement this in code.
  • Add these variables underneath the player1YPos = 100 line:
player1Direction = ""
player1Speed = 5
  • This should look like this:

4-3.png

  • Next, we'll change the game loop to modify the event listener and all and event handler.
  • Replace your game loop code with this code. Ensure you keep all the indents where they should be. You may find you need to tweak the indents with the tab key once you've pasted the code.
while gameState != "exit":  # game loop - note: everything in the mainloop is indented one tab
    for event in pygame.event.get():  # get user interaction events
	if event.type == pygame.QUIT:  # tests if window's X (close) has been clicked
	    gameState = "exit"  # causes exit of game loop
	if event.type == pygame.KEYDOWN:
	    if event.key == pygame.K_LEFT:
		# player1XPos -= 5
		player1Direction = "left"
	    elif event.key == pygame.K_RIGHT:
		# player1XPos += 5
		player1Direction = "right"

    # Player 1 Event handler code now...
    if player1Direction == "left":
	player1XPos -= player1Speed
    elif player1Direction == "right":
	player1XPos += player1Speed

    screen.fill(black)
    player1 = pygame.draw.rect(screen, green, (player1XPos, player1YPos, 20, 20))
  • This will look like this:

4-4.png

  • Run the program with Shift-F10, and steer the square with the left/right cursor keys.
  • What's different between this code and the previous version?
  • Comment the lines of code to explain what they do.

Badge Tasks

  • Silver: Add the ability to move player1 up and down or add comments to your code to explain how it works.
  • Gold: Add the functionality to increase and decrease player1Speed with the Q and W keys.
  • Platinum: Add a feature to make player1 visible/invisible when the space bar is pressed, or stop the square from travelling beyond the edge of the window.

Badge It

  • Be honest and take the quiz using the link below to assess your own progress. Your teacher will randomly check some students work to moderate their marking.
  • Once you have done above tasks and tested they are working as intended, click here for the self assessment.