''' This is the main source code file for Gopher vs Zombies. ''' from __future__ import print_function #this lets the Python 2 interpreter use print as a function. import pygame from hole import Hole from gopher import Gopher from zombie import Zombie from board import Board import resources import sys board_tile_dimensions = (0,0) #the title of the game window game_title = "Gophers vs Zombies" #the default fill color of the main surface background_color = (250,240,172) #the game clock and frame timer via pygame clock = pygame.time.Clock() #the game board that contains the grass, holes, gophers and zombies. board = Board() #the gopher gopher = Gopher(0,4) #enum-style classes for game mode class GameModeInput: pass class GameModeStateUpdate: pass current_game_mode = GameModeInput #enum-style classes for player interaction class PlayerQuit: pass class PlayerUp: pass class PlayerDown: pass class PlayerLeft: pass class PlayerRight: pass class PlayerDig: pass class PlayerNone: pass #The action of the player for this round. Only valid during GameMode.player_input current_player_action = PlayerNone def determine_window_size_from_board_size(): """ Finds the resolution of the application's window based on the size of the game board. Parameters: none -- Note that this function uses the board_tile_dimensions global variable. Returns: (int, int): a tuple containing the resolution of the display window. """ #the width and height of the game board in tiles #this is the default dimension of the board #PROBLEM 1 global board_tile_dimensions board_tile_dimensions = (10,6) #the size of the entire game window. This is given a value later. window_size = (board_tile_dimensions[0]*80+160, board_tile_dimensions[1]*80+160) return window_size def update_game_state(board_config, player_action): """This is the 'think' portion of the game (i.e. the game logic or rules). Given the current state of the game (denoted by board_config) and the most recent player action, this function updates the board with one round of player and non-player character (e.g. zombie) action. First, the gopher is updated. This involves looking at the player_action and moving the gopher or adding a hole accordinly. Next, the board is scanned for zombies. For each zombie found, the zombie is asked as to what its next move should be (via that particular zombie's move method). The move is then enacted on the board which can result in a the zombie moving positions, a zombie/hole collision that removes both the zombie and the hole, or a zombie/gopher collision which ends the game. Parameters: board_config (list): The current state of the board. player_action (enum-like class): The player's most recent action. Returns: none: The board_config is modified via pass by reference. """ global board_tile_dimensions global gopher ''' Let the gopher move first ''' gopher_pos = board.find_gopher_pos(board_config) gopher_move = (0,0) if player_action is PlayerUp: gopher_move = (0, -1) gopher.direction = gopher.Up elif player_action is PlayerDown: gopher_move = (0, 1) gopher.direction = gopher.Down elif player_action is PlayerRight: gopher_move = (1, 0) gopher.direction = gopher.Right elif player_action is PlayerLeft: gopher_move = (-1, 0) gopher.direction = gopher.Left #dig a hole if player_action is PlayerDig: #PROBLEM 3 print("There should be a hole here but there is not!") board_config[gopher_pos[0]][gopher_pos[1]][0] = Hole()#printing a hole elif not player_action is PlayerNone: #check for going over edge of board new_gopher_pos = (gopher_pos[0] + gopher_move[0], gopher_pos[1] + gopher_move[1]) #PROBLEM 2.b #We only check for leaving the board on the top and bottom. if new_gopher_pos[1] < 0 or new_gopher_pos[1] >= board_tile_dimensions[1]: print("the gopher has left the board!") new_gopher_pos = gopher_pos sys.exit() #This ends the game. What would you do if you wanted the game to continue? #check for colliding with a zombie occupant_of_new_gopher_pos = board_config[new_gopher_pos[0]][new_gopher_pos[1]][1] if occupant_of_new_gopher_pos == "z" or isinstance(occupant_of_new_gopher_pos, Zombie): print("The jig is up -- game over!") sys.exit() #remove the gopher from it's old position board_config[gopher_pos[0]][gopher_pos[1]][1] = None #and move it to the new position board_config[new_gopher_pos[0]][new_gopher_pos[1]][1] = gopher #let the gopher know her own position gopher.x, gopher.y = new_gopher_pos ''' Time for zombies to move or be created. ''' #PROBLEM 4 #Can you create more zombies? #You will need to import the random library if you want to procedurally generate the zombies. #Creating a Zombie Randomly in each turn import random x = random.randint(0,10) y = random.randint(0,6) board_config[x][y] = [None, Zombie()] #BONUS PROBLEM 3.a #How can you regulate the number of zombies created? #BONUS PROBLEM 4 #Can you use a file to determine when zombies are created? zombie_count = 0 #scan the board for zombies for x in range(0,board_tile_dimensions[0]): for y in range(0, board_tile_dimensions[1]): occupant = board_config[x][y][1] #was a zombie found? if isinstance(occupant, Zombie): #a zombie was found, so increment the zombie_count zombie_count += 1 #get its move. If it is a "z", use the default move of (-1,0) zombie_move = (-1,0) if occupant is Zombie: zombie_move = occupant.move() #get its new position new_zombie_pos = (x+zombie_move[0], y+zombie_move[1]) #did the zombie reach the end of the board and end the game? if new_zombie_pos[0] < 0: print("The zombie reached the end of the board -- the world is lost!") sys.exit() #see if it fell in a hole tile_of_new_zombie_pos = board_config[new_zombie_pos[0]][new_zombie_pos[1]][0] if isinstance(tile_of_new_zombie_pos, Hole): print ("The zombie fell into a hole and died (again).") board_config[x][y][1] = None #remove the hole board_config[new_zombie_pos[0]][new_zombie_pos[1]][0] = None zombie_count -= 1 else: #move the zombie to its new position board_config[new_zombie_pos[0]][new_zombie_pos[1]][1] = occupant #remove it from the old position board_config[x][y][1] = None if zombie_count == 0: print("Congratulations! You have eliminated all of the zombies. You win!") sys.exit() #BONUS PROBLEM 3.b #How can you repeat the game with harder conditions? def initialize(window_size): """ Starts pygame, loads the art assets from disk into pygame data structures, and starts the application window. Parameters: window_size (int, int): The resolution of the game window. Returns: (pygame Surface): The main display window set to window_size dimensions. """ surface = pygame.display.set_mode(window_size, pygame.RESIZABLE & pygame.SRCALPHA) pygame.display.set_caption(game_title) resources.load_resources() Hole.load_resources() Gopher.load_resources() Zombie.load_resources() Board.load_resources() return surface def default_board_configuration(board_config): """A function that configures to board for a default and easy game. Parameters: board_config (list): A board configuration to alter via pass by reference. Returns: none: The return value is the altered board_config parameter. """ #board_config[row][col] = (tile_state, occupant) for x in range(0, len(board_config)): for y in range(0, len(board_config[0])): board_config[x][y] = [" ",None] board_config[3][0] = [Hole(), None] board_config[9][0] = [None, Zombie()] board_config[0][5] = [None, gopher] board_config[9][3] = [None, Zombie()] board_config[3][1] = [Hole(), None] board_config[9][4] = [None, Zombie()] def graphics_test_board_configuration(board_config): """A function that configures to board that test all combinations of graphics in the basic version of the game. Parameters: board_config (list): A board configuration to alter via pass by reference. Returns: none: The return value is the altered board_config parameter. """ #board_config[row][col] = (tile_state, occupant) for x in range(0, len(board_config)): for y in range(0, len(board_config[0])): board_config[x][y] = [" ",None] board_config[0][0] = [None, Zombie()] board_config[1][0] = [Hole(), Zombie()] board_config[2][0] = [None, Zombie()] board_config[3][0] = [Hole(), Zombie()] board_config[0][1] = [None, Gopher()] board_config[1][1] = [Hole(), Gohper()] board_config[2][1] = [None, Gopher()] board_config[3][1] = [Hole(), Gopher()] board_config[0][2] = [None, None] board_config[1][2] = [Hole(), None] def update_graphics_and_sound(surface, board_config, game_mode): """Clears the display, handles the timed frame update, asks the board to render a surface, renders that surface to the display window, and flips the display buffer. Parameters: surface (pygame Surface): The main window to render to. board_config (list): The current state of the board. game_mode (enum-like class): The current game mode. Returns: none: Graphics are updated on the window. """ deltaTime = clock.tick(30) surface.fill(background_color) surface.blit(board.render(deltaTime, board_config), (0,0)) pygame.display.flip() def ui_event_to_player_action(e): """Processes user interface events and maps them to player actions. Parameters: e (pygame.Event): The user interface event to process. Returns: An enum-style class type corresponding to a player action. Examples: ui_event_to_player_action(e) -> PlayerDig when e represents the player pressing the spacebar. ui_event_to_player_action(e) -> PlayerUp when e represents the player pressing the 'w' or UP arrow keys. """ if e.type == pygame.QUIT: return PlayerQuit elif e.type == pygame.KEYDOWN: if e.key == pygame.K_ESCAPE or e.key == pygame.K_q: return PlayerQuit elif e.key == pygame.K_UP or e.key == pygame.K_w: return PlayerUp elif e.key == pygame.K_DOWN or e.key == pygame.K_s: return PlayerDown #PROBLEM 2 #If the player presses LEFT or 'a', move the gopher left. #If the player presses RIGHT or 'd', move the gopher right. elif e.key == pygame.K_SPACE: return PlayerDig return PlayerNone ''' This is conditional tells the Python interpreter which file of source code to interpret first. ''' if __name__ == '__main__': print ("starting __main__") #This establishes the size of the game board and establishes the #window dimensions. window_size = determine_window_size_from_board_size() #starts pygame's subsystems. pygame.init() #creating an emtpy board of the correct size. board_config = [[[" ",None] for y in range(board_tile_dimensions[1])] for x in range(board_tile_dimensions[0])] #populates the empty board with default contents. default_board_configuration(board_config) #main_surface is a reference to your main display window. main_surface = initialize(window_size) print(board_config) ''' The main game loop. For every application with graphics, there is a loop like this one at its core. It keeps the application running and responsive to user input. Video games work on the listen-think-speak method. They listen for player input, think about how the word changes, and speaks that change to the player by game world (i.e. updating the graphics and sound experienced by the player). ''' while True: ''' Listen ''' #look through all player input for e in pygame.event.get(): #if you want to see all of the possible input channels, #uncomment the print statement below. #print(e) #determin a player action from the user interface event. current_player_action = ui_event_to_player_action(e) #print(current_player_action) if current_player_action is PlayerQuit: sys.exit() elif current_game_mode is GameModeStateUpdate: #selective hearing in StateUpdate mode current_player_action = PlayerNone ''' Think ''' #manage state transitions if current_game_mode == GameModeInput and current_player_action is not PlayerNone: #a player action was taken update_game_state(board_config, current_player_action) ''' If valid input was recieved in player_input mode, update the game state and switch modes to game_reaction. ''' current_game_mode = GameModeStateUpdate elif current_game_mode == GameModeStateUpdate: #reset the player's action current_player_action = PlayerNone current_game_mode = GameModeInput ''' Speak ''' #render the updated game state update_graphics_and_sound(main_surface,board_config, current_game_mode)
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question