Task: Add a Cheat to stop crashing
STEP ONE: ADD IN AN ADDITIONAL KEY EVENT
Find the section in the code where you are looking for key board events
HINT: It is in the Game Loop inside the
for event in pygame.event.get():
You will find code which runs when there is an event.type of KEYDOWN
(i.e. a key is pressed)
After the code for the left arrow and the right arrow you will need to add some code for another key
i.e. Down Arrow
if event.key == pygame.K_DOWN:
x = 50
(Remember that python is an indentation language: This means you need to make sure your code is indented to match the code block it is in.)
this will move your car to an x position of 50 every time the Down arrow is presses.
Run your code and see its effect.
STEP TWO: MOVE THE CAR TO JUST MISS THE THING
Now we would like to modify the code so that instead of the car moving to the x position of 50, it moves just to the left of the thing coming down.
We can calculate this by using the following varibles
thing_startx = the x position of the current thing. (i.e. its left most)
car_width = the width of the car
We would like to move our car so that the whole car is just to the left of the thing.
x = thing_startx - car_width - 1
STEP THREE: ONLY MOVE THE CAR IF IT IS GOING TO CRASH
Now we want to modify our code so that it only fires if the car is going to crash.
We already have some code we use to determine of the car is going to crash.
It is in an IF statement used to display the “You Crashed” message.
if event.key == pygame.K_DOWN:
if x > thing_startx and x < thing_startx + thing_width or x+car_width > thing_startx and x + car_width < thing_startx+thing_width:
x = thing_startx - car_width - 1
STEP FOUR: YOU MIGHT MOVE OF THE SCREEN
If the thing is close the the left side of the screen, our code will now make you crash into the edge.
We need to check for this a move the other way if needed.
if x < 0:
x = thing_startx + thing_width + 1
STEP FIVE: MAKE YOUR CHEAT AUTOMATIC
If you are too lazy to press the down arrow, you could always run the code every game loop instead of when the down arrow is pressed.
Try shifting the code block so it is outside the event loop and see what happens.