Week 4 - Section 2 - The Game

Site: ΕΛ/ΛΑΚ Moodle
Course: Python Lab - May 2017
Book: Week 4 - Section 2 - The Game
Printed by: Guest user
Date: Friday, 3 May 2024, 3:29 AM

Description

In this section we will learn about Graphics

Chapter 7.1 - I have spaceship

7.1 - I have spaceship, do you want a ride?

Most of the time we do not create objects using the draw command of pygame but we use sprites. 

One of this sprites that we will use is a spaceshipspaceship
Sprites are usually in png or gif format. To use this sprite it must be in the same folder as our program.

Right click on the spaceship and save it or click here.

Also download and open this file (avoid_v0.1) to Thonny. Run the program.

What is the result?

This is another sprite of a meteor meteor
Right click on the spaceship and save it or click here.

Look at the lines 19 and 50 and try to show (blit) the meteor inside the screen.
Can you show multiple rocks?

You can download the code from here to display the spaceship.

Chapter 7.2 - Move with Keyboard

7.2 - Move with the Keyboard

Download  the code from here and open it to Thonny.

Study the lines 41 to 59

if event.type == pygame.KEYDOWN: if event.key == pygame.K_RIGHT or event.key == pygame.K_d: ship_x_speed = 5 if event.key == pygame.K_LEFT or event.key == pygame.K_a: ship_x_speed = -5 if event.key == pygame.K_DOWN or event.key == pygame.K_s: ship_y_speed = 5 if event.key == pygame.K_UP or event.key == pygame.K_w: ship_y_speed = -5 if event.type == pygame.KEYUP: if event.key == pygame.K_RIGHT or event.key == pygame.K_LEFT: ship_x_speed = 0 if event.key == pygame.K_d or event.key == pygame.K_a: ship_x_speed = 0 if event.key == pygame.K_UP or event.key == pygame.K_DOWN: ship_y_speed = 0 if event.key == pygame.K_w or event.key == pygame.K_s: ship_y_speed = 0


In these lines pygame checks if arrow keys LEFT, RIGHT, UP, DOWN or keys d, a , s, w are pressed down (KEYDOWN) or released (KEYUP) and moves spaceship accordingly.

In lines 30 to 33 which are outside the main loop we set the starting position of the spaceship and the starting speed in each axis to 0

ship_x = 500 ship_y = 380 ship_x_speed = 0 ship_y_speed = 0


And finally lines 74 to 87 where we show the spaceship, move i and make sure that it stays inside the screen

screen.blit(spaceshipImg, (ship_x, ship_y)) if ship_x >= 0 and ship_x <= 984: ship_x += ship_x_speed elif ship_x < 0: ship_x = 1 elif ship_x > 984: ship_x = 983 if ship_y >= 0 and ship_y <= 728: ship_y += ship_y_speed elif ship_y < 0: ship_y = 1 elif ship_y > 728: ship_y = 727 print(ship_x, ship_y)


The final version to PLAY, finally, is here.

avoid the rocks