def start(self): """Use this method to start the game""" player_name = self.interface.greet() self.player = Player(player_name) self.interface.display(initial_narration()) self.init_level() self.interface.display(self.level.draw_map())
class GameState: def __init__(self): self.rnd = 0 self.memory = [] self.computer = Computer() self.player = Player() self.winner = None def print_board(self): print() for cell in range(9): # start each row in the board if cell in [0, 3, 6]: print("\t\t", end="") # print piece in each box if cell in self.computer.pieces: print(" C ", end="") elif cell in self.player.pieces: print(" P ", end="") else: print(" ", end="") # print row separators if cell in [2, 5]: print("\n\t\t", "-"*11, sep="") elif cell == 8: print("\n") else: print("|", end="") def over(self, justPlayed): if not self.computer.has_moves(self) and not self.player.has_moves(self): self.winner = justPlayed return True if self.player.crossed_board() or not self.computer.has_moves(self): self.winner = 'P' return True elif self.computer.crossed_board() or not self.player.has_moves(self): self.winner = 'C' return True else: return False def save_memory(self, connection): db = connection.cursor() winLoss = 2 if self.winner == 'C' else 1 variables = [] for move, pPieces, cPieces in self.memory: variables.append((move[0], move[1], str(pPieces), str(cPieces), winLoss)) db.executemany('''INSERT INTO memory ("from", "to", "player_pieces", "computer_pieces", "game_result") VALUES (?, ?, ?, ?, ?)''', variables) connection.commit()
def set_players(self, color_current_user): self.player1 = Player(color_current_user, True) color_player2 = 'white' if color_current_user == 'black' else 'black' if not self.with_bot: self.player2 = Player(color_player2) else: self.player2 = Bot(color_player2)
def play_against_player(): challenger_1_name = request.form["player_1"] challenger_1_gesture = request.form["P1-gesture"] challenger_2_name = request.form["player_2"] challenger_2_gesture = request.form["P2-gesture"] challenger_1 = Player(challenger_1_name, challenger_1_gesture) challenger_2 = Player(challenger_2_name, challenger_2_gesture) return render_template("index.html", winner=play(challenger_1, challenger_2), title="Winner")
def test_update_force() -> None: """ Test if it is possible to update the position of a player based on the force from the area layer """ player = Player(0, 0, None) player.velocity = np.ones(2) player.position = 500 * np.ones(2) friction_matrix = np.ones((1000, 1000)) friction = FrictionLayer(friction_matrix=friction_matrix) arena = Arena(width=1000, height=1000, layers=[friction]) assert np.any(arena.force(player) != 0)
def __init__(self, team1, team2, player1_name, player2_name, player3_name, player4_name): self.player1 = Player(player1_name) self.player2 = Player(player2_name) self.player3 = Player(player3_name) self.player4 = Player(player4_name) self.player_list = [ self.player1, self.player2, self.player3, self.player4 ] self.team1 = Team(team1, self.player1, self.player3) self.team2 = Team(team2, self.player2, self.player4) self.team_list = [self.team1, self.team2]
def __init__(self, player_name, deck): ''' Session to record played games. Give a Player class and a Deck class as an argument to properly setup the session. ''' self._num_of_games = 0 self._player_wins = 0 self._dealer_wins = 0 self.player = Player(player_name) self.dealer = Player('Dealer') self.deck = deck
def _boarder_collisions(self, player: Player) -> None: """ Simulate elastic collisions with the walls. To prevent the player from moving through the wall, the position is fixed, and the velocity reflected according to conservation to momentum. :param player: the given player to be investigated. """ if player.position[0] - player.data.player_size <= 0: player.position[0] = player.data.player_size player.velocity[0] = -player.velocity[0] elif player.position[0] + player.data.player_size >= self.arena.width: player.position[0] = self.arena.width - player.data.player_size player.velocity[0] = -player.velocity[0] if player.position[1] - player.data.player_size <= 0: player.position[1] = player.data.player_size player.velocity[1] = -player.velocity[1] elif player.position[1] + player.data.player_size >= self.arena.height: player.position[1] = self.arena.height - player.data.player_size player.velocity[1] = -player.velocity[1] # check collisions: for player_i in [p for p in self.players if p is not player]: r1 = player.position r2 = player_i.position R1 = player.data.player_size R2 = player_i.data.player_size if np.linalg.norm(r1 - r2) < R1 + R2: pass
def parse_player(self, player, team_name) -> Player: name = player.find(class_="abbr") points = player.find(class_="pts") assists = player.find(class_="ast") rebounds = player.find(class_="reb") minutes = player.find(class_="min") fg = player.find(class_="fg") three_pt = player.find(class_="3pt") return Player({ "team": team_name, "name": name.text if name else "", "points": int(points.text) if points and points.text.isnumeric() else 0, "assists": int(assists.text) if assists and assists.text.isnumeric() else 0, "rebounds": int(rebounds.text) if rebounds and rebounds.text.isnumeric() else 0, "minutes": int(minutes.text) if minutes and minutes.text.isnumeric() else 0, "fg": fg.text if fg and re.match("[0-9]+-[0-9]+", fg.text) else "0-0", "3pt": three_pt.text if three_pt and re.match("[0-9]+-[0-9]+", three_pt.text) else "0-0" })
def __init__(self): self.logo = "\n \n \n \ ;+''''+; \n +;:,,,,:;+ \n +:,......,:+ \n +\ ;,........,;+ \n ',..........,' \n .;,..........,;. \n \ ;;,..........,;; \n ';:'',....,''::' \n ';#@@+....+@@#;' \n \ ;;@##@.,,.@##@;; \n #;+##',.,,+##+;# \n +;,,,,,..,,,,,;+ \ \n +;::::,'',::::;+ \n +';;:::@@:::;;'+ \n :++;;::::;;++:\ \n +';;;;;+ \n ++';;'++ \n" print(chr(27) + "[2J") print(self.logo) self.players = [Player()] print(chr(27) + "[2J") print(self.logo) self.players.append(Player()) print(chr(27) + "[2J") self.turn = False
def Easter_Egs(entry): if this.AllowEasternEggs == True: debug("Easter Check") # and entry['PlayerPilot'] == True and entry["Fighter"] == False if entry['event'] == "HullDamage" and entry[ 'PlayerPilot'] == True and entry["Fighter"] == False: if entry['Health'] < 0.3: debug("plaing sound") Player(this.plugin_dir, ["sounds\\hullAlarm.wav"]).start()
def generate_level(level_map, player_image, enemy_image): """Генерирует уровень, в котором w - стена, . - пустое пространство(пол), @ - игрок""" player = None for tile_object in level_map.tmxdata.objects: if tile_object.name == 'Player': player = Player(player_image, tile_object.x, tile_object.y) if tile_object.name == 'Obstacle': Obstacle(tile_object.x, tile_object.y, tile_object.width, tile_object.height) if tile_object.name == 'Mob': Enemy(enemy_image, tile_object.x, tile_object.y, player, Enemy.PISTOL) return player
def main(): sensor = Sensor() #while True: # print("Distance received: " + str(sensor.get_distance())) player = Player() player.load_file() player.play() print("wait") for i in reversed(range(10)): print(i) time.sleep(1) print("tryna stop") player.stop() print("exiting")
def add_player(self): """ Add a new player to the game. @return player_id: the unique ID to be associated with the added player. """ player_id = uuid4().hex self.players[player_id] = Player(player_id, self.is_next_seller) # TODO give player a card if they join halfway through? self.players[player_id].stats = [PlayerStat(None, None, None)] * len( self.rounds) # Alternate between buyer and seller for each new player self.is_next_seller = not self.is_next_seller return player_id
async def register_all(self, ctx): """Register to every available modes in one command.""" game = get_game(ctx) name = ctx.author.id for mode in game.leaderboards: if name not in game.leaderboards[mode]: game.leaderboards[mode][name] = Player(ctx.author.name, ctx.author.id) num = int(split_with_numbers(mode)[0]) role = discord.utils.get(ctx.guild.roles, name=f"{num}vs{num} Elo Player") await ctx.author.add_roles(role) await ctx.send(embed=Embed( color=0x00FF00, description=f"<@{name}> has been registered for every mode."))
def main(): p1 = Player("X") p2 = Player("Y") players = [p1, p2] p1.has_turned = False b = Board() b.draw() game = True while game: for i, player in enumerate(players): if player.has_turned == False: val = input(f"{player.char}s Turn. Specify the Field on the Board you want to change: ") if int(val) <= 8: if b.check_val(val) == "0": b.set_val(player, val) player.has_turned = True if i == 0: players[1].has_turned = False elif i == 1: players[0].has_turned = False b.draw() ret = b.check_if_won(player) if ret == player.char: print(f"Player {player.char} has won!") game = False break elif ret == "Tie": print("Tie!") game = False break else: val = input(f"{player.char}s Turn. Specify the Field on the Board you want to change: ") else: print("[-] Please pick a Value between 0-8")
def play_against_computer(): # user input challenger_1_name = request.form["player_1"] challenger_1_gesture = request.form["P1-gesture"] challenger_1 = Player(challenger_1_name, challenger_1_gesture) # random computer selection gestures = ["Rock", "Paper", "Scissors"] computer_roll = random.choice(gestures) # computer_roll = random.randint(0,2) # if computer_roll == 0: # computer_roll = "Rock" # elif computer_roll == 1: # computer_roll = "Paper" # computer_roll = "scissors" computer = Computer("Computer", computer_roll) return render_template("PvC.html", winner=play(challenger_1, computer), title="Winner")
async def register(self, ctx, mode): """Register the player to the elo leaderboard. Example: !r N or !r N all This command will register the user into the game mode set in argument. The game mode needs to be the N in NvsN, and it needs to already exist. This command can be used only in the register channel. The command will fail if the mode doesn't exist (use !modes to check).""" game = get_game(ctx) name = ctx.author.id if name in game.leaderboards[mode]: await ctx.send(embed=Embed( color=0x000000, description=f"There's already a played called <@{name}>.")) return game.leaderboards[mode][name] = Player(ctx.author.name, ctx.author.id) await ctx.send(embed=Embed( color=0x00FF00, description=f"<@{name}> has been registered.")) num = split_with_numbers(mode)[0] role = discord.utils.get(ctx.guild.roles, name=f"{num}vs{num} Elo Player") await ctx.author.add_roles(role)
def test_move_player(): """ Check if the code is able to change the position of a player """ player = Player() # Initialize a player player.mass = 100 player.force = np.array([-10.0, 0.0]) player.position = np.array([10.0, 10.0]) player.velocity = np.array([50.0, 50.0]) assert np.any(np.not_equal(player.force, np.zeros(2))) assert np.any(np.not_equal(player.position, np.zeros(2))) assert np.any(np.not_equal(player.velocity, np.zeros(2))) # Initialize a area arena = Arena(layers=[]) physics = Physics(arena=arena, players=[player], time_step=0.1) physics.move_players() np.testing.assert_array_equal(player.velocity, np.array([49.99, 50])) np.testing.assert_array_equal(player.position, np.array([14.999, 15]))
from setting import * import pygame from modules.player import Player from modules.background import Background from modules.bullet import Bullet from modules.enemy import Enemy from modules.score import * import random, math # -------------------------------------------------SCREEN DEFENITION win = pygame.display.set_mode((W_WIDTH, W_HEIGHT)) title = pygame.display.set_caption(TITLE) # -------------------------------------------------INIT OBJECTS player = Player(W_WIDTH // 2) backgrounds = [Background(0), Background(-W_HEIGHT)] bullets, enemies = [], [] status_bar = StatusBar() score_meter = ScoreMeter() health_bar = HealthBar() # -------------------------------------------------CONTROL FUNCS def player_control(): player.draw(win) player.move() def bullet_control(): for bul in bullets: bul.draw(win)
__copyright__ = "(c) Matthew Johnson 2019" __license__ = "Creative Commons Attribution-ShareAlike 2.0 Generic License." __author__ = "Matt" __version__ = "1.4" #import required modules import pygame as p #to simplify and shorten import random #spawn asteroids in random positions from modules.player import Player #class that handels all player functions from modules.enemy import Enemy #class that handels all enemy functions from modules.button import Button #class that handels all button functions from modules.message import Message #class that handels all message functions player = Player() #make the player class callable enemy = Enemy() #make the enemy class callable p.init() #initiate pygame window and all other elements #sets the display width and height width_display = 800 height_display = 600 gameDisplay = p.display.set_mode( (width_display, height_display)) #makes game display when called upon p.display.set_caption("Space Invaders") #creates the title name for the window clock = p.time.Clock() #simplifies the clock module space_background = p.image.load( "asserts/space background.png" ) #loads in the choosen image to be displayed later
def __init__(self): self.player = Player(self) self.guard = Guard() self.ether = Ether() self.draw_map = getmap.GetMap() self.wall = Wall()
def setUp(self): self.rock = Player("Roosa", "rock") self.paper = Player("Colin", "paper") self.scissors = Player("Hannah", "scissors")
from modules.environment import Environment from modules.player import Player env = Environment(p1=Player(name='Alice'), p2=Player(name='Bob')) env.launch_game(iterations=10)
class Engine: """This class ties it all together and might be viewed as something somewhat akin to a controller in an MVC framework. """ def __init__(self, library_path, prompt_func=input, print_func=print): self.prompt_char = ">" self.library_path = library_path self.reset_game() self.interface = CommandLine(self, prompt_func, print_func) self.bag = Bag() self.level = None self.player = None self.player_in_room = None self.room = None for direction in ("north", "south", "east", "west"): while not self.add_direction_to_commands(direction): pass # The heart of what we want to do within this while loop is contained within # The add_direction_to_commands function. We just want to keep calling it # until it returns True. def start(self): """Use this method to start the game""" player_name = self.interface.greet() self.player = Player(player_name) self.interface.display(initial_narration()) self.init_level() self.interface.display(self.level.draw_map()) def init_level(self): """Looks up the level information from file, loads it and inserts the player into the room. """ self.room = LevelLoader(self.library_path, self.room_file) self.level = self.room.enter(self.player, "entrance") self.player_in_room = True self.interface.display(self.room.room_description()) def reset_game(self): """Returns the game to its initial state""" self.room_file = "level_1.json" self.player_in_room = False def in_room(self): """Used to determine if the player is currently in a room""" if self.player == None: return False return self.player.in_room() def load_player(self, player): """Attribute setter for the player""" self.player = player def north(self): """Moves the player north if able""" if not self.level.can_go_north(self.player): self.interface.display("You cannot go north") else: for creature in self.level.get_move_ai(): if creature.coords == (self.player.coords[0], self.player.coords[1] + 1): self.attack(creature) break else: self.player.travel("n") def south(self): """Moves the player south if able""" if not self.level.can_go_south(self.player): self.interface.display("You cannot go south") else: for creature in self.level.get_move_ai(): if creature.coords == (self.player.coords[0], self.player.coords[1] - 1): self.attack(creature) break else: self.player.travel("s") def east(self): """Moves the player east if able""" if not self.level.can_go_east(self.player): self.interface.display("You cannot go east") else: for creature in self.level.get_move_ai(): if creature.coords == (self.player.coords[0] + 1, self.player.coords[1]): self.attack(creature) break else: self.player.travel("e") def west(self): """Moves the player west if able""" if not self.level.can_go_west(self.player): self.interface.display("You cannot go west") else: for creature in self.level.get_move_ai(): if creature.coords == (self.player.coords[0] - 1, self.player.coords[1]): self.attack(creature) break else: self.player.travel("w") def attack(self, enemy): dmg = self.player.weapon.damage self.interface.display("You attack the " + enemy.name + " for " + str(dmg) + " damage!") response = enemy.take_damage(dmg) enemy.set_target(self.player) if response: self.interface.display(response) for index, item in enumerate(self.level.contents): if item is enemy: self.level.remove(enemy.name) def exit(self): """Tests for exit conditions and exits the player if they are met The length of this method suggests that it is ripe for splitting these actions into separate methods """ can_exit = self.level.exit(self.player) if can_exit: self.display_exit_message() if not self.enter_next_level(): self.player_in_room = False self.interface.display_end_of_game() else: format_string = "Sorry, you are not at an exit of {0}." message = format_string.format(self.room.name) self.interface.display(message) return can_exit def display_exit_message(self): """Displays the level's exit text to the user if it exists""" if self.room.exit_text == None: self.interface.display("You have exited {0}".format(self.room.name)) elif self.room.exit_text == "final" and "bacon" in self.bag.items: self.interface.display(final_narration_win()) elif self.room.exit_text == "final" and "bacon" not in self.bag.items: self.interface.display(final_narration_lose()) else: self.interface.display(self.room.exit_text) def enter_next_level(self): """Transports the player to the next level or returns False if there is no next level """ next_level, has_next_level = self.room.enter_next_level(self.player) if has_next_level: self.level = next_level self.interface.display(self.room.room_description()) return True return False def item_count(self): """Displays the player's inventory""" self.interface.display(self.bag.look()) def coordinates(self): """Returns the x, y coordinates of the player""" coords = self.player.locate() message = "Your co-ordinates are: ({0},{1})".format(coords[0], coords[1]) self.interface.display(message) def vaccum_key_and_gold(self): """Automagically picks up gold and keys""" if self.pick_up_item("key"): self.interface.display("You picked up the key!") if self.pick_up_item("gold"): self.interface.display("You picked up the gold!") if self.pick_up_item("bacon"): self.interface.display("You picked up the bacon!") def vaccum_weapons(self): """Swiftly picks up Excalibur""" if self.pick_up_item("excalibur"): self.interface.display("Behold! The most power ever felt!") def pick_up_item(self, item): """Allows the player to pick up and item by removing an item from the room and placing it in their bag """ if self.level.get_by_name(item) != None: player_coord = self.player.locate() item_coord = self.level.get_by_name(item).locate() if player_coord == item_coord: self.bag.add(Item(item)) self.level.remove(item) return True return False def display_help(self): """Displays the help menu""" self.interface.display_help(self.in_room()) def invalid_command(self): """Displays a message that tells the user their command was invalid""" self.interface.display("Sorry that command is not valid.") self.interface.display("Please type 'help' and press enter for a menu.") def main_loop(self): """This is the core game loop that cycles through the turns""" play = True self.start() while play: play = self.move_player() if self.in_room(): self.vaccum_key_and_gold() self.vaccum_weapons() play &= self.move_creatures() if play: self.interface.display(self.level.draw_map()) self.interface.display(self.player.show_health()) def move_player(self): """Gets the command from the player and moves (or quits)""" command = self.interface.prompt(self.prompt_char).lower() possible_commands = self.interface.current_commands(self.in_room()) if command == "q": return False else: if not self.execute_command(command, possible_commands): self.invalid_command() return True def execute_command(self, command, commands): """Executes the command if valid, returns false if invalid""" try: cmd_tuple = commands[command] cmd_tuple[0]() return True except KeyError: return False def move_creatures(self): """Moves the creatures in the room""" creatures = self.level.get_move_ai() for creature in creatures: target_tile = next_tile(creature.coords, creature.target) if target_tile == self.player.coords: dmg = creature.weapon.damage self.interface.display("You were attacked by the " + creature.name + " for " + str(dmg) + " damage!") response = self.player.take_damage(dmg) if response: self.interface.display(response) return False else: creature.move() return True def add_direction_to_commands(self, direction): if not hasattr(self, direction): self.interface.display("That is not a valid direction") return False response = self.interface.prompt("Please choose a key to be your {} movement: ".format(direction)) if response in self.interface.command_mapping: self.interface.display( "That key is already in use to {}".format(self.interface.command_mapping[response][1]) ) return False self.interface.command_mapping[response] = (getattr(self, direction), "move {}".format(direction), False) return True
def load_stage_2(): state.time_counter = 0 # background and foreground state.bkg.image = assets.image_assets["img_bkg_level_2"] state.frg.image = assets.image_assets["img_frg_level_2"] # player player = Player(state, assets, x=500, y=200, batch=main_batch, group=groups[5]) window.push_handlers(player) window.push_handlers(player.key_handler) # health bar health_bar = HealthBar(state, assets, x=state.player_life, y=900, batch=main_batch, group=groups[8]) # infection bar infection_bar = InfectionBar(state, assets, x=state.infection_level, y=970, batch=main_batch, group=groups[8]) # virus spawner spawn_locations = [(139, 828), (293, 603), (330, 291), (101, 141), (483, 71), (754, 214), (941, 221), (634, 521), (782, 665), (871, 845)] virus_spawner = VirusSpawner(state, assets, spawn_locations, x=-5, y=0, batch=main_batch, group=groups[5]) # stage - polygon colliders vertices1 = [403, 0, 343, 122, 173, 46, 151, 1] vertices2 = [600, 58, 660, 0, 1001, 0, 998, 35, 656, 167] vertices3 = [1001, 730, 795, 555, 739, 379, 871, 275, 1001, 275] vertices4 = [1, 742, 0, 193, 170, 269, 204, 500, 123, 701] vertices5 = [289, 1001, 374, 696, 626, 657, 730, 865, 657, 1000] polygon1 = PolygonCollider(util.get_points(vertices1), state, assets, "poly1", group=groups[5]) polygon2 = PolygonCollider(util.get_points(vertices2), state, assets, "poly2", group=groups[5]) polygon3 = PolygonCollider(util.get_points(vertices3), state, assets, "poly3", group=groups[5]) polygon4 = PolygonCollider(util.get_points(vertices4), state, assets, "poly4", group=groups[5]) polygon5 = PolygonCollider(util.get_points(vertices5), state, assets, "poly5", group=groups[5]) # list of all game objects game_objects.append(player) game_objects.append(health_bar) game_objects.append(infection_bar) game_objects.append(virus_spawner) game_objects.append(polygon1) game_objects.append(polygon2) game_objects.append(polygon3) game_objects.append(polygon4) game_objects.append(polygon5)
class Session(): ''' Session to record played games. Give a Player class as an argument to properly setup the session. ''' def __init__(self, player_name, deck): ''' Session to record played games. Give a Player class and a Deck class as an argument to properly setup the session. ''' self._num_of_games = 0 self._player_wins = 0 self._dealer_wins = 0 self.player = Player(player_name) self.dealer = Player('Dealer') self.deck = deck def game_winner(self, winner): ''' Declare the game winner. 1 = Human 2 = Dealer ''' if winner == 1: self._player_wins += 1 elif winner == 2: self._dealer_wins += 1 def start_next_game(self): ''' Starts the next blackjack game. Increases the games played by one, and adds cards to the player's and the dealer's hand. ''' self.player.clear_hand() self.dealer.clear_hand() self.deck.reset_deck() self._num_of_games += 1 for _ in range(2): self.player.add_card(self.deck.deal_card()) self.dealer.add_card(self.deck.deal_card()) def player_busted(self): ''' Checks if the human player busted, that is his/her hand value is over 21. ''' if self.player.get_hand_value() > 21: return True return False def dealer_busted(self): ''' Checks if the human player busted, that is his/her hand value is over 21. ''' if self.dealer.get_hand_value() > 21: return True return False
def load_stage_3(): state.time_counter = 0 # background and foreground state.bkg.image = assets.image_assets["img_bkg_level_3"] state.frg.image = assets.image_assets["img_frg_level_3"] # player player = Player(state, assets, x=150, y=800, batch=main_batch, group=groups[5]) window.push_handlers(player) window.push_handlers(player.key_handler) # health bar health_bar = HealthBar(state, assets, x=state.player_life, y=900, batch=main_batch, group=groups[8]) # infection bar infection_bar = InfectionBar(state, assets, x=state.infection_level, y=970, batch=main_batch, group=groups[8]) # virus spawner spawn_locations = [(97, 733), (96, 551), (169, 363), (468, 394), (659, 167), (774, 346), (896, 544), (732, 742), (570, 905), (359, 863)] virus_spawner = VirusSpawner(state, assets, spawn_locations, x=-5, y=0, batch=main_batch, group=groups[5]) # stage - polygon colliders vertices1 = [449, 252, 241, 209, 0, 239, 0, 0, 509, 0] vertices2 = [1001, 404, 889, 352, 815, 145, 830, 0, 1001, 0] vertices3 = [ 187, 601, 286, 489, 440, 532, 591, 509, 652, 627, 600, 739, 320, 742 ] vertices4 = [ 699, 910, 864, 889, 977, 793, 1001, 799, 1001, 1001, 784, 1001 ] polygon1 = PolygonCollider(util.get_points(vertices1), state, assets, "poly1", group=groups[5]) polygon2 = PolygonCollider(util.get_points(vertices2), state, assets, "poly2", group=groups[5]) polygon3 = PolygonCollider(util.get_points(vertices3), state, assets, "poly3", group=groups[5]) polygon4 = PolygonCollider(util.get_points(vertices4), state, assets, "poly4", group=groups[5]) # list of all game objects game_objects.append(player) game_objects.append(health_bar) game_objects.append(infection_bar) game_objects.append(virus_spawner) game_objects.append(polygon1) game_objects.append(polygon2) game_objects.append(polygon3) game_objects.append(polygon4)
class Engine: """This class ties it all together and might be viewed as something somewhat akin to a controller in an MVC framework. """ def __init__(self, library_path, prompt_func=input, print_func=print): self.prompt_char = ">" self.library_path = library_path self.reset_game() self.interface = CommandLine(self, prompt_func, print_func) self.bag = Bag() self.level = None self.player = None self.player_in_room = None self.room = None for direction in ("north", "south", "east", "west"): while not self.add_direction_to_commands(direction): pass # The heart of what we want to do within this while loop is contained within # The add_direction_to_commands function. We just want to keep calling it # until it returns True. def start(self): """Use this method to start the game""" player_name = self.interface.greet() self.player = Player(player_name) self.interface.display(initial_narration()) self.init_level() self.interface.display(self.level.draw_map()) def init_level(self): """Looks up the level information from file, loads it and inserts the player into the room. """ self.room = LevelLoader(self.library_path, self.room_file) self.level = self.room.enter(self.player, "entrance") self.player_in_room = True self.interface.display(self.room.room_description()) def reset_game(self): """Returns the game to its initial state""" self.room_file = "level_1.json" self.player_in_room = False def in_room(self): """Used to determine if the player is currently in a room""" if self.player == None: return False return self.player.in_room() def load_player(self, player): """Attribute setter for the player""" self.player = player def north(self): """Moves the player north if able""" if not self.level.can_go_north(self.player): self.interface.display("You cannot go north") else: for creature in self.level.get_move_ai(): if creature.coords == (self.player.coords[0], self.player.coords[1] + 1): self.attack(creature) break else: self.player.travel("n") def south(self): """Moves the player south if able""" if not self.level.can_go_south(self.player): self.interface.display("You cannot go south") else: for creature in self.level.get_move_ai(): if creature.coords == (self.player.coords[0], self.player.coords[1] - 1): self.attack(creature) break else: self.player.travel("s") def east(self): """Moves the player east if able""" if not self.level.can_go_east(self.player): self.interface.display("You cannot go east") else: for creature in self.level.get_move_ai(): if creature.coords == (self.player.coords[0] + 1, self.player.coords[1]): self.attack(creature) break else: self.player.travel("e") def west(self): """Moves the player west if able""" if not self.level.can_go_west(self.player): self.interface.display("You cannot go west") else: for creature in self.level.get_move_ai(): if creature.coords == (self.player.coords[0] - 1, self.player.coords[1]): self.attack(creature) break else: self.player.travel("w") def attack(self, enemy): dmg = self.player.weapon.damage self.interface.display("You attack the " + enemy.name + " for " + str(dmg) + " damage!") response = enemy.take_damage(dmg) enemy.set_target(self.player) if response: self.interface.display(response) for index, item in enumerate(self.level.contents): if item is enemy: self.level.remove(enemy.name) def exit(self): """Tests for exit conditions and exits the player if they are met The length of this method suggests that it is ripe for splitting these actions into separate methods """ can_exit = self.level.exit(self.player) if can_exit: self.display_exit_message() if not self.enter_next_level(): self.player_in_room = False self.interface.display_end_of_game() else: format_string = "Sorry, you are not at an exit of {0}." message = format_string.format(self.room.name) self.interface.display(message) return can_exit def display_exit_message(self): """Displays the level's exit text to the user if it exists""" if self.room.exit_text == None: self.interface.display("You have exited {0}".format( self.room.name)) elif self.room.exit_text == "final" and "bacon" in self.bag.items: self.interface.display(final_narration_win()) elif self.room.exit_text == "final" and "bacon" not in self.bag.items: self.interface.display(final_narration_lose()) else: self.interface.display(self.room.exit_text) def enter_next_level(self): """Transports the player to the next level or returns False if there is no next level """ next_level, has_next_level = self.room.enter_next_level(self.player) if has_next_level: self.level = next_level self.interface.display(self.room.room_description()) return True return False def item_count(self): """Displays the player's inventory""" self.interface.display(self.bag.look()) def coordinates(self): """Returns the x, y coordinates of the player""" coords = self.player.locate() message = "Your co-ordinates are: ({0},{1})".format( coords[0], coords[1]) self.interface.display(message) def vaccum_key_and_gold(self): """Automagically picks up gold and keys""" if self.pick_up_item("key"): self.interface.display("You picked up the key!") if self.pick_up_item("gold"): self.interface.display("You picked up the gold!") if self.pick_up_item("bacon"): self.interface.display("You picked up the bacon!") def vaccum_weapons(self): """Swiftly picks up Excalibur""" if self.pick_up_item("excalibur"): self.interface.display("Behold! The most power ever felt!") def pick_up_item(self, item): """Allows the player to pick up and item by removing an item from the room and placing it in their bag """ if self.level.get_by_name(item) != None: player_coord = self.player.locate() item_coord = self.level.get_by_name(item).locate() if player_coord == item_coord: self.bag.add(Item(item)) self.level.remove(item) return True return False def display_help(self): """Displays the help menu""" self.interface.display_help(self.in_room()) def invalid_command(self): """Displays a message that tells the user their command was invalid""" self.interface.display("Sorry that command is not valid.") self.interface.display( "Please type 'help' and press enter for a menu.") def main_loop(self): """This is the core game loop that cycles through the turns""" play = True self.start() while play: play = self.move_player() if self.in_room(): self.vaccum_key_and_gold() self.vaccum_weapons() play &= self.move_creatures() if play: self.interface.display(self.level.draw_map()) self.interface.display(self.player.show_health()) def move_player(self): """Gets the command from the player and moves (or quits)""" command = self.interface.prompt(self.prompt_char).lower() possible_commands = self.interface.current_commands(self.in_room()) if command == "q": return False else: if not self.execute_command(command, possible_commands): self.invalid_command() return True def execute_command(self, command, commands): """Executes the command if valid, returns false if invalid""" try: cmd_tuple = commands[command] cmd_tuple[0]() return True except KeyError: return False def move_creatures(self): """Moves the creatures in the room""" creatures = self.level.get_move_ai() for creature in creatures: target_tile = next_tile(creature.coords, creature.target) if target_tile == self.player.coords: dmg = creature.weapon.damage self.interface.display("You were attacked by the " + creature.name + " for " + str(dmg) + " damage!") response = self.player.take_damage(dmg) if response: self.interface.display(response) return False else: creature.move() return True def add_direction_to_commands(self, direction): if not hasattr(self, direction): self.interface.display("That is not a valid direction") return False response = self.interface.prompt( "Please choose a key to be your {} movement: ".format(direction)) if response in self.interface.command_mapping: self.interface.display("That key is already in use to {}".format( self.interface.command_mapping[response][1])) return False self.interface.command_mapping[response] = (getattr( self, direction), "move {}".format(direction), False) return True
from modules.environment import Environment from modules.player import Player env = Environment(p1=Player(name='Hanieh')) env.launch_game(iterations=10)
def create_new_world(self): self.world = World() self.player = Player(self.world) self.load_starting_position()