def main(): """ Main function """ pg.init() pg.display.set_caption("Projet 3 : Aidez Macgyver à s'échapper !") window = pg.display.set_mode((cst.WINDOW_HEIGHT, cst.WINDOW_WIDTH)) laby = Labyrinth("map.txt") while laby.mac_gyver.game: """I choose module pygame for the move I can to change my destination (Top, Left, Up or Right)""" laby.show_labyrinth(window) pg.display.flip() for event in pg.event.get(): if event.type == pg.QUIT: laby.mac_gyver.game = False pg.quit() elif event.type == pg.KEYDOWN: if event.key == pg.K_LEFT: laby.mac_gyver.move_to("L") elif event.key == pg.K_RIGHT: laby.mac_gyver.move_to("R") elif event.key == pg.K_UP: laby.mac_gyver.move_to("U") elif event.key == pg.K_DOWN: laby.mac_gyver.move_to("D")
def input(self): events = pygame.event.get() for event in events : if event.type == KEYDOWN : if event.key == K_RIGHT : if self.Astar() : self.winner = 2 else: self.winner = 3 if event.key == K_SPACE : if self.Astar() : self.winner = 1 else: self.winner = 3 if event.key == K_r : self.Lab = Labyrinth(self.size, self.style) self.winner = 0 if event.type == QUIT : sys.exit() if event.type == KEYUP: if event.key == K_RIGHT: self.Lab.stopDestroyWalls() if event.key == K_SPACE: self.Lab.stopDestroyWalls()
def empty_maze(w, h): lab = Labyrinth(w, h) lab[0, 0] = 1 lab.start = 0, 0 lab[w - 2, h - 2] = 1 lab.goal = w - 2, h - 2 return lab
def game(): level = Labyrinth() level.open_csv(constants.CSV_LEVEL, constants.NSPRITE) hero = Macgyver() hero.create(level.structure) guard = Guard() guard.create(level.structure) ether = Item() ether.create(level.ground_list, level.structure, 'E') thumb = Item() thumb.create(level.ground_list, level.structure, 'T') needle = Item() needle.create(level.ground_list, level.structure, 'N') screen = View() screen.load() screen.create(level.structure) return level, hero, guard, ether, thumb, needle, screen
def initialization(self, window): """ Initialise new objects when call """ self.labyrinth = Labyrinth() self.mac_gyver = Player( MAC_GYVER_IMAGE, FLOOR_IMAGE, self.labyrinth, self.window ) self.mac_gyver.position = [0, 0] self.objects = Objects( SYRINGE_IMAGE, ETHER_IMAGE, NEEDLE_IMAGE, self.labyrinth, self.window ) # Labyrinth self.labyrinth.labyrinth_construction() self.labyrinth.display_level(window) # Player self.mac_gyver.blit(self.mac_gyver.position) # Objects self.objects.generate_random_position() self.objects.display_objects() self.objects.objects_collected = 0 self.run = True self.response = None
def test_in_range(self): map_ = ["...", "###"] location = Location(1, 2) out_of_range_location = Location(0, 3) labyrinth = Labyrinth(map_) self.assertTrue(labyrinth.in_range(location)) self.assertFalse(labyrinth.in_range(out_of_range_location))
def __init__(self, json_file="labyrinth.json"): """ GameText constructor. Instantiates objects from Labyrinth, MacGyver and Syringe classes. """ self.labyrinth = Labyrinth(json_file) self.macgyver = MacGyver(self.labyrinth) self.syringe = Syringe(self.labyrinth)
def BFS(lab: Labyrinth): """ Fa una busqueda per nivells de forma iterativa Precondicions: Necessita un laberynth d'entrada vàlid (amb posició d'entrada, sortida i almenys un camí vàlid) Postcondicions: Un trail amb un camí dels més curts possibles (pot trobar 2 camins amb la mateixa longitud que siguin vàlids, en aquest cas retornarà el primer que trobi a la hora de processar-los) """ print('Starting BFS') #Posteriorment afegirem a trails la posició d'inici, per aixó l'afegim aquí ja_buscats = [lab.getStartCell()] # Donat que en el BFS busquem tots els camins possibles fins que trobem el més curt, # necessitem varis trails. La iniciem amb la posició de sortida per a no fer saltar la verificacio de # camins possibles trails = [[lab.getStartCell()]] while True: #Comencem la iteració # En el cas que la longitud de trails sigui 0, implicaria que no hi hauria cap camí possible. # també detectaria un error a la hora de llegir el laberint si no conté una start cell if trails.__len__() == 0: print("Error al buscar un camí, es possible que no hi hagi solució?") break else: #comprova cada trail for j in trails: pos_val = j[j.__len__() - 1] #agafem la ultima posició de cada taril per a obtenir els seus children children = pos_val.getChildren() #d'aquesta manera independentment de la llargada sempre tenim els #children de la ultima posició if children.__len__() == 0: #si detectem que aquell camí no te cap children, implica que s'ha acabat #per tant eliminem el camí de trails trails.remove(j) else: #per cada children que tingui el camí actual volem crear un camí nou (afegint k al final) # Per tant primer filtem per veure si aquest children ja ha estat buscat, sino el conté, copiem el # el trail i li afegim el children k al final i l'afegim a trails. Llavors mirem si aquest children # es la posició final, si ho és retornem el trail (que ja te la posició k inclosa). De no ser aixi # afegim la posició com a ja buscada for k in children: if not ja_buscats.__contains__(k): prov = j.copy() prov.append(k) trails.append(prov) #'aqui' if k == lab.getEndCell(): prov_f =trails[trails.__len__()-1] #hem afegit abans 'aqui' a trails al final de tot return prov_f ja_buscats.append(k) #borrem el trail j degut a que no te cap dels childrens i es inutil guardar-lo ja que els camins # derivats d'aquest trail j ja han estat afegits ('aqui'). trails.remove(j) # para la salida obtenemos getchildren() donde obtenemos los hijos del nodo return trails
def main(): """This function is the main function to be executed to play the game.""" pygame.init() # we build the labyrinth, with the player and the tools to be found csv_path = os.path.join("data", "grid.csv") game_laby = Labyrinth(LabyViewer.LABY_WIDTH, LabyViewer.LABY_HEIGHT, csv_path) game_laby.initialize_player_location() game_player = game_laby.player game_tools = game_laby.tools # we initialize the main window with our game interface window = pygame.display.set_mode( (Interface.SCREEN_WIDTH, Interface.SCREEN_HEIGHT)) game_back = pygame.image.load("sprites\\backs\\blue_sky.png").convert() game_labyviewer = LabyViewer(game_laby) game_dashboard = Dashboard("game") game_interface = Interface(game_back, game_labyviewer, game_dashboard) window.blit(game_back, Interface.SCREEN_ORIGIN) # we load our sprites m_gyver = pygame.image.load("sprites\\laby\\m_gyver.png").convert() m_gyver.set_colorkey((255, 255, 255)) # set white as transparent sand_path = pygame.image.load("sprites\\laby\\path.png").convert() wall = pygame.image.load("sprites\\laby\\wall.png").convert() guard = pygame.image.load("sprites\\laby\\guard.png").convert() guard.set_colorkey((255, 255, 255)) # set white as transparent # we improve our window mac_g_a = pygame.image.load("sprites\\laby\\m_gyver.png").convert_alpha() mac_g_a.set_colorkey((255, 255, 255)) # set white as transparent pygame.display.set_icon(mac_g_a) pygame.display.set_caption("Mac Gyverinth - game mode - by etienne86") pygame.display.flip() # we display our labyrinth with walls, paths, guard and player sprites_dict = { "wall": wall, "sand_path": sand_path, "guard": guard, "m_gyver": m_gyver } game_labyviewer.display_labyrinth(window, sprites_dict) # we display our tools in the labyrinth game_labyviewer.display_tools_in_labyrinth(window) # we display our dashboard game_interface.display_dashboard(window, game_tools) # we execute our game loop game_loop(window, game_interface, game_laby, game_player, sprites_dict) pygame.quit()
def __init__(self): pygame.init() # The labyrinth self.lab = Labyrinth() # Map construction self.lab.build_map("maze.txt") # Random positions for the accessories self.lab.random_position() # Replace the start en finish position in the path self.lab.start_finish_to_path() # Creating the Hero self.hero = MacGyver(self.lab) # Creating the information title self.title_score = TitleScore() # Creating the score countdown self.score = Score() # The windows of the game self.window = pygame.display.set_mode((BOARD_SIZE_X, BOARD_SIZE_Y)) self.window.fill(BLACK) self.background = pygame.Surface((750, 750)) self.background.fill(BLACK) # Walls positioning self.wall = pygame.image.load("pics/wall50.png").convert() for walls in self.lab.walls: self.background.blit( self.wall, (walls.posx * SPRITE_SIZE_X, walls.posy * SPRITE_SIZE_Y)) # Paths positioning self.path = pygame.image.load("pics/path50.png").convert() for paths in self.lab.paths: self.background.blit( self.path, (paths.posx * SPRITE_SIZE_X, paths.posy * SPRITE_SIZE_Y)) # Starting point positioning self.start_point = pygame.image.load("pics/start50.png").convert() self.background.blit(self.start_point, (self.lab.start_pos.posx * SPRITE_SIZE_X, self.lab.start_pos.posy * SPRITE_SIZE_Y)) # Finish point positioning self.finish_point = pygame.image.load("pics/finish50.png").convert() self.background.blit(self.finish_point, (self.lab.finish_pos.posx * SPRITE_SIZE_X, self.lab.finish_pos.posy * SPRITE_SIZE_Y)) # Coordinate assignment to the accessories. gel_position, ether_position, syringe_position = self.lab.rand_pos # Creation of the sprites group self.sprites = pygame.sprite.Group( AccessorySprite(self.lab, gel_position, "tub"), AccessorySprite(self.lab, ether_position, "ether"), AccessorySprite(self.lab, syringe_position, "syringe"), HeroSprite(self.hero), ScoreSprite(self.hero, self.score), TitleScoreSprite(self.hero, self.title_score))
def main(): labyrinth = Labyrinth() labyrinth.load_labyrinth_from_file("labyrinth.txt") macgyver = MacGyver(labyrinth) running = True while running: print(labyrinth.display()) response = input("Where do you want to go ? ( Q to quit the game)") if response == "q" or response == "Q": running = False elif response in ("h", "b", "d", "g"): macgyver.move(directions[response])
def __init__(self, size, disp_size, style): self.disp_size = disp_size self.style = style self.BLOCK_SIZE = self.disp_size // size self.size = size self.screen = pygame.display.set_mode((self.disp_size, self.disp_size)) pygame.display.set_caption('Splash Labyrinth') pygame.time.Clock().tick(30) self.Lab = Labyrinth(size, style) # this var keeps track of winners situation # 0 means the game is still running # 1 means p1 wins, 2 means p2 wins # 3 means the player who pushed the button lost self.winner = 0
def test_str(self): map_ = ["...", "#.#", "###"] layer = Labyrinth(map_) labyrinth = Labyrinth3d([map_, map_]) self.assertEqual(str(labyrinth), str(layer) + "\n" + str(layer))
def play_game(self, gui = False): while(True): self.gui = gui if (gui == False): self.gui = GUI(self) menu_sel = self.gui.print_menu() if(menu_sel == 1): #start new game #set labyrinth size: width = self.gui.ask_width() height = self.gui.ask_height() #create labyrinth self.labyrinth = Labyrinth(width, height) self.labyrinth.generateMaze() #createa player self.player = Player(self.labyrinth.getStartNode()) #the game itself self.gui.game_loop() if(menu_sel == 2): #Load game from a file self.load_game() self.gui.game_loop() if(menu_sel == 3): #Exit game return self.end_game()
def check_map_choice(map_files, map_directory, map_extension): file_map_length = len(map_files) user_input_s = input( "Entrez un numéro de labyrinthe pour commencer à jouer : ") try: user_input_i = int(user_input_s) except ValueError: print("Merci de choisir un chiffre entre 1 et {0}".format( file_map_length)) return check_map_choice(map_files, map_directory, map_extension) if user_input_i < 1 or (user_input_i - 1) >= file_map_length: print("Merci de choisir un chiffre entre 1 et {0}".format( file_map_length)) return check_map_choice(map_files, map_directory, map_extension) print("Vous avez choisi la carte", user_input_i) with open(map_directory + map_files[user_input_i - 1] + map_extension, 'r') as f: labyrinth = Labyrinth(f.read()) if len(labyrinth.exits) < 1: print( "!!!!!!!!! carte invalide, il n'y a pas de sortie !!!!!!!!!!!!!!!") return check_map_choice(map_files, map_directory, map_extension) if not labyrinth.robot: print( "!!!!!!!!! carte invalide, il n'y a pas de robot !!!!!!!!!!!!!!!") return check_map_choice(map_files, map_directory, map_extension) return labyrinth
def main(): labyrinth = Labyrinth("labyrinth_test.json") macgyver = MacGyver(labyrinth) print("Collected_syringe_elements : {}". format(macgyver.collected_syringe_elements)) # returns [] print("Starting position : {}". format((macgyver.position.x, macgyver.position.y))) # returns (0, 1) macgyver.move("r") print("New position : {}". format((macgyver.position.x, macgyver.position.y))) # returns (1, 1) macgyver.move("r") print("New position : {}". format((macgyver.position.x, macgyver.position.y))) # returns (2, 1) macgyver.move("r") print("New position : {}". format((macgyver.position.x, macgyver.position.y))) # returns "Can't # move ..." then (2, 1) macgyver.move("d") print("New position : {}". format((macgyver.position.x, macgyver.position.y))) # returns (2, 2) macgyver.move("d") print("New position : {}". format((macgyver.position.x, macgyver.position.y))) # returns (2, 3) for i in range(11): macgyver.move("r") # returns "MacGyver failed ..." print("New position : {}". format((macgyver.position.x, macgyver.position.y))) # returns (13, 3)
class GameText: """ Sets GameText class. The GameText class consists of 2 methods : - __init__() - run() """ def __init__(self, json_file="labyrinth.json"): """ GameText constructor. Instantiates objects from Labyrinth, MacGyver and Syringe classes. """ self.labyrinth = Labyrinth(json_file) self.macgyver = MacGyver(self.labyrinth) self.syringe = Syringe(self.labyrinth) def run(self): """ Manages the game progress. Sets : "carry_on" boolean variable user interaction labyrinth display """ carry_on = True print("\nHelp MacGyver to escape from the labyrinth : he needs to pick\ up a needle, a tube and ether before fighting the guard !") while carry_on: self.labyrinth.display() user_answer = input("In which direction do you want MacGyver to \ move ? Please enter 'u' for up, 'd' for down, 'l' for left and 'r' for \ right, or 'q' to quit : ") success = None if user_answer not in ["q", "u", "d", "l", "r"]: print("\nInvalid choice !") continue elif user_answer == "q": carry_on = False else: success = self.macgyver.move(user_answer) # 'success' becomes True or False after fighting the guard if success is not None: carry_on = False self.labyrinth.display()
def test_init(self): map_ = ["#..", "..."] labyrinth = Labyrinth(map_) expected_map = [[LabyrinthObject(True), LabyrinthObject(False), LabyrinthObject(False)], [LabyrinthObject(False), LabyrinthObject(False), LabyrinthObject(False)]] self.assertEqual(labyrinth.width, 2) self.assertEqual(labyrinth.height, 3) self.assertEqual(labyrinth.map, expected_map)
def load_game(self): #file handle f = open(os.path.realpath(__file__).replace('game.py','')+'saved_game.dat', 'r'); fileContent = f.read() f.close() w = 0 #create labyrinth and nodes for line in fileContent.split('\n'): lineAr = line.split(':') if (len(lineAr) == 2): key = lineAr[0].strip() value = lineAr[1].strip() if (key == 'W'): w = int(value) if (key == 'H'): #create labyrinth self.labyrinth = Labyrinth(w, int(value)) if (key == 'Id'): self.labyrinth.addNode(Node(Pos())) self.labyrinth.getLastNode().setId(int(value)) if (key == 'X'): self.labyrinth.getLastNode().setX(int(value)) if (key == 'Y'): self.labyrinth.getLastNode().setY(int(value)) if (key == 'Z'): self.labyrinth.getLastNode().setZ(int(value)) #set connections id = 0 for line in fileContent.split('\n'): lineAr = line.split(':') if (len(lineAr) == 2): key = lineAr[0].strip() value = lineAr[1].strip() if (key == 'Id'): id = int(value) if (key == 'ConnectionRIGHT'): self.labyrinth.findNodeById(int(value)).setConnection(self.RIGHT, self.labyrinth.findNodeById(id)) if (key == 'ConnectionLEFT'): self.labyrinth.findNodeById(int(value)).setConnection(self.LEFT, self.labyrinth.findNodeById(id)) if (key == 'ConnectionUP'): self.labyrinth.findNodeById(int(value)).setConnection(self.UP, self.labyrinth.findNodeById(id)) if (key == 'ConnectionDOWN'): self.labyrinth.findNodeById(int(value)).setConnection(self.DOWN, self.labyrinth.findNodeById(id)) if (key == 'Player position'): playerNode = self.labyrinth.findNodeById(int(value)) playerNode.setPlayer(True) self.player = Player(playerNode) if (key == 'End node'): self.labyrinth.endNode = self.labyrinth.findNodeById(int(value))
def test_init(self): map_ = ["...", "#.#", "###"] layer = Labyrinth(map_) labyrinth = Labyrinth3d([map_, map_]) self.assertEqual(labyrinth.depth, 2) self.assertEqual(labyrinth.width, 3) self.assertEqual(labyrinth.height, 3) self.assertEqual(labyrinth.map, [layer, layer])
def main(): internal_labyrinth_dict = { (0, 0): Cell(True, True, True, True), (1, 0): Cell(True, True, False, True), (0, 1): Cell(True, True, True, True), (1, 1): Cell(True, True, True, False) } # labyrinth in labyrinth labyrinth_dict = { (0, 0): Cell(True, True, True, True), (1, 0): Cell(True, True, True, True), (0, 1): Cell(True, True, True, True), (1, 1): Labyrinth(internal_labyrinth_dict) } multi_labyrinth = Labyrinth(labyrinth_dict) print("labyrinth ", multi_labyrinth.get_labyrinth_dict()) print_labyrinth(multi_labyrinth) # 1. Count closed cells closed_number = get_number_of_closed_cells(multi_labyrinth) print("Initial number of closed cells in the labyrinth: ", closed_number) # 2. Close all cells wall_visitor = CloseCellsVisitor() wall_visitor.visit(False, multi_labyrinth) print("Closing all cells...") print_labyrinth(multi_labyrinth) # 3. Count closed in the updated labyrinth closed_number = get_number_of_closed_cells(multi_labyrinth) print("Updated number of closed cells in the labyrinth: ", closed_number) # 4. Open all cells wall_visitor.visit(True, multi_labyrinth) print("Open all cells...") print_labyrinth(multi_labyrinth) # 5. Count closed in the updated labyrinth closed_number = get_number_of_closed_cells(multi_labyrinth) print("Updated number of closed cells in the labyrinth: ", closed_number)
def test_explore_multiple_unreachable(self): # Same as the previous test, except filter type 2 is unreachable. rooms = ['S', 'L', 'R', 'D', 'G'] corridors = [('S', 'L', 0), ('S', 'R', 1), ('S', 'D', 2), ('D', 'G', 3)] filters = [('S', 0), ('S', 1), ('D', 2), ('L', 3)] start = 'S' goal = 'G' labyrinth = Labyrinth(rooms, corridors, filters, start, goal) self.assertEqual(explore_multiple(labyrinth, 18), None)
def test_explore_single_basic_1(self): rooms = ['A', 'B', 'C', 'D', 'E', 'F'] corridors = [('A', 'B', 0), ('B', 'D', 2), ('B', 'C', 0), ('C', 'D', 3), ('C', 'E', 1), ('C', 'E', 3), ('C', 'F', 1)] filters = [('A', 0), ('C', 2), ('D', 3), ('E', 1)] start = 'A' goal = 'F' labyrinth = Labyrinth(rooms, corridors, filters, start, goal) self.assertEqual(explore_single(labyrinth), 8)
def test_explore_single_unreachable(self): # Same as the previous test, except we require filter type 3 to go from B to D. rooms = ['A', 'B', 'C', 'D'] corridors = [('A', 'B', 0), ('B', 'D', 3), ('B', 'C', 0), ('C', 'D', 3)] filters = [('A', 0), ('C', 2), ('D', 3), ('D', 1)] start = 'A' goal = 'D' labyrinth = Labyrinth(rooms, corridors, filters, start, goal) self.assertEqual(explore_single(labyrinth), None)
def __init__(self): """Class constructor""" self.lab = Labyrinth('map.txt') # -tc- Même classe pour MacGyver et Murdoc? MacGyver peut se déplacer, pas Murdoc macgyver = Character('M', 1, 3) # -tc- Attention, il me semble plus logique que la position de départ de MacGyver soit définie dans map.txt guardian = Character('G', 13, 13) # -tc- il me semble plus logique que la position finale soit définie dans map.txt self.lab.set_character_position(macgyver) self.lab.set_character_position(guardian) self.lab.set_tool_positions(constants.TOOLS) view = pygame_.Pygame(*self.lab.get_size()) # view = CLI() # -tc- jeu en CLI pas possible. Votre classe Labyrinthe dépend de pygame view.display_lab(self.lab.lablist) game_loop = True while game_loop: # -tc- attention à cadencer votre boucle 30-40 tours par second à l'aide de pygame.time.Clock direction = view.get_direction() if direction is None: # exit key pressed exit() for d in direction: move = self.lab.move_macgyver(macgyver, guardian, d) if move['event'] in ['CONTINUE', 'ADD_TOOL']: view.display_lab(self.lab.lablist) elif move['event'] == 'NO_MOVE': continue elif move['event'] == 'WIN': view.win() game_loop = False break # -tc- si game_loop = False, éviter le break elif move['event'] == 'LOSE': view.lose() game_loop = False # -tc- si game_loop = False, éviter le break break
def test_explore_single_basic(self): rooms = ['A', 'B', 'C', 'D'] corridors = [('A', 'B', 0), ('B', 'D', 2), ('B', 'C', 0), ('C', 'D', 3)] filters = [('A', 0), ('C', 2), ('D', 3), ('D', 1)] start = 'A' goal = 'D' labyrinth = Labyrinth(rooms, corridors, filters, start, goal) # There are two edges leading to the goal room, D. However the filter of type 3 cannot be obtained # without reaching the goal room itself. So the explorer must first go to C to pick up the filter # of type 2. Thus the fastest sequence of actions is: # pick up filter 0, go from A to B, go from B to C, pick up filter 2, go from C to B, go from B to D. self.assertEqual(explore_single(labyrinth), 4)
def main(): """This function is the main function to be executed to edit the map.""" pygame.init() # we build the labyrinth csv_path = os.path.join("data", "grid.csv") edit_laby = Labyrinth(LabyViewer.LABY_WIDTH, LabyViewer.LABY_HEIGHT, csv_path) # we initialize the main window with our game interface window = pygame.display.set_mode( (Interface.SCREEN_WIDTH, Interface.SCREEN_HEIGHT)) edit_back = pygame.image.load("sprites\\backs\\sea.png").convert() edit_labyviewer = LabyViewer(edit_laby) edit_dashboard = Dashboard("edit") edit_interface = Interface(edit_back, edit_labyviewer, edit_dashboard) window.blit(edit_back, Interface.SCREEN_ORIGIN) # we load our sprites m_gyver = pygame.image.load("sprites\\laby\\m_gyver.png").convert() m_gyver.set_colorkey((255, 255, 255)) # set white as transparent sand_path = pygame.image.load("sprites\\laby\\path.png").convert() wall = pygame.image.load("sprites\\laby\\wall.png").convert() guard = pygame.image.load("sprites\\laby\\guard.png").convert() guard.set_colorkey((255, 255, 255)) # set white as transparent # we improve our window mac_g_a = pygame.image.load("sprites\\laby\\m_gyver.png").convert_alpha() mac_g_a.set_colorkey((255, 255, 255)) # set white as transparent pygame.display.set_icon(mac_g_a) pygame.display.set_caption("Mac Gyverinth - edit mode - by etienne86") pygame.display.flip() # we display our labyrinth with walls, paths, guard and player sprites_dict = { "wall": wall, "sand_path": sand_path, "guard": guard, "m_gyver": m_gyver } edit_labyviewer.display_labyrinth(window, sprites_dict) # we display our dashboard edit_interface.display_dashboard(window) # we execute our edit loop edit_loop(window, edit_interface, edit_laby, sprites_dict, csv_path) pygame.quit()
def test_getitem(self): map_ = [".#.", "##.", ".#."] labyrinth = Labyrinth(map_) wall = LabyrinthObject(True) empty = LabyrinthObject(False) for x in range(3): for y in range(3): current = labyrinth[Location(x, y)] if y == 1 or x == 1 and y == 0: self.assertEqual(current, wall) else: self.assertEqual(current, empty) self.assertRaises(TypeError, labyrinth.__getitem__, 1) self.assertRaises(IndexError, labyrinth.__getitem__, Location(-1, 1))
def test_next_state(self): map_ = ["...", "#.#", "###"] labyrinth = Labyrinth(map_) location = Location(1, 1) out_of_range_location = Location(0, 4) state = State(out_of_range_location, 1) self.check_next_state(labyrinth, state, []) expected_next_states = [State(Location(0, 1), 1), State(Location(1, 0), 0), State(Location(1, 2), 0), State(Location(2, 1), 0)] state = State(location, 1) self.check_next_state(labyrinth, state, expected_next_states) state = State(Location(0, 0), 1) self.check_next_state(labyrinth, state, expected_next_states[0:2])
def main(): """ Main function """ pygame.init() # Initialize pygame window = pygame.display.set_mode( DISPLAY_MODE) # Set the window size of the screen pygame.display.set_caption(DISPLAY_GAME_TITLE) # Set title of screen labyrinth = Labyrinth(window) labyrinth.load_level_from_file("level/level1.map") # Load level one Item(labyrinth.grid, ITEM_TOTAL) labyrinth.draw() score = Score(window, ITEM_TOTAL) score.draw() player = Player(window, labyrinth.grid, labyrinth.player_position, ITEM_TOTAL) # Loop until the user clicks the close button. done = False while not done: pygame.time.Clock().tick(1000) # Update the clock for event in pygame.event.get(): # User did something if event.type == pygame.QUIT: # If user clicked close done = True # Flag that we are done so we exit this loop elif event.type == pygame.KEYDOWN and player.is_finish is None: player.move(event.key) # Move player labyrinth.draw() # Update labyrinth score.draw(player.score) # Update score player.game_over() # Show Game Over pygame.display.update()
def test_explore_multiple_basic(self): # L -- S -- R # | # D # | # G rooms = ['S', 'L', 'R', 'D', 'G'] corridors = [('S', 'L', 0), ('S', 'R', 1), ('S', 'D', 2), ('D', 'G', 3)] filters = [('S', 0), ('S', 1), ('R', 2), ('L', 3)] start = 'S' goal = 'G' labyrinth = Labyrinth(rooms, corridors, filters, start, goal) # A single explorer needs 6 timesteps to get to the goal. self.assertEqual(explore_multiple(labyrinth, 20), 1) self.assertEqual(explore_multiple(labyrinth, 6), 1) # Two explorers can make it in 5 timesteps. One explorer goes right, picks up filter 2, goes back and drops it at S. # Meanwhile, the other explorer goes left, picks up filter 3, goes back to S, picks up filter 2, # and finally proceeds to D and G. self.assertEqual(explore_multiple(labyrinth, 5), 2) # No matter how many explorers you have, it's not possible to reach the goal in 4 or fewer timesteps. self.assertEqual(explore_multiple(labyrinth, 4), None)
def main(): screen = pygame.display.set_mode((15 * sp_size, 15 * sp_size)) Lab = Labyrinth("mappy.txt", sp_size) Lab.convert_file_txt() Lab.get_pos() objects = Objects(Lab) objects.random() macgyver = MacGyver("mappy.txt", sp_size, objects, Lab) guardian = Guardian(sp_size) pygame.display.flip() current_game = True while current_game: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_RIGHT: macgyver.move_right() elif event.key == pygame.K_LEFT: macgyver.move_left() elif event.key == pygame.K_UP: macgyver.move_up() elif event.key == pygame.K_DOWN: macgyver.move_down() macgyver.get_objects() Lab.get_pos() arbitror(macgyver, guardian) objects.display_objects() screen.blit(guardian.image, (guardian.rect.x, guardian.rect.y)) screen.blit(macgyver.image, (macgyver.rect.x, macgyver.rect.y)) macgyver.score_count() pygame.display.flip()
def maze(w, h, size=2): def conv_size(n): return (n - 1) // size + 1 nw, nh = conv_size(w), conv_size(h) ns = size // 2 - 1 uf = UnionFind(nw * nh) lab = Labyrinth(w, h) for x in range(w): for y in range(h): lab[x, y] = 0 edges = [] for i in range(nh - 1): for j in range(nw - 1): f = flatten(i, j, nw, nh) edges.append((f, f + 1)) # right edges.append((f, f + nw)) # down for i in range(nh - 1): f = flatten(i, nw - 1, nw, nh) edges.append((f, f + nw)) # down for j in range(nw - 1): f = flatten(nh - 1, j, nw, nh) edges.append((f, f + 1)) # right shuffle(edges) while len(uf) > 1: u, v = edges.pop() y1, x1 = unflatten(u, nw, nh) y2, x2 = unflatten(v, nw, nh) if uf.find(u) != uf.find(v): uf.union(u, v) if x2 - x1 == 1: for i in range(size + 1): for j in range(1, ns + 1): ny = size * y1 - j if ny >= 0: lab[size * x1 + i, ny] = True else: break lab[size * x1 + i, size * y1] = True for j in range(1, ns + 1): ny = size * y1 + j if ny < h: lab[size * x1 + i, ny] = True else: break else: for i in range(size + 1): for j in range(1, ns + 1): nx = size * x1 - j if nx >= 0: lab[nx, size * y1 + i] = True else: break lab[size * x1, size * y1 + i] = True for j in range(1, ns + 1): nx = size * x1 + j if nx < w: lab[nx, size * y1 + i] = True else: break lab[0, 0] = 1 lab.start = 0, 0 lab[lab.w - 2, lab.h - 2] = 1 lab.goal = lab.w - 2, lab.h - 2 return lab
__author__ = 'davide' from labyrinth import Labyrinth, NeighborsGenerator import numpy as np if __name__ == "__main__": lab = Labyrinth(6, 5) lab.start = 0, 0 lab.goal = 5, 4 lab.walls = {(2, 2), (3, 2), (4, 2), (5, 2)} n = NeighborsGenerator(lab) current = np.array([1, 2]) direction = np.array([1, 1]) # the correct result is [3,4], but the third call # returns None print(n.jump_rec(current, direction, lab.goal)) print(n.jump_it_1(current, direction, lab.goal)) print(n.jump_it_2(current, direction, lab.goal)) for i in range(lab.w): print("|", end="") for j in range(lab.h): if (i, j) == lab.start: print("S|", end="") elif (i, j) == lab.goal: print("G|", end="") else: print(" " if lab[i, j] else "X", end="|") print()
#!/usr/bin/python from pool import Pool from input_output import IO from labyrinth import Labyrinth from access import Access pool = Pool() pool.fill() io = IO() labyrinth = Labyrinth() access = Access() io.fill() labyrinth.fill() access.fill() while True: labyrinth.process(pool) access.process(pool) io.process(pool)
class Game(object): UP = 0 DOWN = 1 RIGHT = 2 LEFT = 3 gui = False def move(self, direction): self.player.move(direction) def save_game(self): #create file f = open(os.path.realpath(__file__).replace('game.py','')+'saved_game.dat', 'w+') f.write("W:"+str(self.labyrinth.width)+'\n') f.write("H:"+str(self.labyrinth.height)+'\n') for node in self.labyrinth.nodes: f.write(node.info()) # print(node.info(), file=f) f.write("Player position:"+str(self.player.getCurrentNode().getId())+'\n') # print("player position:"+str(self.player.getCurrentNode().getId()), file=f) f.write("End node:"+str(self.labyrinth.getEndNode().getId())+'\n') f.close() print("Saved!") def load_game(self): #file handle f = open(os.path.realpath(__file__).replace('game.py','')+'saved_game.dat', 'r'); fileContent = f.read() f.close() w = 0 #create labyrinth and nodes for line in fileContent.split('\n'): lineAr = line.split(':') if (len(lineAr) == 2): key = lineAr[0].strip() value = lineAr[1].strip() if (key == 'W'): w = int(value) if (key == 'H'): #create labyrinth self.labyrinth = Labyrinth(w, int(value)) if (key == 'Id'): self.labyrinth.addNode(Node(Pos())) self.labyrinth.getLastNode().setId(int(value)) if (key == 'X'): self.labyrinth.getLastNode().setX(int(value)) if (key == 'Y'): self.labyrinth.getLastNode().setY(int(value)) if (key == 'Z'): self.labyrinth.getLastNode().setZ(int(value)) #set connections id = 0 for line in fileContent.split('\n'): lineAr = line.split(':') if (len(lineAr) == 2): key = lineAr[0].strip() value = lineAr[1].strip() if (key == 'Id'): id = int(value) if (key == 'ConnectionRIGHT'): self.labyrinth.findNodeById(int(value)).setConnection(self.RIGHT, self.labyrinth.findNodeById(id)) if (key == 'ConnectionLEFT'): self.labyrinth.findNodeById(int(value)).setConnection(self.LEFT, self.labyrinth.findNodeById(id)) if (key == 'ConnectionUP'): self.labyrinth.findNodeById(int(value)).setConnection(self.UP, self.labyrinth.findNodeById(id)) if (key == 'ConnectionDOWN'): self.labyrinth.findNodeById(int(value)).setConnection(self.DOWN, self.labyrinth.findNodeById(id)) if (key == 'Player position'): playerNode = self.labyrinth.findNodeById(int(value)) playerNode.setPlayer(True) self.player = Player(playerNode) if (key == 'End node'): self.labyrinth.endNode = self.labyrinth.findNodeById(int(value)) def play_game(self, gui = False): while(True): self.gui = gui if (gui == False): self.gui = GUI(self) menu_sel = self.gui.print_menu() if(menu_sel == 1): #start new game #set labyrinth size: width = self.gui.ask_width() height = self.gui.ask_height() #create labyrinth self.labyrinth = Labyrinth(width, height) self.labyrinth.generateMaze() #createa player self.player = Player(self.labyrinth.getStartNode()) #the game itself self.gui.game_loop() if(menu_sel == 2): #Load game from a file self.load_game() self.gui.game_loop() if(menu_sel == 3): #Exit game return self.end_game() def hasWon(self): return self.player.getCurrentNode() == self.labyrinth.getEndNode() def end_game(self): print("Ending game.") return 0