def generate_adventurer(self): #placeholder adventurer_class = self._random_class() adventurer = Adventurer(self.starting_adven_level(adventurer_class), adventurer_class, self._random_heroic()) adventurer.equip_items(self.equipment) return [adventurer]
def __init__(self): self.dungeon = Dungeon(4, 4) self.dungeon.generate() self.adventurer = Adventurer("") self.root = Tk() self.root.resizable(False, False) self.root.title("Dungeon Adventure") self.start_menu_init()
def __init__(self, map_file_name, class_name): self.player = Adventurer('Tango', class_name) # default character self.player_x = 0 # player's current x-coord self.player_y = 0 # player's current y-coord self.world = Map( map_file_name) # load the given map as the world for the adventure self.won = False # has the player beaten the adventure? self.determine_start()
def __init__(self): pygame.init() #Obsługa głównej petli self.run = True #Ustawienia ekranu gry self.SCREEN_WIDTH = 500 self.SCREEN_HEIGHT = 500 self.screen = pygame.display.set_mode((self.SCREEN_WIDTH, self.SCREEN_HEIGHT)) #Ustawienia gry self.PLATFORM_NUMBER = 5 self.SKELETON_NUMBER = 4 #Zegar self.clock = pygame.time.Clock() #Tworzenie instancji gracza self.player = Adventurer(250,250, self.screen,self.SCREEN_WIDTH, self.SCREEN_HEIGHT ) #Zmienna do obsługi kolizji gracza z wrogiem self.hit_delay = 0 #Tworzenie grup sprite self.all_sprites = pygame.sprite.Group() self.all_platforms = pygame.sprite.Group() self.all_enemies = pygame.sprite.Group() #Platformy startowe self.PLATFORM_LIST = [(0,self.SCREEN_HEIGHT - 40,self.SCREEN_WIDTH, 40), (300, 430, 100, 10), (100, 400, 100, 10), (430,350,100,10), (150, 270,100,10), (200,200,100,10), (250, 130, 100,10), (50,50,200,20)] #Dodawanie spritów do grup self.all_sprites.add(self.player) for plat in self.PLATFORM_LIST: p = Platform(*plat) #wpisanie argumentów do argumentów klasy self.all_sprites.add(p) self.all_platforms.add(p)
def start_game(self, name, current_canvas): """Checks if an adventurer name was given, if not, creates a popup prompting for a name. If a name is given, the creation menu is hidden, the dungeon is generated, and the adventurer is placed at the entrance. The main game logic is started by the Main_Game class. Adds the start menu to the window behind the main game to allow the game to restart if the main game ends.""" if name.strip() == "": error_window = Toplevel() error_window.title("Error") message = Label(error_window, text="Please enter a name", font="Times 20").grid(row=0, column=0) else: current_canvas.grid_forget() self.adventurer = Adventurer("") self.adventurer.name = name self.dungeon.generate() self.dungeon.visited_rooms.clear() self.dungeon.visited_rooms.append(self.dungeon.unique_rooms[0]) entrance = self.dungeon.unique_rooms[0].position() entrance_row, entrance_col = entrance[0], entrance[1] self.adventurer.set_location(entrance_row, entrance_col) self.startmenu.grid(row=0, column=0) main_game = Main_Game(self.root, self.dungeon, self.adventurer) main_game.frame.grid(row=0, column=0)
def test_adventurer_use_healing_potion(self): player = Adventurer("player") hit_point = player.hit_point() player.use_healing_potion() self.assertEqual(player.hit_point(), hit_point)
print('LOOK or L - Lets you see the map/room again. ') print('QUESTS - Lists all your active and completed quests. ') print('INV - Lists all the items in your inventory. ') print('CHECK - Lets you see an item (or yourself) in more detail. ') print('NORTH or N - Moves you to the north. ') print('SOUTH or S - Moves you to the south. ') print('EAST or E - Moves you to the east. ') print('WEST or W - Moves you to the west. ') print('QUIT - Ends the adventure.') if order == 'LOOK' or order == 'L': cur_room.draw() # cur_room.draw() if order == 'INV': print('You are carrying:') inv = adventurer.get_inv() if len(inv) == 0: print('Nothing.') if order == 'CHECK': item = input("Check what? ") if item in adventurer.inventory: print(item) else: print("You don't have that!") if __name__ == '__main__': args = sys.argv[1:] adventurer = Adventurer() rooms_list, items_list, quests_list = [], [], [] read_config(args) cur_room = rooms_list[0] commands(adventurer, cur_room)
class Adventure: # changes to a 'current' location to go a specific direction NORTH = [0, -1] EAST = [1, 0] SOUTH = [0, 1] WEST = [-1, 0] def __init__(self, map_file_name, class_name): self.player = Adventurer('Tango', class_name) # default character self.bot = Playerbot() # the robot the player will interact with self.player_x = 0 # player's current x-coord self.player_y = 0 # player's current y-coord self.world = Map( map_file_name) # load the given map as the world for the adventure self.won = False # has the player beaten the adventure? self.determine_start() def determine_start(self): ''' determine_start figures out where the game will start on the map ''' starts = self.world.get_starting_cells() start = starts[ die.roll(len(starts)) - 1] # randomly choose a start location from those possible self.player_x, self.player_y = start def move_player(self, loc_mod): ''' move_player alters the player's location based on the given modifier ''' self.player_x += loc_mod[0] self.player_y += loc_mod[1] self.bot.move(loc_mod) # if the player moves onto a road, take the road in the same direction until a visitable cell is reached if self.world.cells[self.player_y][self.player_x].is_road(): self.move_player(loc_mod) def start(self): ''' start kicks off an adventure ''' # keep visiting locations until the move count runs out moves = 20 while not self.won and self.player.hp > 0 and moves > 0: self.visit_location() moves -= 1 # based on how game ended, inform Android if self.won: Client.sendMessage('win') elif moves == 0: Client.sendMessage('no moves') else: Client.sendMessage('died') def travel_options(self): ''' travel_options returns a list of valid options for leaving the current cell ''' opt = [] # north if not (self.player_y - 1 < 0) and self.world.cells[self.player_y - 1][ self.player_x].id != '#': opt.append('north') # east if not (self.player_x + 1 > len(self.world.cells[self.player_y]) - 1) and self.world.cells[self.player_y][self.player_x + 1].id != '#': opt.append('east') # south if not (self.player_y + 1 > len(self.world.cells) - 1) and self.world.cells[self.player_y + 1][self.player_x].id != '#': opt.append('south') # west if not (self.player_x - 1 < 0) and self.world.cells[self.player_y][ self.player_x - 1].id != '#': opt.append('west') return opt def visit_action(self, opt): ''' visit_action handles the user's choice of action ''' # ask Android for user's choice. no validation necessary because Android will only present user with valid options choice = Client.sendMessage('action:' + str(opt)) print("\taction choice:", choice) # set up items for interaction items = self.world.cells[self.player_y][self.player_x].items chest, pool = None, None # possible items to interact with on the cell for it in items: if isinstance(it, item.Chest): chest = it elif isinstance(it, item.Key): self.player.backpack.append( it) # keys are automatically picked up self.world.cells[self.player_y][self.player_x].items.remove( it) # remove the key from the cell once player picks it up print('\t***********PICKED UP KEY******************') elif isinstance(it, item.RadiantPool): pool = it # handle movement choice if choice == 'north': self.move_player(Adventure.NORTH) elif choice == 'east': self.move_player(Adventure.EAST) elif choice == 'south': self.move_player(Adventure.SOUTH) elif choice == 'west': self.move_player(Adventure.WEST) # handle interaction choice else: # if interacting with a chest, see if the player has any keys that unlock it if choice == 'chest': for it in self.player.backpack: if isinstance(it, item.Key): if chest.unlocked_by(it): self.won = True if not self.won: Client.sendMessage( 'need key' ) # inform Android that the player does not have the right key # a pool heals the player for a specified number of points elif choice == 'pool': pool.cleanse(self.player) def visit_combat(self): ''' visit_combat performs combat for the current cell ''' if len(self.world.cells[self.player_y][self.player_x].npcs) == 0: return True # skip combat if there's nobody to fight targets = [] # list of the names of possible targets for enemy in self.world.cells[self.player_y][self.player_x].npcs: targets.append(str(enemy).lower()) Client.sendMessage('combat:' + str(targets)) # inform Android combat has started self.bot.encounter() # as long as there are combatants, fight while len(self.world.cells[self.player_y][self.player_x].npcs) > 0: # player acts first choice = Client.sendMessage( 'hp:' + str(self.player.hp)) # expect 'attack' or 'run' print('\tcombat choice:\'' + choice + '\'') if choice == 'run': # player has a 75% chance to successfully run if die.roll(4) > 1: Client.sendMessage( 'run:true') # tell Android run was successful self.determine_start( ) # teleport the player off to a starting location break else: Client.sendMessage( 'run:false') # tell Android run was not successful # player attack phase # choice = Client.sendMessage('target') # ask Android for a valid target target = self.world.cells[self.player_y][ self.player_x].get_npc_by_name( targets[0]) # step 2 only allows 1 opponent per cell player_dmg = self.player.roll_damage() self.bot.hit() Client.sendMessage('dealt:' + str(player_dmg)) # if the target dies as a result of the damage, remove it from the cell and from list of possible targets if not target.take_damage(player_dmg): self.world.cells[self.player_y][self.player_x].npcs.remove( target) targets.remove(target.name) Client.sendMessage('gained:' + str(target.xp_worth())) # NPC attack phase for npc in self.world.cells[self.player_y][self.player_x].npcs: npc_dmg = npc.roll_damage() Client.sendMessage( 'recv:' + str(npc_dmg) ) # tell Android how much damage player was dealt to the player if not self.player.take_damage(npc_dmg): return False return True def visit_location(self): ''' visit_location enables the player to visit a location ''' # combat happens immediately. return if player dies if not self.visit_combat(): return self.visit_options() # prompt user with post-combat options def visit_options(self): ''' visit_options presents the player with all post-combat options ''' opt = self.travel_options( ) # directions player can travel from current location # output items for item in self.world.cells[self.player_y][self.player_x].items: opt.append(str(item)) # prompt user and take action self.visit_action(opt)
def create_adv(): """This method asks user for Character Name input. This should reference the Adventurer Class""" player_name = input( "Welcome to the bridge of death... What is your name? ") player = Adventurer(player_name)
def user_input(): """This method will allow the user to perform a set of tasks based on the room and inventory the adventurer holds: Move, use healing/vision potion, view inventory, give up""" keystroke = input( "What would you like to do? Press \"1\" for all options.") # print all options if keystroke == "1": options = [] if Room.move_up is True: options.append("u") if Room.move_down is True: options.append("d") if Room.move_left is True: options.append("l") if Room.move_right is True: options.append("r") if Adventurer.healing_potions > 0: options.append("h") if Adventurer.vision_potions > 0: options.append("v") options.append("q") print(options) user_input() # quit option if keystroke == "q": a = input( "Temptation to quit is the greatest just before you are about " "to succeed. Do you really want to give up? (y or n) ") if a == "y": print( "There is a difference between giving up and knowing when you had enough.\n" "Better luck next time. Game over.") # press Enter to restart restart_game() if a == "n": user_input() # move adventurer if keystroke == "u": Adventurer.move_up() if keystroke == "d": Adventurer.move_down() if keystroke == "l": Adventurer.move_left() if keystroke == "r": Adventurer.move_right() #use healing potion if keystroke == "h": Adventurer.use_healing_potion() # use vision potion if keystroke == "v": Adventurer.use_vision_potion() # hidden menu item to show map if keystroke == "map": print_dungeon() else: input("That is not a valid command. Try again. ") # prints new room, then prompts for next user input print_room() user_input()
class Adventure: # changes to a 'current' location to go a specific direction NORTH = [0, -1] EAST = [1, 0] SOUTH = [0, 1] WEST = [-1, 0] def __init__(self, map_file_name, class_name): self.player = Adventurer('Tango', class_name) # default character self.player_x = 0 # player's current x-coord self.player_y = 0 # player's current y-coord self.world = Map( map_file_name) # load the given map as the world for the adventure self.won = False # has the player beaten the adventure? self.determine_start() def determine_start(self): ''' determine_start figures out where the game will start on the map ''' starts = self.world.get_starting_cells() start = starts[ die.roll(len(starts)) - 1] # randomly choose a start location from those possible self.player_x, self.player_y = start def move_player(self, loc_mod): ''' move_player alters the player's location based on the given modifier ''' self.player_x += loc_mod[0] self.player_y += loc_mod[1] # if the player moves onto a road, take the road in the same direction until a visitable cell is reached if self.world.cells[self.player_y][self.player_x].is_road(): self.move_player(loc_mod) def start(self): ''' start kicks off an adventure ''' # print(self.world) # print('Starting', self.player, 'at (' + str(self.player_x) + ',' + str(self.player_y) + ')') # keep visiting locations until the move count runs out moves = 20 while not self.won and self.player.hp > 0 and moves > 0: self.visit_location() moves -= 1 print() if self.won: print('The key unlocked the chest! You win!') elif moves == 0: print('You ran out of moves!') else: print('YOU DIED') def travel_options(self): ''' travel_options returns a list of valid options for leaving the current cell ''' opt = [] # north if not (self.player_y - 1 < 0) and self.world.cells[self.player_y - 1][ self.player_x].id != '#': opt.append('north') # east if not (self.player_x + 1 > len(self.world.cells[self.player_y]) - 1) and self.world.cells[self.player_y][self.player_x + 1].id != '#': opt.append('east') # south if not (self.player_y + 1 > len(self.world.cells) - 1) and self.world.cells[self.player_y + 1][self.player_x].id != '#': opt.append('south') # west if not (self.player_x - 1 < 0) and self.world.cells[self.player_y][ self.player_x - 1].id != '#': opt.append('west') return opt def visit_action(self, opt): ''' visit_action handles the user's choice of action ''' while True: # take in user choice and check if valid choice = input("What would you like to do? ").lower() if opt.count(choice) == 0: print("\tInvalid choice. Try again.") continue # handle movement choice if choice == 'north': self.move_player(Adventure.NORTH) elif choice == 'east': self.move_player(Adventure.EAST) elif choice == 'south': self.move_player(Adventure.SOUTH) elif choice == 'west': self.move_player(Adventure.WEST) # handle interaction choice else: items = self.world.cells[self.player_y][self.player_x].items chest, key, pool = None, None, None for it in items: if isinstance(it, item.Chest): chest = it elif isinstance(it, item.Key): key = it elif isinstance(it, item.RadiantPool): pool = it # if interacting with a chest, see if there are any keys that unlock it if choice == 'chest': for it in self.player.backpack: if isinstance(it, item.Key): if chest.unlocked_by(it): self.won = True if not self.won: print('\tYou need a key to unlock this chest.') # interacting with a key picks it up elif choice == 'key': print('\tYou picked up the key.') self.player.backpack.append(key) self.world.cells[self.player_y][ self.player_x].items.remove(key) # a pool heals the player for a specified number of points elif choice == 'radiant pool': hp = self.player.hp pool.cleanse(self.player) print('\tYou healed for', self.player.hp - hp, 'hit points.') else: print('Interacting with \'' + choice + '\'s is not supported.') continue break # exit when a valid choice has been made def visit_combat(self): ''' visit_combat performs combat for the current cell ''' if len(self.world.cells[self.player_y][self.player_x].npcs) == 0: return True targets = [] # list of the names of possible targets print('You are attacked!', end=' ') for enemy in self.world.cells[self.player_y][self.player_x].npcs: print(enemy, end=' ') targets.append(str(enemy).lower()) print('enters combat with you.') # as long as there are combatants, fight while len(self.world.cells[self.player_y][self.player_x].npcs) > 0: # player acts first print('\tYou have', self.player.hp, 'hp.', end=' ') choice = input('Attack or run? ').lower() if choice == 'run': # player has a 75% chance to successfully run if die.roll(4) > 1: print('\t\tSuccessfully ran away.') self.determine_start() break else: print('\t\tCannot escape!') # player attack phase choice = input('\tChoose a target: ').lower() while targets.count(choice) == 0: print('\tInvalid target.') choice = input('\tChoose a target: ').lower() target = self.world.cells[self.player_y][ self.player_x].get_npc_by_name(choice) player_dmg = self.player.roll_damage() print('\t\tDealt', player_dmg, 'damage to', target) # if the target dies as a result of the damage, remove it from the cell if not target.take_damage(player_dmg): # if player levels up due to the XP if self.player.gain_xp(target.xp_worth()): print('\t\tLevel up! You are now level', self.player.level) self.world.cells[self.player_y][self.player_x].npcs.remove( target) print('\t\t' + str(target), 'evaporated!') print('\t\tGained', target.xp_worth(), 'xp.') # all NPCs hit for npc in self.world.cells[self.player_y][self.player_x].npcs: npc_dmg = npc.roll_damage() print('\t\tYou took', npc_dmg, 'points of damage from', npc) if not self.player.take_damage(npc_dmg): return False return True def visit_location(self): ''' visit_location enables the player to visit a location ''' # print(self.world.cells[self.player_y][self.player_x].id) # combat happens immediately. return if player dies if not self.visit_combat(): return self.visit_options() # prompt user with post-combat options def visit_options(self): ''' visit_options presents the player with all post-combat options ''' opt = self.travel_options( ) # directions player can travel from current location # output possible directions print('\nYou see a path to the', opt[0].capitalize(), end='') for i in range(1, len(opt)): print(',', opt[i].capitalize(), end='') print('.') # output items if len(self.world.cells[self.player_y][self.player_x].items) > 0: print('On the ground in front of you is a ', end='') for i, item in enumerate( self.world.cells[self.player_y][self.player_x].items): if i > 0: print(',', end=' ') opt.append(str(item)) print(str(item).title(), end='') print('.') # prompt user and take action self.visit_action(opt)
#Begin the program only if the appropriate files are inserted into the command prompt. Retrieve info from CONFIG files and use this information to make Adventurer, Item, Quest, and Room objects. if len(sys.argv) != 4: sys.exit("Usage: python3 simulation.py <paths> <items> <quests>") #If the file name does not exist, raise the error and catch the exception. try: paths = create_rooms(read_paths(sys.argv[1])) items = generate_items(sys.argv[2]) quests = generate_quests(sys.argv[3], items, paths) except FileNotFoundError: print("Please specify a valid configuration file.") sys.exit() #Create the character and assign its location to the first room in the configuration file and then begin the game. character = Adventurer() character.current_room = paths[0] character.current_room.draw() print() while True: """Receive commands from standard iput and act appropriately""" user_input = input(">>> ").lower() if user_input == "quit": """Leave the game if user_input == QUIT""" print("Bye!") sys.exit() elif user_input == "help": """List all valid commands and their usage"""
def test_adventurer_decrease_hit_points(self): player = Adventurer("player") hit_point = player.hit_point() player.decrease_hit_points(5) decrease_hit_points = hit_point - 5 self.assertEqual(player.hit_point(), decrease_hit_points)
def test_adventurer_set_location(self): player = Adventurer("player") player.set_location(1, 2) self.assertEqual(player.current_location, (1, 2))
def test_adventurer_current_location(self): player = Adventurer("player") player_location = player.current_location self.assertEqual(player_location, (0, 0))
width=4) if self.dungeon.check_west(row, col): self.canvas.create_line(200 * (display_col) + 10, 200 * display_row + 55, 200 * (display_col) + 10, 200 * display_row + 165, fill="white", width=4) if self.dungeon.check_east(row, col): self.canvas.create_line(200 * (display_col + 1) + 10, 200 * display_row + 55, 200 * (display_col + 1) + 10, 200 * display_row + 165, fill="white", width=4) if __name__ == '__main__': from adventurer import Adventurer root = Tk() test = Dungeon(6, 6) test.generate() Tom = Adventurer("Tom") mapdrawer = MapDisplay(test, root) # entire_map = mapdrawer.draw_entire_map() # entire_map.pack() player_map = mapdrawer.draw_player_map(Tom) player_map.pack() root.mainloop()
# print monthsMessage2 # 2. Initialize Pygame. # Why do we need to do this? Because they told us to. pygame.init() # 3. Make a screen with a size. The size MUST be a tuple screen_size = (512, 480) pygame_screen = pygame.display.set_mode(screen_size) # set the title of the window that opens... pygame.display.set_caption("GAME OF 'NO NAME'") theHero = Hero() bad_guy = BadGuy() adventurer = Adventurer() # make a bad_guys group bad_guys = Group() # add the bad_guy to the bad_guys group bad_guys.add(bad_guy) bad_guys.add(Adventurer()) # make a start button start_button = Start_Button(pygame_screen, monthsMessage) start_button2 = Start_Button2(pygame_screen) # make a group for our arrows to live in # a group is a pygame thing. Its like a list, # but with cool stuff too arrows = Group() adventurers = Group() # ========VARIABLES FOR OUR GAME==========
class AdventureGUI: def __init__(self): self.dungeon = Dungeon(4, 4) self.dungeon.generate() self.adventurer = Adventurer("") self.root = Tk() self.root.resizable(False, False) self.root.title("Dungeon Adventure") self.start_menu_init() def start(self): """Creates the tkinter window containing the game. Used to delay startup so that changes can be made to the dungeon and adventurer for testing specific cases.""" self.root.mainloop() def start_menu_init(self): """Builds the start menu for the game. Has a button to start a new game, display instructions and exit the program.""" self.startmenu = Frame(self.root) self.startmenu.grid(row=0, column=0) menu_spacer = Frame(self.startmenu, height=100, width=600).grid(row=0, column=0) title = Label(self.startmenu, text="502 Dungeon Adventure", font="Times 40", pady=50).grid(row=1, column=0) new_game_button = Button(self.startmenu, text="New Game", font="Times 20", command=self.game_init).grid(row=2, column=0) instructions_button = Button(self.startmenu, text="Instructions", font="Times 20", command=self.display_instructions).grid( row=3, column=0) exit_button = Button(self.startmenu, text="Exit", font="Times 20", command=self.root.destroy).grid(row=4, column=0) menu_spacer2 = Frame(self.startmenu, height=100, width=600).grid(row=5, column=0) def display_instructions(self): """Displays basic instructions for the game. Hides the start menu and replaces it with a screen containing text from a separate text file. Creates a button that will return the user to the start menu.""" self.startmenu.grid_forget() instruction_file = open("dungeon_instruct.txt", 'r') instruction_text = instruction_file.read() instruct_frame = Frame(self.root, height=600, width=600) instruct_frame.grid(row=0, column=0) t = Text(instruct_frame, wrap="word", font="Times 16") t.grid(row=0, column=0) t.insert("1.0", instruction_text) instruction_file.close() back_button = Button( instruct_frame, text="Back", font="Times 20", command=lambda: self.return_to_start(instruct_frame)).grid( row=1, column=0) def return_to_start(self, current): """Hides the tkinter object that is passed in and displays the start menu object.""" current.grid_forget() self.startmenu.grid(row=0, column=0) def game_init(self): """Creates a menu for choosing game settings. Provides an entry for setting an adventurer name and buttons for selecting the game difficulty. The default difficulty is easy and buttons are toggled.""" def set_difficulty(difficulty): if difficulty == "Hard": dungeon.resize_dungeon(10, 10) easy_button["relief"] = "raised" medium_button["relief"] = "raised" hard_button["relief"] = "sunken" elif difficulty == "Medium": dungeon.resize_dungeon(7, 7) easy_button["relief"] = "raised" medium_button["relief"] = "sunken" hard_button["relief"] = "raised" elif difficulty == "Easy": dungeon.resize_dungeon(4, 4) easy_button["relief"] = "sunken" medium_button["relief"] = "raised" hard_button["relief"] = "raised" else: pass dungeon = self.dungeon adventurer = self.adventurer self.startmenu.grid_forget() creation_menu = Frame(self.root) creation_menu.grid(row=0, column=0) new_name = Label(creation_menu, text="Adventurer Name: ", font="Times 14") new_name.grid(row=0, column=0, columnspan=2) name_entry = Entry(creation_menu, width=40) name_entry.grid(row=0, column=2) difficulty = Label(creation_menu, text="Choose difficulty:", font="Times 14") difficulty.grid(row=1, column=0, columnspan=2) hard_button = Button(creation_menu, text="Hard", command=lambda: set_difficulty("Hard")) hard_button.grid(row=2, column=2) medium_button = Button(creation_menu, text="Medium", command=lambda: set_difficulty("Medium")) medium_button.grid(row=3, column=2) easy_button = Button(creation_menu, text="Easy", relief="sunken", command=lambda: set_difficulty("Easy")) easy_button.grid(row=4, column=2) confirm_button = Button( creation_menu, text="Confirm", font="Times 16", command=lambda: self.start_game(name_entry.get(), creation_menu)) confirm_button.grid(row=6, column=0) back_button = Button( creation_menu, text="Back", font="Times 16", command=lambda: self.return_to_start(creation_menu)) back_button.grid(row=6, column=1) def start_game(self, name, current_canvas): """Checks if an adventurer name was given, if not, creates a popup prompting for a name. If a name is given, the creation menu is hidden, the dungeon is generated, and the adventurer is placed at the entrance. The main game logic is started by the Main_Game class. Adds the start menu to the window behind the main game to allow the game to restart if the main game ends.""" if name.strip() == "": error_window = Toplevel() error_window.title("Error") message = Label(error_window, text="Please enter a name", font="Times 20").grid(row=0, column=0) else: current_canvas.grid_forget() self.adventurer = Adventurer("") self.adventurer.name = name self.dungeon.generate() self.dungeon.visited_rooms.clear() self.dungeon.visited_rooms.append(self.dungeon.unique_rooms[0]) entrance = self.dungeon.unique_rooms[0].position() entrance_row, entrance_col = entrance[0], entrance[1] self.adventurer.set_location(entrance_row, entrance_col) self.startmenu.grid(row=0, column=0) main_game = Main_Game(self.root, self.dungeon, self.adventurer) main_game.frame.grid(row=0, column=0)
class Game(object): def __init__(self): pygame.init() #Obsługa głównej petli self.run = True #Ustawienia ekranu gry self.SCREEN_WIDTH = 500 self.SCREEN_HEIGHT = 500 self.screen = pygame.display.set_mode((self.SCREEN_WIDTH, self.SCREEN_HEIGHT)) #Ustawienia gry self.PLATFORM_NUMBER = 5 self.SKELETON_NUMBER = 4 #Zegar self.clock = pygame.time.Clock() #Tworzenie instancji gracza self.player = Adventurer(250,250, self.screen,self.SCREEN_WIDTH, self.SCREEN_HEIGHT ) #Zmienna do obsługi kolizji gracza z wrogiem self.hit_delay = 0 #Tworzenie grup sprite self.all_sprites = pygame.sprite.Group() self.all_platforms = pygame.sprite.Group() self.all_enemies = pygame.sprite.Group() #Platformy startowe self.PLATFORM_LIST = [(0,self.SCREEN_HEIGHT - 40,self.SCREEN_WIDTH, 40), (300, 430, 100, 10), (100, 400, 100, 10), (430,350,100,10), (150, 270,100,10), (200,200,100,10), (250, 130, 100,10), (50,50,200,20)] #Dodawanie spritów do grup self.all_sprites.add(self.player) for plat in self.PLATFORM_LIST: p = Platform(*plat) #wpisanie argumentów do argumentów klasy self.all_sprites.add(p) self.all_platforms.add(p) #Obsługa eventów def events(self): # Obsługa wydarzeń for event in pygame.event.get(): if event.type == pygame.QUIT: self.run = False if pygame.key.get_pressed()[pygame.K_ESCAPE]: self.run = False # Aktualizacja położeń i akcji def update(self): #Platformy self.all_platforms.update() # Utrzymanie odpowiedniej ilosci wrogów na ekranie self.create_enemy() # Wrogowie self.all_enemies.update() #Sprawdzenie kolizji player-platform platform_colide = pygame.sprite.spritecollide(self.player,self.all_platforms, False ) if platform_colide: self.player.y = platform_colide[0].rect.top - self.player.height #ustawienie gracza na platformie w przypadku kolizji self.player.vel[1] = 0 #usunięcie przemieszczenia pionowego # Przesuwanie "ekranu" w góre jeżeli gracz osiagnie 3/4 wysokości ekranu if self.player.rect.y <= self.SCREEN_HEIGHT /4: self.player.y += abs(self.player.vel[1]) for plat in self.all_platforms: plat.rect.y += abs(self.player.vel[1]) #Usunięcie platform poniżej dolnej granicy ekranu if plat.rect.top >= self.SCREEN_HEIGHT: plat.kill() self.player.score += 10 #Zwiekszenie punktacji wraz z każdą pokonaną platformą #Powtórzenie operacji w przypadku wrogów for enemy in self.all_enemies: enemy.rect.y += abs(self.player.vel[1]) if enemy.rect.top >= self.SCREEN_HEIGHT: enemy.kill() #Utrzymanie odpowieniej ilosci platform na ekranie while len(self.all_platforms) < self.PLATFORM_NUMBER: width = random.randrange(100,300) height = random.randrange(5,30) p = Platform(random.randrange(0,self.SCREEN_WIDTH - width),random.randrange(-30,-10),width,height) self.all_platforms.add(p) self.all_sprites.add(p) #Gracz self.player.update(self.all_platforms) #Sprawdzanie czy gracz ciagle pozostaje na ekranie "GAME OVER CONDITION" if self.player.rect.bottom >= self.SCREEN_HEIGHT: for sprite in self.all_sprites: sprite.rect.y -= max(self.player.vel[1],10) #efekt spadania gracza oraz platform if sprite.rect.bottom < 0: sprite.kill() #usuwanie obiektów opuszczających ekran if len(self.all_platforms) == 0: self.game_over_screen() #Sprawdzenie poziomu zycia gracza if self.player.health <= 0: self.game_over_screen() #Sprawdzenie kolizji gracz-wrog self.collision_check() # Tworzenie obiektów na ekranie def redrawGameWindow(self): self.screen.fill((0,0,0)) self.all_platforms.draw(self.screen) self.player.draw() #Rysowanie przeciwników na podstawie stworzonej metody for enemy in self.all_enemies.sprites(): enemy.draw() #Wyświetlanie wyniku self.draw_text(str(self.player.score), 30, (255,0,0), self.SCREEN_WIDTH/2, 20) pygame.display.update() # Wyświetlanie tekstu def draw_text(self, text, size, color, x, y): font = pygame.font.SysFont('comicsans', size) text_surface = font.render(text, True, color) text_rect = text_surface.get_rect() text_rect.midtop = (x,y) self.screen.blit(text_surface, text_rect) #Ekran startowy gry def start_screen(self): self.screen.fill((0,255,0)) self.draw_text("Brave Adventurer!", 50, (0,0,255), self.SCREEN_WIDTH/2, self.SCREEN_HEIGHT/4) self.draw_text("Arrows to move and jump.", 40, (0,0,255),self.SCREEN_WIDTH/2,self.SCREEN_HEIGHT/2 ) self.draw_text("Press a key to play.", 40, (0, 0, 255), self.SCREEN_WIDTH / 2, self.SCREEN_HEIGHT *3/4) pygame.display.flip() self.key_wait() #Oczekiwanie na wciśniecie przycisku przez gracza def key_wait(self): waiting = True while waiting: self.clock.tick(25) for event in pygame.event.get(): if event.type == pygame.QUIT: waiting = False self.run = False if event.type == pygame.KEYUP: waiting = False #Ekran końcowy rozgrywki def game_over_screen(self): self.screen.fill((255,0,0)) self.draw_text("GAME OVER!", 100, (0,0,0),self.SCREEN_WIDTH/2,self.SCREEN_HEIGHT/2) pygame.display.flip() self.key_wait() self.run = False #Tworzenie przeciwników na planszy def create_enemy(self): #dodawanie przeciwniak jeśli jest ich mniej niż 3 na planszy if len(self.all_enemies) <= self.SKELETON_NUMBER - 1 : top_platforms = [] # lista zawierające platformy znajdujące się powyżej górnej granicy ekranu for plat in self.all_platforms.sprites(): if plat.rect.y < 0 and plat.is_skeleton_on == False: #Tworzenie szkielete tylko na platformach powyżej granicy ekranu i bez szkieleta na niej top_platforms.append(plat) if top_platforms: plat = random.choice(top_platforms) #wybór losowej platformy do umieszczenia wroga #Pozycja wroga na planszy x = random.randint(plat.rect.x, plat.rect.x + plat.width) y = plat.rect.top - 33 enemy = Skeleton(x, y, self.screen, plat) self.all_sprites.add(enemy) self.all_enemies.add(enemy) #Platforma może posiadać tylko 1 szkieleta plat.is_skeleton_on = True # Metoda sprawdzająca kolizje gracza z przeciwnikami oraz wystrzelonymi przez nich pociskami def collision_check(self): #Sprawdzenie oglnej kolizji z wrogami coliding_enemies = pygame.sprite.spritecollide(self.player, self.all_enemies,False) if coliding_enemies: #Sprawdzenie kolizji mask coliding_enemies_mask = pygame.sprite.spritecollide(self.player, coliding_enemies,False, pygame.sprite.collide_mask) if coliding_enemies_mask: #Jeżeli gracz nie blokuje ataków odejmowane jest mu życie for enemy in coliding_enemies_mask: #Odwracanie wroga w stronę gracza if enemy.rect.x > self.player.rect.x: enemy.left = True enemy.right = False enemy.vel[0] = - enemy.vel[0] elif enemy.rect.x < self.player.rect.x: enemy.left = False enemy.right = True enemy.vel[0] = - enemy.vel[0] enemy.attack = True #włączenie animacji ataku if enemy.hit: self.player.health -= 10 enemy.hit = False #Jeżeli gracz atakuje, odebranie życia wrogowi if self.player.attack == False: if self.player.attack2Count >= 12 and self.player.attack2Count <= 15: #zadanie obrażeń tylko w odpowiednim miejscu animacji enemy.health -= self.player.attack_2_damage self.player.attack = True
def test_adventurer_has_all_pillars(self): player = Adventurer("player") self.assertFalse(player.has_all_pillars())
import sys from room import Room from adventurer import Adventurer from item import Item from quest import Quest #Calling the Adventurer Class adv = Adventurer() pSource ="p" iSource ="i" paths = [] rooms = [] items = [] quests =[] #Calling the reading congfig files def main(pathSource, itemSource, questSource): global pSource pSource = pathSource global iSource iSource = itemSource global qSource qSource = questSource currentRoom = None #Checking that there is 3 configuration files else print error and quit if (len(sys.argv) < 4): print("Usage: python3 simulation.py <paths> <items> <quests>")
class PlayGame: _game_over, _game_win = False, False _game_cave = [] _game_adventurer = Adventurer() _user_input = "" _RAND_MAX = 20 _RAND_MIN = 1 def __init__(self): self._game_cave = Cave() def start_game(self): print(" WELCOME TO HUNT THE WUMPUS\n" + "YOU MUST FIND THE WUMPUS IN HIS DARK AND DANGEROUS LAIR!\n" + "YOU ARE EQUIPPED WITH A BOW AND FIVE ARROWS.") while not self._game_over: self._game_turn() if self._game_win: print("YOU SLEW THE FOUL WUMPUS!!!!") def _game_turn(self): current_room = self._game_cave.visit_room(self._game_adventurer.current_room) print("YOU ARE IN ROOM : "+str(self._game_adventurer.current_room)) if current_room[0]: self._encountered_wumpus() elif current_room[1]: self._encountered_pit() elif current_room[2]: self._encountered_bats() if not self._game_over: self._check_connected_rooms() self._user_input = input(": ") self._interpret_command() def _interpret_command(self): goto_schemes = ("GO", "GOTO", "GO TO", "G") shoot_schemes = ("SHOOT", "S") look_schemes = ("LOOK", "L") quit_schemes = ("QUIT", "Q") if self._user_input.upper().startswith(goto_schemes): room = re.search("\d+", self._user_input).group() self._go_to_room(int(room)) elif self._user_input.upper().startswith(shoot_schemes): room = re.search("\d+", self._user_input).group() self._shoot_arrow(int(room)) elif self._user_input.upper().startswith(look_schemes): self._look() elif self._user_input.upper().startswith(quit_schemes): print("Goodbye....") self._game_over = True else: print("SORRY I DIDN'T UNDERSTAND THAT") def _go_to_room(self, room): if room in self._game_cave.cave_map[self._game_adventurer.current_room]: self._game_adventurer.set_current_room(room) else: print("YOU CANT GET THERE FROM HERE") def _shoot_arrow(self, room): print("TWWANG YOU LOOSE AN ARROW FROM YOUR MIGHTY YEW BOW!!") if room in self._game_cave.cave_map[self._game_adventurer.current_room]: if self._game_cave.visit_room(room)[0]: print("YOUR SWIFT ARROW PUNCTURES THE HEART OF THE STINKING BEAST!") self._game_win = True self._game_over = True return print("CRUNCH THE ARROW BREAKS AGAINST THE STONE WALL OF THE CAVE!") self._arrow_missed() def _look(self): rooms = self._game_cave.cave_map[self._game_adventurer.current_room] print("YOU SEE PATHS TO ROOMS "+str(rooms[0])+", "+str(rooms[1])+" and "+str(rooms[2])) def _check_connected_rooms(self): rooms = self._game_cave.cave_map[self._game_adventurer.current_room] for e in rooms: if self._game_cave.visit_room(e)[0]: print("YOU SMELL THE FOUL STENCH OF THE WUMPUS!") if self._game_cave.visit_room(e)[1]: print("YOU HEAR A RUSH OF WIND WHISTLING FROM A NEARBY CAVE!") if self._game_cave.visit_room(e)[2]: print("YOU HEAR A LEATHERY FLAPPING NOISE!") def _arrow_missed(self): if randint(0, 3) != 3: print("You woke the Wumpus!") self._game_cave.wumpus_move() def _encountered_wumpus(self): print("YOU ARE DEVOURED BY THE EVIL WUMPUS") self._game_over = True def _encountered_bats(self): print("OH NO YOU WERE GRABBED BY THE SUPER BATS") self._game_adventurer.current_room = randint(self._RAND_MIN, self._RAND_MAX) def _encountered_pit(self): print("YOU STUMBLE DOWN A BOTTOMLESS PIT!!") self._game_over = True