def __init__(self, window): # initializes window to be used by controller self._window = window # initializes basic maze sprites from MazeBlock class and inserts into group self.maze_block = MazeBlock() self.blocks = pygame.sprite.Group() # initializes item sprites from Item class and inserts into group self.item = Item() self.items = pygame.sprite.Group() self.item_img = self.item.image # initializes player sprites from PlayerSprite class and inserts into group self.player = PlayerSprite() self.player_image = self.player.image self.img = self.maze_block.image # Gets maze and Player object from Maze model self.maze = Maze("models/grid_02.txt") self.model_player = self.maze._player # Creates a exit sprite group self.exits = pygame.sprite.Group() # Creates static images self._static = StaticImages() self._coins = self._static.coinshow() self._check = self._static.check() self._exit = self._static.exit() self._cross = self._static.cross()
def __init__(self, filename=None): """ Call the classmethod to load all students from the CSV """ self._maze = Maze() self._maze._load_all_from_file(filename) self._maze.generate_random_spots() self._window = pygame.display.set_mode( (self._maze.row * GridSize.SIZE, self._maze.col * GridSize.SIZE + GridSize.SIZE))
def test_maze_setter_changing_mazes(maze_object): """1002 - Tests constructor player if equal to 'P'""" maze_object = Maze("tests/test2.txt", "P") with open("tests/test2.txt", 'r') as f: contents = f.read().split("\n") maze = [[_ for _ in line] for line in contents] maze_object.maze = maze assert maze_object.maze == maze
def test_is_player(): maze1 = Maze("views/maze.txt") assert hasattr(maze1, "is_player") assert maze1.is_player(1,3) == True assert maze1.is_player(1,0) == False assert maze1.is_player(6,2) == False
def test_is_exit(): maze1 = Maze("views/maze.txt") assert hasattr(maze1, "is_exit") assert maze1.is_exit(1,2) == False assert maze1.is_exit(1,0) == False assert maze1.is_exit(6,3) == True
def test_can_move_to(): """ -> This test will check if Maze class had "can_move_to" attribute. -> maze1 is an object of Maze class and maps the game """ maze1 = Maze("views/maze.txt") assert hasattr(maze1, 'can_move_to') assert maze1.can_move_to(1,2) == True assert maze1.can_move_to(3,1) == True assert maze1.can_move_to(0,1) == False assert maze1.can_move_to(6,0) == False
def test_game_controller_check_user_input(): mazeObject = Maze("tests/test1.txt", 'P') game_controller = GameController(mazeObject) game_controller.check_user_input('d', 0, 0) game_controller.check_user_input('a', 0, 0) game_controller.check_user_input('w', 0, 0) game_controller.check_user_input('x', 0, 0)
def test_find_random_spot(): """ -> This function will make an object of Maze class by importing “maze.txt” from the views folder. -> Then, it will check if the maze class has an attribute “find_random_spot” """ maze1 = Maze("views/maze.txt") assert hasattr(maze1, "find_random_spot")
def test_display(): """ -> This function will make an object of Maze class by importing “maze.txt” from the views folder. -> Then, it will check if the maze class has an attribute “display” """ maze1 = Maze("views/maze.txt") assert hasattr(maze1, 'display')
def generate_maze(): # largura = int(request.args.get('largura', False)) # altura = int(request.args.get('altura', False)) quantidade = request.args.get('quantidade', False) id_partida = request.args.get('id_partida', False) if quantidade: quantidade = int(quantidade) else: quantidade = 10 start = x, y = 1, 1 zoom = 20 borders = 6 end_x = quantidade - 1 end_y = quantidade - 1 end = end_x, end_y maze = Maze(quantidade, quantidade) maze.create_maze(x, y) maze.cells[1][0] = False data = solution_maze(maze.cells, start, end, zoom, borders, id_partida) return jsonify(data)
def __init__(self, filename, player): """Using the filename and players as args, starts the game as filename is the maze and the player is the player. Args: filename(str): The text file of the maze player(str): the player """ self._contents = Maze(filename, player) self._welcome = WelcomeController(self._contents) self._endgame = EndGameController(self._contents.player.backpack, self._contents)
def game_view_instance(): maze = Maze() maze._load_all_from_file() maze.generate_random_spots() window = pygame.display.set_mode((1000, 1000)) view = GameView(maze, window) return view
def my_maze(): return Maze()
from models.maze import Maze from flask import Flask,request,render_template app = Flask(__name__) maze=Maze() """ homepage """ @app.route('/', methods=['GET']) def default(): return render_template('index.html',scores=sorted(maze.scores,key=lambda x: (x['score']),reverse=True)) """ Display the database storing the winners' scores """ @app.route('/api/list') def list_all_scores(): return {"scores": maze.scores} """ Add the winners' scores into database """ @app.route('/api/new', methods=["PUT"]) def add_new_score(): data = request.get_json() if data is None: return "Empty data.", 400 if len(data) != 2: return "Invalid keys.", 400 if type(data["name"]) != str or type(data["score"]) != float: return "Invalid data provided.", 400 score = [data["name"], data["score"]]
def test_find_player_runtime_error(): """60002- Tests to see if player index can be found, raises Runtime Error when cannot""" maze_object = Maze("tests/test3.txt", "P") with pytest.raises(RuntimeError): maze_object.find_player_idx()
def maze_object(): """ This is a sample Maze object that is valid""" return Maze("tests/test1.txt", "P")
def test_init_correct_backpack(): """1001- Test if the construct of the backpack is valid""" maze_object = Maze("tests/test1.txt", "P") view = EndGameView(maze_object.player.backpack, maze_object) assert view._backpack == []
def main(): """ Main function contains main UI text and fps, as well as the game loop """ """set the game display""" msg = "Null" width, height = 800, 800 window = pygame.display.set_mode((width, height)) window.fill((0, 0, 0)) clock = pygame.time.Clock() timer = 20 time_pass = 0 time_txt = font.render(f"Time: {str(round(timer))}", True, blue) window.blit(time_txt, (0, 0)) score = 0 pygame.display.set_caption("Maze Game") run = True """create the images of the maze, player, and items.""" maze = Maze("Views\maze.txt") maze.display() player = Player(maze.player[0], maze.player[1], [maze.player[2], maze.player[3]]) items = [] for i in maze._items: items.append(Items(i[0], i[1], [i[2], i[3]])) """Place the images on the game window""" window.blit(maze.surface, (100, 100)) pygame.display.update() """Running loop""" while run: dt = clock.tick(30) """ Stop the game if the game is quit """ for event in pygame.event.get(): if event.type == pygame.QUIT: run = False msg = "Quit" """movement functions for the player class""" keys = pygame.key.get_pressed() move = False if keys[pygame.locals.K_RIGHT]: if int(player.rect.x / maze._x_scale) < maze._width: if maze.can_move_to( int(player.rect.x / maze._x_scale) + 1, int(player.rect.y / maze._y_scale)): move = True #-- move the player right by x pixels player.rect.x = min(player.rect.x + maze._x_scale, 700) if keys[pygame.locals.K_LEFT]: if int(player.rect.x / maze._x_scale) > 0: if maze.can_move_to( int(player.rect.x / maze._x_scale) - 1, int(player.rect.y / maze._y_scale)): move = True #-- move the player left by x pixels player.rect.x = max(player.rect.x - maze._x_scale, 0) if keys[pygame.locals.K_UP]: if int(player.rect.y / maze._y_scale) - 1 >= 0: if maze.can_move_to(int(player.rect.x / maze._x_scale), int(player.rect.y / maze._y_scale) - 1): move = True #-- move the player up by x pixels player.rect.y = max(player.rect.y - maze._y_scale, 0) if keys[pygame.locals.K_DOWN]: if player.rect.y / maze._y_scale + 1 < maze._height: if maze.can_move_to(int(player.rect.x / maze._x_scale), int(player.rect.y / maze._y_scale) + 1): move = True #-- move the player down by x pixels player.rect.y = min(player.rect.y + maze._y_scale, 700) """ Delete items that are picked up by the player""" for i, item in enumerate(items): if item.rect == player.rect: player.pickup() items.pop(i) """If the player reaches the exit, they either win or lose depending on if they collected all the items""" if maze.is_exit(int(player.rect.x / maze._x_scale), int(player.rect.y / maze._y_scale)): run = False if player.backpack >= 4: msg = "You Win" else: msg = ("You Lost") """ Re-textures the maze first, then the player and remaining items.""" window.blit(maze.surface, (0, 100)) window.blit(player.image, player.rect) for i in items: window.blit(i.image, i.rect) pygame.display.update() """Detects if the player moved in this frame. Delays for a short time to slow the player.""" if move: pygame.time.delay(400) """Timer that adds to score and ends game if it reaches 0""" time_pass += dt if 1 <= time_pass / 1000: timer -= 1 time_pass = 0 """Covers the old timer and replaces it before updating.""" time_txt = font.render( "Timer: {} Backpack: {}".format(str(round(timer)), player.backpack), True, blue) window.blit(pygame.Surface((800, 100)), (0, 0)) window.blit(time_txt, (0, 0)) pygame.display.update() if timer <= 0: run = False msg = ("You ran out of time") """Detects how the game ended, and returns a message""" if msg != "Quit" and msg != "Null": score = 100 * player.backpack + timer end_bubble = font.render( "{} Please Check the Command line".format(msg), True, blue) window.fill((10, 10, 10)) window.blit(end_bubble, (10, 10)) pygame.display.update() """Tells the player what their score was""" print(f"Final score: {score}") name = input("Please tell me your name: ") scr_json = { "name": name, "score": score, "date": datetime.datetime.now().strftime("%c") } res = requests.post("http://127.0.0.1:5000/api/add", json=scr_json)
def render_maze(screen, maze: Maze): if not (maze.get_game_over() or maze.get_game_won()): for x in range(len(maze.board)): for y in range(len(maze.board[x])): screen.addstr(y, x, maze.board[y][x]) screen.addstr(maze.get_mg_xy_position()[1], maze.get_mg_xy_position()[0], '.') if not maze.get_a_collected(): screen.addstr(maze.get_a_xy_position()[1], maze.get_a_xy_position()[0], 'A') else: screen.addstr(20, 0, 'A item collected') if not maze.get_b_collected(): screen.addstr(maze.get_b_xy_position()[1], maze.get_b_xy_position()[0], 'B') else: screen.addstr(21, 0, 'B item collected') elif maze.get_game_over(): screen.clear() screen.addstr(1, 1, 'Game over') elif maze.get_game_won(): screen.clear() screen.addstr(1, 1, 'You win! Congrats!')
def main(screen): maze_obj = Maze(15, 15) maze_obj.generate_board() maze_obj.place_items() # Turn off cursor blinking curses.curs_set(0) render_maze(screen, maze_obj) while 1: key = screen.getch() if key == curses.KEY_UP: maze_obj.move_mg(maze_obj.DIRECTION_UP) render_maze(screen, maze_obj) elif key == curses.KEY_DOWN: maze_obj.move_mg(maze_obj.DIRECTION_DOWN) render_maze(screen, maze_obj) elif key == curses.KEY_LEFT: maze_obj.move_mg(maze_obj.DIRECTION_LEFT) render_maze(screen, maze_obj) elif key == curses.KEY_RIGHT: maze_obj.move_mg(maze_obj.DIRECTION_RIGHT) render_maze(screen, maze_obj) elif key == curses.KEY_ENTER or key in [10, 13]: # If user press enter, exit the program exit()
class GameController: """ Takes the app window as a parameter and manipulates it with a collection of sprites `GameView`. :param window: Application Window :type window: <pygame.Surface> """ def __init__(self, window): # initializes window to be used by controller self._window = window # initializes basic maze sprites from MazeBlock class and inserts into group self.maze_block = MazeBlock() self.blocks = pygame.sprite.Group() # initializes item sprites from Item class and inserts into group self.item = Item() self.items = pygame.sprite.Group() self.item_img = self.item.image # initializes player sprites from PlayerSprite class and inserts into group self.player = PlayerSprite() self.player_image = self.player.image self.img = self.maze_block.image # Gets maze and Player object from Maze model self.maze = Maze("models/grid_02.txt") self.model_player = self.maze._player # Creates a exit sprite group self.exits = pygame.sprite.Group() # Creates static images self._static = StaticImages() self._coins = self._static.coinshow() self._check = self._static.check() self._exit = self._static.exit() self._cross = self._static.cross() def display(self): """loop that is used to add to the sprite group for maze blocks """ maze = self.maze.grid for x in range(len(maze)): for y in range(len(maze[x])): if maze[x][y] == "X": self.createblocks(y, x) def displayPlayer(self): """[summary]loop to find the player location :return: [description]coorinates for player location :rtype: int """ maze = self.maze.grid for x in range(len(maze)): for y in range(len(maze[x])): if maze[x][y] == "P": return x, y # def additems(self): # """adds the tokens to the item sprite group # """ # self.maze.add_items() # maze = self.maze.grid # for x in range(len(maze)): # for y in range(len(maze[x])): # if maze[x][y] not in ["X", "P", "E", " "]: # self.createitem(y,x) def additems(self): """adds the tokens to the item sprite group """ itemlist = ['S', 'H', 'R', 'M', 'B', 'C'] self.maze.add_items() maze = self.maze.grid for x in range(len(maze)): for y in range(len(maze[x])): if maze[x][y] in itemlist: itemvalue = maze[x][y] itemlist.remove(itemvalue) self.createitem(y, x) def display_exit(self): """[summary]loop to find the exit location :return: [description]coordinates for exit location :rtype: int """ maze = self.maze.grid for x in range(len(maze)): for y in range(len(maze[x])): if maze[x][y] == "E": self.exit_item(y, x) def createblocks(self, y, x): """ adds items to the self.blocks sprite group :param x: y coordinate :type x: int :param y: x coordinate :type y: int """ block = MazeBlock() block.update(y, x) self.blocks.add(block) def createitem(self, y, x): """ adds items to the self.items sprite group :param x: y coordinate :type x: int :param y: x coordinate :type y: int """ item = Item() item.update(y, x) self.items.add(item) def exit_item(self, y, x): """ adds items to the self.exits sprite group :param x: y coordinate :type x: int :param y: x coordinate :type y: int """ exit = ExitSprite() exit.update(y, x) self.exits.add(exit) def loop(self): """ This is the game loop, runs until a win or lose condition is fulfilled """ # initiate pygame pygame.init() running = True # opens a display on top of window self.display() #black surface that covers player sprite's last location rectangle_surface = pygame.Surface((10, 10)) # calls method to display player co-ordinates x, y = self.displayPlayer() # method to display the items self.additems() # finds location of exist and add to its sprite group self.display_exit() # uses the sprite group blocks to draw the walls self.blocks.draw(self._window) # uses the sprite group to add the items self.items.draw(self._window) # uses sprite group for exit self.exits.draw(self._window) # ### Testing Background ####### background_img = pygame.image.load( "views/images/background.png").convert() background = pygame.transform.scale(background_img, (800, 600)) # updates the player position self.player.rect.x = x * 25 self.player.rect.y = y * 25 # initiates pygame display and clock pygame.display.update() clock = pygame.time.Clock() current_time = 4800 font = pygame.font.SysFont('arial', 48) # begins the loop until game ends while running: clock.tick(50) current_time -= 1 time_in_seconds = math.floor(current_time / 80) if current_time == 0: return False, 0 # if user clicks "X" on window, window closes for event in pygame.event.get(): if event.type == pygame.locals.QUIT: return "kill" # these are conditions if user uses the WASD controls. # If the player collides with a wall, the game will push him the other way # If the player collides with an item, it will be added to his backpack elif event.type == pygame.KEYDOWN: if event.key == pygame.K_a: self.player.changespeed(-4, 0) elif event.key == pygame.K_d: self.player.changespeed(4, 0) elif event.key == pygame.K_w: self.player.changespeed(0, -4) elif event.key == pygame.K_s: self.player.changespeed(0, 4) elif event.type == pygame.KEYUP: if event.key == pygame.K_a: self.player.changespeed(4, 0) elif event.key == pygame.K_d: self.player.changespeed(-4, 0) elif event.key == pygame.K_w: self.player.changespeed(0, 4) elif event.key == pygame.K_s: self.player.changespeed(0, -4) if pygame.sprite.spritecollide(self.player, self.exits, dokill=False): #deletes all sprites for sprite in self.blocks.sprites(): del sprite for sprite in self.items.sprites(): del sprite for sprite in self.exits.sprites(): del sprite # # delivers win condition, if users backpack contains the four items, they win! return True if len(self.items) == 2: return True, current_time elif len(self.items) == 1: return True, current_time + 500 elif len(self.items) == 0: return True, current_time + 1000 else: return False, 0 #covers the image blur of the player self.player.update(self.blocks, self.items) # updates the player position self._window.fill((0, 0, 0)) ### Background and coins won blit ### self._window.blit(background, [0, 0]) self._window.blit(self._cross, (700, 625)) if len(self.items) <= 5: self._window.blit(self._coins, (225, 625)) if len(self.items) <= 4: self._window.blit(self._coins, (300, 625)) if len(self.items) <= 3: self._window.blit(self._coins, (375, 625)) if len(self.items) <= 2: self._window.blit(self._coins, (450, 625)) self._window.blit(self._check, (700, 625)) if len(self.items) <= 1: self._window.blit(self._coins, (525, 625)) if len(self.items) <= 0: self._window.blit(self._coins, (600, 625)) self.blocks.draw(self._window) self.items.draw(self._window) self._window.blit(self.player_image, self.player.rect) # timer display if time_in_seconds >= 30: text = font.render(f"Timer: {str(time_in_seconds)}", True, (34, 139, 34)) elif time_in_seconds >= 10: text = font.render(f"Timer: {str(time_in_seconds)}", True, (255, 215, 0)) else: text = font.render(f"Timer: {str(time_in_seconds)}", True, (220, 20, 60)) self._window.blit(text, (25, 625)) # exit self._window.blit(self._exit, [775, 75]) # updates window pygame.display.flip() pygame.display.update() self._window.convert()
def test_welcome_display(): """"Tests if welcome display maze structure correctly""" maze_object = Maze("tests/test1.txt", "P") view = WelcomeView(maze_object) assert "xPx x" in view.display_maze()
def test_is_item(): maze1 = Maze("views/maze.txt") assert hasattr(maze1, "is_item")
class App: '''Main class for the application. It interacts with Maze model and three controllers: WelcomeController GameController GameOverController''' def __init__(self, filename=None): """ Call the classmethod to load all students from the CSV """ self._maze = Maze() self._maze._load_all_from_file(filename) self._maze.generate_random_spots() self._window = pygame.display.set_mode( (self._maze.row * GridSize.SIZE, self._maze.col * GridSize.SIZE + GridSize.SIZE)) @property def window(self): """Getter for the game window""" return self._window def run(self): """ This is the main method for our application. It runs an infinite loop, unless the user decides to quit. The `SystemExit` exception is raised by the child controllers. """ pygame.init() print(self._maze.locations) clock = pygame.time.Clock() welcome_controller = WelcomeController( self.window, self._maze.row * GridSize.SIZE, self._maze.col * GridSize.SIZE + GridSize.SIZE, GridSize.SIZE) running = False welcome_controller.run() pygame.display.update() welcome_controller.get_input() running = True # initialize pygame elements self._maze.create_player() self._maze.create_maze_exit() self._maze.create_wall() self._maze.create_items() while running: pygame.display.update() clock.tick(20) self.window.fill((0, 0, 0)) game_controller = GameController(self._maze, self._window) game_controller.run() # check if time runs out if self._maze._time_left <= 0: running = False # check if player reaches the exit if pygame.sprite.collide_rect(self._maze.player, self._maze.maze_exit): running = False game_over_controller = GameOverController(self.window, self._maze) game_over_controller.run() pygame.display.update() # ask for player name if game_over_controller._maze_result: self._maze.add_name_score() while True: key = game_over_controller.get_user_input() if key == "q": pygame.quit()
def maze(): """ create instance of class Maze to help with tests """ return Maze('models/grid_02.txt')
def test_endgame_display(): """2001 - Tests if the endgame display maze structure correctly""" maze_object = Maze("tests/test1.txt", "P") view = EndGameView(maze_object.player.backpack, maze_object) assert "xPx x" in view.display_maze()
def test_game_display(): """1001 - Tests if the game display maze structure correctly""" maze_object = Maze("tests/test1.txt", "P") view = GameView(maze_object) assert "xPx x" in view.display_maze()
def search_from(maze, start_row, start_column): maze.update_position(start_row, start_column) if maze[start_row][start_column] == OBSTACLE: return False if maze[start_row][start_column] == TRIED: return False if maze.is_exit(start_row, start_column): return True maze.update_position(start_row, start_column, TRIED) found = search_from(maze, start_row + 1, start_column) or \ search_from(maze, start_row, start_column + 1) or \ search_from(maze, start_row - 1, start_column) or \ search_from(maze, start_row, start_column - 1) if found: maze.update_position(start_row, start_column, PART_OF_PATH) else: maze.update_position(start_row, start_column, DEAD_END) return found my_maze = Maze('maze.txt') my_maze.draw_maze() my_maze.update_position(my_maze.start_row, my_maze.start_col) search_from(my_maze, my_maze.start_row, my_maze.start_col)