import os os.environ['SDL_VIDEO_WINDOW_POS'] = "100,100" os.chdir(os.path.dirname(__file__)) from typing import TYPE_CHECKING if TYPE_CHECKING: from pgzero.builtins import screen, Actor, keyboard, keys import pgzrun import math from pgzhelper import * import random # Treasure Hunt # Catch the coin. Dodge the skull and the bomb. # random gives the game a different starting place every time # Set the size of the game window WIDTH = 800 HEIGHT = 600 ##### BACKGROUND ##### # The background picture is 800 by 600, so it fills the window bg = Actor('background') ##### SHIP ##### # The ship you steer, sitting near the bottom of the window ship = Actor('ship') ship.x = 400 ship.y = 500 ##### COIN ##### # The coin starts at the top, in a different place every game coin = Actor('coin') coin.x = random.randint(20, 780) coin.y = 0 ##### SKULL ##### # The skull drops the same way the coin does skull = Actor('skull') skull.x = random.randint(20, 780) skull.y = 0 ##### BOMB ##### # And so does the bomb bomb = Actor('bomb') bomb.x = random.randint(20, 780) bomb.y = 0 # Set up game variables score = 0 lives = 3 game_over = False # The colour of the writing, in one place so it is easy to change hud_colour = (255, 255, 255) def draw_hud(): # The writing the player reads goes in here screen.draw.text('Score: ' + str(score), (20, 20), color=hud_colour, fontsize=40) screen.draw.text('Lives: ' + str(lives), (630, 20), color=hud_colour, fontsize=40) def reset_to_top(actor): # Put a falling thing back at the top, somewhere new across actor.x = random.randint(20, 780) actor.y = 0 def update(): """ Runs every frame """ global score, lives, game_over ##### SHIP ##### # Move the ship left and right if keyboard.left: ship.x -= 5 if keyboard.right: ship.x += 5 # Stop the ship driving off the screen if ship.x < 60: ship.x = 60 if ship.x > 740: ship.x = 740 ##### COIN ##### # Move the coin down the page, faster the better you are doing if score > 10: coin.y += 8 elif score > 5: coin.y += 6 else: coin.y += 4 # Reset the coin at the top of the page once it hits the bottom if coin.y > 600: reset_to_top(coin) # Coin collision with ship if coin.colliderect(ship): #sounds.collect.play() reset_to_top(coin) score = score + 1 ##### SKULL ##### # Move the skull down the page skull.y += 4 # Reset the skull at the top of the page once it hits the bottom if skull.y > 600: reset_to_top(skull) # Skull collision with ship if skull.colliderect(ship): #sounds.lose.play() reset_to_top(skull) score -= 1 ##### BOMB ##### # Move the bomb down the page bomb.y += 4 # Reset the bomb at the top of the page once it hits the bottom if bomb.y > 600: reset_to_top(bomb) # Bomb collision with ship if bomb.colliderect(ship): #sounds.explosion.play() reset_to_top(bomb) lives -= 1 # When the lives run out, the game is over if lives == 0: game_over = True def draw(): bg.draw() ship.draw() coin.draw() skull.draw() bomb.draw() # The writing goes on LAST so nothing can paint over it draw_hud() pgzrun.go()