def __play_music_game(self, widget=False): self.__stop_player() self._player = Player() self._player.load(os.path.join(BASE, "Audio", "musica02.ogg")) self._player.play() self._player.set_volumen(self._music_vol) self._player.connect("endfile", self.__play_music_game)
def test_add_lose(): player = Player('1', 'Player') player.add_lose() player.add_lose() losses = player.record[player.LOSSES] assert (losses == 2)
def play_web_game(is_stop, player1: Player, player2: Player, turn_to, send_board_step, send_player1_running, send_player2_running, wait_human_action, game_over): board = Board() while not is_stop(): turn_to(board.current_player) if board.current_player == BOARD.o: if isinstance(player1, Human): action = wait_human_action(1, is_stop) if is_stop(): return board.step(action) else: action = player1.take_action(board, is_output_action=False, running_output_function=send_player1_running, is_stop=is_stop) send_board_step(1, action) else: if isinstance(player2, Human): action = wait_human_action(2, is_stop) if is_stop(): return board.step(action) else: action = player2.take_action(board, is_output_action=False, running_output_function=send_player2_running, is_stop=is_stop) send_board_step(2, action) is_over, winner = board.result() if is_over: game_over(winner) return
def start_until_game_over(player1: Player, player2: Player, board_renderer: BoardRenderer = None): """ Player player1 and player2 play on the board until the game is over, and output the winner. :param player1: Player 1. :param player2: Player 2. :param board_renderer: The board renderer. :return: <int> board The winner returned by board. """ board = Board() while True: # Render. if board_renderer is not None: board.render(board_renderer) # Take action. if board.current_player == BOARD.o: player1.take_action(board, is_output_action=board_renderer is not None) else: player2.take_action(board, is_output_action=board_renderer is not None) # Game over? is_over, winner = board.result() if is_over: if board_renderer is not None: board.render(board_renderer) return winner
def start_until_game_over(player1: Player, player2: Player, board_renderer: BoardRenderer = None): """ 玩家 player1 和玩家 player2 在 board 上进行游戏直到游戏结束,并输出获胜者。 Player player1 and player2 play on the board until the game is over, and output the winner. :param player1: 玩家 1。 Player 1. :param player2: 玩家 2。 Player 2. :param board_renderer: 棋盘渲染器。 The board renderer. :return: <int> board 返回的获胜者。 The winner returned by board. """ board = Board() while True: # 渲染。 Render. if board_renderer is not None: board.render(board_renderer) # 执行动作。 Take action. if board.current_player == BOARD.o: player1.take_action(board, is_output_action=board_renderer is not None) else: player2.take_action(board, is_output_action=board_renderer is not None) # 游戏是否结束。 Game over? is_over, winner = board.result() if is_over: if board_renderer is not None: board.render(board_renderer) return winner
def h_vs_h(self, player_type1, player_type2): """ input : player_type1 and player_type2 are string function: Sets the game to play human vs human output: a list with two human players """ players = list() P1name = self.view.input_option("Enter " + player_type1 + "'s name: ") players.append(Player('1', P1name)) P2name = self.view.input_option("Enter " + player_type2 + "'s name: ") players.append(Player('2', P2name)) return players
def __init__(self,character, name ,percent_first_move, percent_second_move, percent_third_move, percent_fourth_move): Player.__init__(self, character, name) self.percent_first_move = percent_first_move self.percent_second_move = percent_second_move self.percent_third_move = percent_third_move self.percent_fourth_move =percent_fourth_move self.win_checker = Win_Checker() self.block_checker = Block_Checker() self.biggest_percent = 1 self.test=False self.ranges = self.create_ranges(percent_first_move, percent_second_move, percent_third_move, percent_fourth_move)
def test_levelup_by_one(self): ''' tests that player.levelup() increases level by one for randomly chosen level. ''' p1 = Player('p1','elf') # set p1 to random level for i in range(randrange(max_level-1)): p1.level_up() l = p1.level p1.level_up() self.assertEqual(p1.level - l, 1)
def __init__(self): # Create the game camera self.tileSize = Vector2(40, 40) self.screenSize = Vector2(800, 800) pygame.font.init() self.font_renderer = pygame.font.Font( os.path.join("fonts", 'Millennium-Regular_0.ttf'), 24) self.window = Window(self.screenSize, "Robot Clergy", self.tileSize, self.font_renderer) self.camera = Camera(Vector2(20, 20), self.tileSize, self.screenSize) self.mapHolder = MapHolder(["Church"], self.tileSize, self.window.tileLoader) # Timing and delta time stuff self.clock = pygame.time.Clock() self.deltaTime = 0 self.taskList = TaskList() self.timedEventHandler = TimedEvents() for i in range(0, 100): randomNode = self.mapHolder.loadedMap.getRandomEmptyNode() task = Task(randomNode.pos, self.taskListEventCallback, 200, 1, eSkills.CONVINCING) randomNode.addUserAction(UserAction("Go Here", task)) # Init the player class playerImage = self.window.tileLoader.getImageByName("player", 0, 0) self.player = Player(playerImage, self.screenSize, self.taskList, self.tileSize) self.humanSpawner = HumanFactory( self.mapHolder.getCurrentMap().gridSize, self.window.tileLoader, self.tileSize) self.humans = [] self.timedEventHandler.addTimedEvent(1000, self.peopleStartComingForService) self.nmbrOfCreatures = 4 self.AICreatures = [ ClergyRobot(i, random() * 8 * self.tileSize.y, random() * 8 * self.tileSize.y, self.window.tileLoader, self.tileSize, self.taskList) for i in range(self.nmbrOfCreatures) ] self.movingCreaturesGroup = pygame.sprite.Group() self.movingCreaturesGroup.add(self.humans) self.movingCreaturesGroup.add(self.AICreatures) self.timedEventHandler.addTimedEvent(10000, self.addToTimedEvent)
def test_check_block_posibility_player2_col_2(): win_checker = Win_Checker() connect4 = Connect4('clear') board = Board(6, 7) board.matrix = [[' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' '], ['2', ' ', ' ', ' ', ' ', ' ', ' '], ['1', '1', '1', ' ', ' ', '2', ' '], ['1', '1', '2', '2', '2', '1', ' '], ['1', '1', '2', '2', '2', '1', '2']] players = [Player('1', "Player1"), Player('2', "Player2")] actual = 0 #Player1 result = win_checker.check(connect4, board, players, actual) assert (result == 2)
def test_check_normal_flow_empty_matrix_no_win_posibility(): checker = Checker() connect4 = Connect4('clear') board = Board(6, 7) board.matrix = [[' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ']] players = [Player('1', "Player1"), Player('2', "Player2")] actual = 0 #Player1 result = checker.check(connect4, board, players, actual) assert (result == -1)
def test(): map = Pyramid() player = Player() teste = GeoFriend2(map, player) run = True teste.reset_view() while run: teste.render() for event in pygame.event.get(): if event.type == pygame.QUIT: run = False if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: teste.player_step(2) elif event.key == pygame.K_RIGHT: teste.player_step(3) elif event.key == pygame.K_UP: teste.player_step(1) elif event.key == pygame.K_DOWN: teste.player_step(0) elif event.key == pygame.K_SPACE: print("Space pressed") map = Pyramid() teste = GeoFriend2(map, player) # if event.type == pygame.MOUSEBUTTONUP: # print("Mouse event") # pos = pygame.mouse.get_pos() # print(pos) # test()
def __init__(self): self.actions_available = BASE_ACTIONS self.player = Player("NoName", "Male", "Human", None) self.config_loader = UnsuiConfigLoader() self.config_loader.generate()
def test_print_record(self, mock_stdout): player = Player('1', 'Player') player.add_win() player.add_win() player.add_lose() player.print_record() console = "Player Record: Wins: 2 | Losses: 1 | draws: 0\n" assert (mock_stdout.getvalue() == console)
def getPlayers(): #Gets player number and creates player objects numPlayers = int(input('How many players?')) playerList = [] for player in range(numPlayers): playerList.append(Player()) #TODO Get player names return playerList
def __init__(self): self.action_space = Discrete(4) self.maps = [Basic(), Pyramid()] #, HighPlatform() low = [80, 80, 65, 65, 0] high = [1200, 720, 1215, 735, 1310] self.observation_space = Box(low=np.array(low), high=np.array(high)) self.GeoFriend2 = None self.player = Player()
def h_vs_c(self, player_type1, player_type2): """ input : player_type1 and player_type2 are string function: Sets the game to play human vs computer output: a list witha player and an agent """ players = list() P1name = self.view.input_option("Enter " + player_type1 + "'s name: ") players.append(Player('1', P1name)) P2name = self.view.input_option("Enter " + player_type2 + "'s name: ") p = self.get_computer_parameters() players.append(Agent('2', P2name, p[0], p[1], p[2], p[3])) return players
def test_level_growth(self): """ tests that all stats are >= those of previous level (for 1st n levels)""" n = 10 # number of levels to test p1 = Player('p1','elf') for level in range(n): h = p1.health hp= p1.max_hp a = p1.attack ba= p1.base_attack ar= p1.armour l = p1.level p1.level_up() self.assertTrue(p1.health >= h) self.assertTrue(p1.max_hp >= hp) self.assertTrue(p1.attack >= a) self.assertTrue(p1.base_attack >= ba) self.assertTrue(p1.armour >= ar) self.assertTrue(p1.level >= l)
def test_add_win(): player = Player('1', 'Player') player.add_win() player.add_win() player.add_win() wins = player.record[player.WINS] assert (wins == 3)
def start_until_game_over(player1: Player, player2: Player, board_renderer: BoardRenderer = None): """ :param player1: :param player2: :param board_renderer: :return: """ board = Board() while True: if board_renderer is not None: board.render(board_renderer) if board.current_player == BOARD.o: player1.take_action(board, is_output_action=board_renderer is not None) else: player2.take_action(board, is_output_action=board_renderer is not None) is_over, winner = board.result() if is_over: if board_renderer is not None: board.render(board_renderer) return winner
def __init__(self, load=False, input_func=user_input.default_input): if load == False: # define attributes: # self.player = Player("NoName", "Male", "Human", None) self.parser = Parser() self.config_loader = UnsuiConfigLoader() self.GAME_START = datetime.now() self.commands_entered = 0 self.actions_available = BASE_ACTIONS # call set up functions: # self.config_loader.generate() user_input.opening_setup(self,input=input_func) self.events_engine = EventsEngine.EventsEngine(getStartingEvents(self)) else: self.load_game(load)
def __init__ui(self): self.resize(SCREEN_WIDTH, SCREEN_HEIGHT) self.setStyleSheet("background-color: black;") self.deus_machine = {} self.shields = [] self.enemies = [] self.lives = [] self.players = [] self.player_bullets = [] self.enemy_bullets = {} self.scores = [] self.level = Level(self) for i in range(self.players_count): self.players.append(Player(self, i + 1, self.players_count)) self.scores.append(Score(self, i + 1)) self.player_bullets.append([]) self.lives.append([]) self.start_game()
class Gameloop: def __init__(self): # Create the game camera self.tileSize = Vector2(40, 40) self.screenSize = Vector2(800, 800) pygame.font.init() self.font_renderer = pygame.font.Font( os.path.join("fonts", 'Millennium-Regular_0.ttf'), 24) self.window = Window(self.screenSize, "Robot Clergy", self.tileSize, self.font_renderer) self.camera = Camera(Vector2(20, 20), self.tileSize, self.screenSize) self.mapHolder = MapHolder(["Church"], self.tileSize, self.window.tileLoader) # Timing and delta time stuff self.clock = pygame.time.Clock() self.deltaTime = 0 self.taskList = TaskList() self.timedEventHandler = TimedEvents() for i in range(0, 100): randomNode = self.mapHolder.loadedMap.getRandomEmptyNode() task = Task(randomNode.pos, self.taskListEventCallback, 200, 1, eSkills.CONVINCING) randomNode.addUserAction(UserAction("Go Here", task)) # Init the player class playerImage = self.window.tileLoader.getImageByName("player", 0, 0) self.player = Player(playerImage, self.screenSize, self.taskList, self.tileSize) self.humanSpawner = HumanFactory( self.mapHolder.getCurrentMap().gridSize, self.window.tileLoader, self.tileSize) self.humans = [] self.timedEventHandler.addTimedEvent(1000, self.peopleStartComingForService) self.nmbrOfCreatures = 4 self.AICreatures = [ ClergyRobot(i, random() * 8 * self.tileSize.y, random() * 8 * self.tileSize.y, self.window.tileLoader, self.tileSize, self.taskList) for i in range(self.nmbrOfCreatures) ] self.movingCreaturesGroup = pygame.sprite.Group() self.movingCreaturesGroup.add(self.humans) self.movingCreaturesGroup.add(self.AICreatures) self.timedEventHandler.addTimedEvent(10000, self.addToTimedEvent) def getInputs(self): """Return the events corresponding to each button press""" events = pygame.event.get([pygame.KEYDOWN, pygame.KEYUP]) return events def preach(self): self.timedEventHandler.addTimedEvent(10000, self.peopleStartComingForService) def peopleStartComingForService(self): task = Task(Vector2(11 * self.tileSize.x, 5 * self.tileSize.y), self.preach, 250, 4, eSkills.CONVINCING, "Preach") self.taskList.enqueueTask(task) x = self.tileSize.x y = self.tileSize.y entranceLists = [Vector2(19 * x, 5 * y), Vector2(19 * x, 6 * y)] seating = [ Vector2(18 * x, 1 * y), Vector2(18 * x, 2 * y), Vector2(18 * x, 3 * y), Vector2(18 * x, 4 * y), Vector2(18 * x, 7 * y), Vector2(18 * x, 8 * y), Vector2(18 * x, 9 * y), Vector2(18 * x, 10 * y), Vector2(16 * x, 1 * y), Vector2(16 * x, 2 * y), Vector2(16 * x, 3 * y), Vector2(16 * x, 4 * y), Vector2(16 * x, 7 * y), Vector2(16 * x, 8 * y), Vector2(16 * x, 9 * y), Vector2(16 * x, 10 * y), Vector2(14 * x, 1 * y), Vector2(14 * x, 2 * y), Vector2(14 * x, 3 * y), Vector2(14 * x, 4 * y), Vector2(14 * x, 7 * y), Vector2(14 * x, 8 * y), Vector2(14 * x, 9 * y), Vector2(14 * x, 10 * y), ] randomAmountOfHumans = int(random() * len(seating)) for i in range(randomAmountOfHumans): chair = seating[int(random() * len(seating))] seating.remove(chair) humanWaitTask = WaitTask(chair, None, "Listen to preacher", task, eSkills.STUBBORNNESS) self.humans.append( self.humanSpawner.initCreatureAtPos( entranceLists[int(random() * 2)], humanWaitTask)) def handleEvents(self): """Handle the events thrown by the game""" for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() return elif event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: pygame.event.post(pygame.event.Event(pygame.QUIT)) def taskListEventCallback(self): print("A task was just finished") def addToTimedEvent(self): taskPos = self.mapHolder.getCurrentMap().getRandomEmptyNode().pos self.taskList.enqueueTask( Task(taskPos, self.taskListEventCallback, 30, "RandomTask")) self.timedEventHandler.addTimedEvent( self.timedEventHandler.elapsedTime + 5000, self.addToTimedEvent) def startLoop(self): """The main function that runs the whole game.""" # Game loop while pygame.display.get_init(): currentMap = self.mapHolder.getCurrentMap() self.deltaTime = self.clock.get_time() self.timedEventHandler.updateTimer(self.deltaTime) self.player.updateMouse(currentMap) if len(self.humans) > 0: for human in self.humans: if not human.alive: self.humans.remove(human) human.update(currentMap, self.deltaTime) for ai in self.AICreatures: ai.Update(currentMap, self.deltaTime, self.movingCreaturesGroup) npcs = [human for human in self.humans] npcs.extend(self.AICreatures) self.camera.drawScreen(self.window.screen, currentMap, self.player, npcs) debugInfo = [len(self.taskList.listOfTasks)] debugArray = [task.taskName for task in self.taskList.listOfTasks] debugInfo.extend(debugArray) self.camera.drawDebug(self.window.screen, debugInfo) self.handleEvents() if pygame.display.get_init(): pygame.event.pump() try: pygame.display.update() except: print("Display not initialised") self.clock.tick(60)
class GameInstance(object): def __init__(self, load=False, input_func=user_input.default_input): if load == False: # define attributes: # self.player = Player("NoName", "Male", "Human", None) self.parser = Parser() self.config_loader = UnsuiConfigLoader() self.GAME_START = datetime.now() self.commands_entered = 0 self.actions_available = BASE_ACTIONS # call set up functions: # self.config_loader.generate() user_input.opening_setup(self,input=input_func) self.events_engine = EventsEngine.EventsEngine(getStartingEvents(self)) else: self.load_game(load) #------- Actions Functions --------# def generate_rooms_dict(self): ''' this returns a list of all rooms in the area ''' return self.config_loader.get_by_type('room') def check_events(self): ''' Checks all events in the event list to see if they have been triggered. ''' self.events_engine.checkEvents() def load_game(self,fname): with open(fname, 'rb') as f: newgame = pickle.load(f) self.set(newgame) del newgame # Deprecated, replaced by Pickle. Leave here. #self.config_loader.generate(load) #self.player = self.config_loader.create_player() def set(self,game): '''sets all attributes in this game equal to those of given game''' self.player = game.player self.parser = game.parser self.config_loader = game.config_loader self.GAME_START = game.GAME_START self.commands_entered = game.commands_entered self.actions_available = game.actions_available self.events = game.events def save_game(self,fname=DEFAULT_SAVE_FILE): with open(fname,'wb') as f: pickle.dump(self,f,pickle.HIGHEST_PROTOCOL) # Deprecated, replaced by Pickle. Leave here. #self.config_loader.save_game(self.player) def exit_game(self,save=True): if save==True: self.save_game() sys.exit() def take_action(self, command, input=user_input.default_input): # This method now uses the Command object returned from the Parser # This means you can call commands with 2 words, e.g. 'look desk' # TODO: # - Move this code to user_input maybe # ^ Any thoughts on this? This code will become very large as we implement more verbs. # Unless we can devise a smart way to handle them all. if command: if command.verb.name == 'exit': self.exit_game() if command.verb.name == 'look': # call look function of object of command if command.object == None: print self.player.current_location.description elif command.object.type == 'error': invalid_input("I don't understand %s" % command.object.name, input_string=command.raw, tag='unknown object error', game=self) elif 'in' in command.object.prepositional_modifiers: self.config_loader.get_by_type_and_name('item', command.object.name).look_in() else: # If there is no object of look it will print the current room's description self.config_loader.get_by_type_and_name('item', command.object.name).look() if command.verb.name == 'go': if command.object != None: try: target_room = self.config_loader.get_by_type_and_name('room', command.object.name) if target_room.name in self.player.current_location.exits: self.player.current_location = target_room else: print 'Cannot go to '+Fore.GREEN+"{}".format(target_room.name) except ValueError as err: if err.message[0:16] == 'Cannot find room': invalid_input(err.message, input_string=command.raw, tag='room not found', game=self) else: raise else: print self.player.current_location.exits travel_location = input("Which Room?") try: self.player.current_location = self.config_loader.get_by_type_and_name('room', self.player.current_location.exits[int(travel_location)-1]) except ValueError: try: self.player.current_location = self.config_loader.get_by_type_and_name('room', travel_location) except ValueError: invalid_input('Place not recognized.', input_string=travel_location, tag='room specified not found', game=self) if command.verb.name == 'stats': print ' ### USER STATS ### ' self.player.player_status() print ' ### GAME STATS ### ' print 'game started : ', self.GAME_START print 'commands entered : ', self.commands_entered if command.verb.name == 'quests': user_input.get_events_list(self) if command.verb.name == 'help': user_input.help_info() if command.verb.name == 'location': self.player.player_location() if command.verb.name == 'inventory' or command.verb.name == 'bag': print self.player.inventory.list_of_items() if command.verb.name == 'save': self.save_game() if command.verb.name == 'name': print self.player.name else: print "I'm not sure what you mean." self.commands_entered += 1 else: invalid_input('Command not recognized.', input_string=command.raw, tag='unknown command', game=self)
def test_create_Player_1(): Player('1', 'Player1')
import sys import signal from parse import parse_arguments from Player.Player import Player from Player.Receiver import Receiver from Player.protocol.protocol import get_socket receiver = None def signal_handler(sig, frame): receiver.__del__() print("force exit", file=sys.stderr) exit(84) if __name__ == '__main__': args = parse_arguments() if args.name is None or args.port is None: sys.exit(84) signal.signal(signal.SIGINT, signal_handler) sock = get_socket(args.port, args.host) receiver = Receiver(sock) player = Player(receiver, args.name) player.update() receiver.set_receiving(False)
def test_add_draw(): player = Player('1', 'Player') player.add_draw() draws = player.record[player.DRAWS] assert (draws == 1)
class GameInstance(object): def __init__(self): self.actions_available = BASE_ACTIONS self.player = Player("NoName", "Male", "Human", None) self.config_loader = UnsuiConfigLoader() self.config_loader.generate() #------- Actions Functions --------# def generate_rooms_dict(self): ''' this returns a list of all rooms in the area ''' return self.config_loader.get_by_type('room') def take_action(self,action,input=user_input.default_input): """ This function takes an action specified by a string and completes that action. """ # NOTE: currently there is no check to ensure that each action is available # TODO: check to see if action is available before trying... like: # if action in self.actions_available: # === Base Actions: === room_dict = self.generate_rooms_dict() if action == "exit": sys.exit() elif action == "look": print self.player.current_location.description elif action == "enter": raise NotImplementedError('action_main call needs to be fixed') #action_main() elif action == "go": print self.player.current_location.exits travel_location = input("Which Room?") try: self.player.current_location = self.config_loader.get_by_type_and_name('room', self.player.current_location.exits[int(travel_location)-1]) except ValueError: try: self.player.current_location = self.config_loader.get_by_type_and_name('room', travel_location) except ValueError: print 'Place not recognized.' elif action == "stats": self.player.player_status() return True elif action == "help": user_input.help_info() return True elif action == "location": self.player.player_location() return True # === iteminteractions === elif action == "grab": self.player.inventory.add_item(user_input.choose_object(self.keys)) # === monster interactions elif action == "fight": opponent_engine() return True else: print "That's not a valid command!!!"
def handle_events(self, events): temp = (pg.time.get_ticks() // 400) % 2 == 0 if temp != self.show_cursor: self.show_cursor = temp self.draw_text() for e in events: # Any mouse action if e.type == MOUSEBUTTONUP: pos = pg.mouse.get_pos() pos = [ pos[0] - self.rects["Main"].x, pos[1] - self.rects["Main"].y ] # If it happened in this rect if self.rects["Scroll"].collidepoint(*pos): # Scroll up if e.button == BUTTON_WHEELUP: self.scroll = max(0, self.scroll - SCROLL_AMNT) # Scroll down elif e.button == BUTTON_WHEELDOWN: self.scroll = min(self.max_scroll, self.scroll + SCROLL_AMNT) elif e.button == BUTTON_LEFT: pos = [ pos[0] - self.rects["Scroll"].x, pos[1] - self.rects["Scroll"].y ] idx = (pos[1] - self.scroll) // ITEM_H if idx < len( self.files) and pos[0] >= ITEM_W - BUTTON_W: # Top button is play button if (pos[1] - self.scroll) % ITEM_H < BUTTON_W: if self.mode == PLAYER: from Player.Player import Player game_vars.player = Player( c.PlayerFile(name=self.files[idx])) game_vars.player.load() self.mode = UNIVERSE self.file = c.UniverseFolder() self.load_files() else: return WorldSelector(self.files[idx]).run() # Bottom button is delete button else: if YesNo("Delete " + add_spaces(self.files[idx]) + "?", redraw_back=self.draw()).run_now(): if self.mode == PLAYER: remove(self.file.path + self.files[idx] + self.file.extension) elif self.mode == UNIVERSE: rmtree(self.file.path + self.files[idx] + self.file.extension) self.load_files() elif self.rects["New"].collidepoint(*pos) and self.file.valid: pos = [ pos[0] - self.rects["New"].x, pos[1] - self.rects["New"].y ] if self.rects["Create"].collidepoint(*pos): self.create_new() # Key press elif e.type == KEYDOWN: if e.key == K_RETURN: self.create_new() else: self.file.type_char(e) self.draw_text()
def create_player(self): name = self.config.get('player', 'name') race = self.config.get('player', 'race') sex = self.config.get('player', 'sex') current_location = self.get_by_type_and_name('room', self.config.get('player', 'current_location')) loaded_player = Player(name, race, sex, current_location) loaded_player.inventory = Inventory() for item in self.config.getlist('player', 'inventory'): loaded_player.inventory.add_item(self.get_by_type_and_name('item', item)) loaded_player.health = self.config.getint('player', 'health') loaded_player.max_hp = self.config.getint('player', 'max_hp') loaded_player.attack = self.config.getint('player', 'attack') loaded_player.base_attack = self.config.getint('player', 'base_attack') loaded_player.armour = self.config.getint('player', 'armour') loaded_player.xp = self.config.getint('player', 'xp') loaded_player.level = self.config.getint('player', 'level') loaded_player.status = self.config.get('player', 'status') loaded_player.base_xp = self.config.getint('player', 'base_xp') return loaded_player
def test_get_Player_1_character(): player1 = Player('1', 'Player1') character = player1.character assert (character == '1')
def test_get_Player_1_name(): player1 = Player('1', 'Player1') name = player1.name assert (name == 'Player1')
def test_create_Player_2(): Player('2', 'Player2')
class JAMTank(gtk.Window): def __init__(self): gtk.Window.__init__(self) self.set_title("JAMTank") self.set_icon_from_file(os.path.join(BASE, "Iconos", "jamtank.svg")) self.fullscreen() self.screen_wh = (640, 480) self.gameres = (640, 480) self.handlers = { "selectmode": [], "createservermode": [], "createclientmode": [], "servermodel": [], "clientmodel": [], "connectingplayers": [], "singlemode": [], } self.selectmode = False self.servermodel = False self.clientmodel = False self.singlemode = False self.createservermode = False self.createclientmode = False self.connectingplayers = False self._statusgame = False self._player = False self._music_vol = 0.2 self._efect_vol = 0.2 self.connect("key-press-event", self.__key_press_event) self.connect("key-release-event", self.__key_release_event) self.connect("realize", self.__do_realize) self.connect("expose-event", self.__expose) self.show_all() print "JAMTank pid:", os.getpid() gobject.idle_add(self.__switch, False, 1) def __expose(self, widget, context): rect = self.get_allocation() path = os.path.join(BASE, "Mapas", "010.png") pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(path, rect.width, -1) h = pixbuf.get_height() if h < rect.height: pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(path, -1, rect.height) self.get_property("window").draw_pixbuf(None, pixbuf, 0, 0, 0, 0) return True def __do_realize(self, widget): screen = self.get_screen() self.screen_wh = (screen.get_width(), screen.get_height()) self.gameres = (self.screen_wh[0] / 4 * 3, self.screen_wh[1]) xid = self.get_property("window").xid #os.putenv("SDL_WINDOWID", str(xid)) print "Resolución del Monitor:", self.screen_wh print "id de la ventana:", xid print "Geometria:" print "\tGame:", self.gameres print "\tStatusGame:", (self.screen_wh[0] / 4, self.screen_wh[1]) path = os.path.join(BASE, "Iconos", "win01.png") pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(path, self.screen_wh[0], -1) h = pixbuf.get_height() if h < self.screen_wh[1]: pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(path, -1, self.screen_wh[1]) pixmap, mask = pixbuf.render_pixmap_and_mask() style = self.style style.bg_pixmap[gtk.STATE_NORMAL] = pixmap self.set_style(style) self.__play_music_intro() def __set_volumen(self, widget, valor, text, model): if text == "musica": self._music_vol = valor self._player.set_volumen(self._music_vol) elif text == "efectos": self._efect_vol = valor model.juego._audio.set_volumen(self._efect_vol) def __play_music_intro(self, widget=False): self.__stop_player() self._player = Player() self._player.load(os.path.join(BASE, "Audio", "musica01.ogg")) self._player.play() self._player.set_volumen(self._music_vol) self._player.connect("endfile", self.__play_music_intro) def __play_music_game(self, widget=False): self.__stop_player() self._player = Player() self._player.load(os.path.join(BASE, "Audio", "musica02.ogg")) self._player.play() self._player.set_volumen(self._music_vol) self._player.connect("endfile", self.__play_music_game) def __stop_player(self): if self._player: self._player.stop() del(self._player) self._player = False def __reset(self): self.__expose(False, False) self.__kill_client_model() self.__kill_server_model() self.__kill_connectingplayers() self.__kill_create_mode() self.__kill_select_mode() def __select_mode(self, widget, valor): self.__reset() # Necesario if valor == "solo": self.__switch(False, 2) elif valor == "red": self.__switch(False, 3) elif valor == "join": self.__switch(False, 4) elif valor == "creditos": self.__switch(False, 5) elif valor == "salir": self.__stop_player() self.destroy() def __switch(self, widget, valor): self.__reset() # Necesario if valor == 1: # Selección de tipo de juego self.selectmode = SelectMode(self) _id = self.selectmode.connect("switch", self.__select_mode) self.handlers["selectmode"].append(_id) elif valor == 2: # Jugar Solo self.singlemode = SingleModelGame(self) xid = self.get_property("window").xid self.singlemode.rungame(xid, self.gameres) self.singlemode.juego._audio.set_volumen(self._efect_vol) self._statusgame = SingleStatusGame(self, self.screen_wh) self._statusgame.connect("volumen", self.__set_volumen, self.singlemode) self._statusgame.set_nivel(self.singlemode.index) self.singlemode.juego.connect("update", self._statusgame.update) _id = self.singlemode.connect("error", self.__switch, 1) self.handlers["singlemode"].append(_id) _id = self.singlemode.connect("end-game", self.__end_single_game) self.handlers["singlemode"].append(_id) self.__play_music_game() elif valor == 3: # Crear Juego en Red self.createservermode = CreateServerMode(self) _id = self.createservermode.connect("close", self.__switch, 1) self.handlers["createservermode"].append(_id) _id = self.createservermode.connect("accion", self.__accion_create_server) self.handlers["createservermode"].append(_id) elif valor == 4: # Unirse a Juego en Red self.createclientmode = CreateClientMode(self) _id = self.createclientmode.connect("close", self.__switch, 1) self.handlers["createclientmode"].append(_id) _id = self.createclientmode.connect("accion", self.__accion_create_client) self.handlers["createclientmode"].append(_id) elif valor == 5: dialog = Credits(self) dialog.run() dialog.destroy() self.__switch(False, 1) def __accion_create_client(self, mode_client, accion, server_dict, player_dict): self.__reset() if accion == "run": host = server_dict.get("ip", "localhost") nickh = server_dict.get("nick", "JAMTank") del(server_dict["ip"]) del(server_dict["nick"]) self.clientmodel = ClientModelGame(self, host, server_dict, player_dict.get("nick", "JAMTank"), player_dict.get("tanque", "")) _id = self.clientmodel.connect("error", self.__switch, 4) self.handlers["clientmodel"].append(_id) _id = self.clientmodel.connect("end-game", self.__end_multi_game) self.handlers["clientmodel"].append(_id) if self.clientmodel.client_run(): self.connectingplayers = ConnectingPlayers( self, nickh, server_dict) self.connectingplayers.internal_widget.jugar.hide() _id = self.connectingplayers.connect("close", self.__switch, 4) self.handlers["connectingplayers"].append(_id) _id = self.connectingplayers.connect("accion", self.__accion_connecting_players_client) self.handlers["connectingplayers"].append(_id) _id = self.clientmodel.connect("players", self.connectingplayers.update_playeres) self.handlers["clientmodel"].append(_id) _id = self.clientmodel.connect("play-run", self.__play_run) self.handlers["clientmodel"].append(_id) self.clientmodel.new_handler_registro(True) else: print "ERROR:", self.__accion_create_client elif accion == "salir": self.__switch(False, 1) def __accion_create_server(self, mode_server, accion, _dict): self.__reset() if accion == "run": new_dict = { "jugadores": int(_dict.get("enemigos", 1) + 1), #"jugadores": int(_dict.get("enemigos", 1)), "mapa": str(_dict.get("mapa", "")), "vidas": int(_dict.get("vidas", 5)) } self.servermodel = ServerModelGame(self, _dict.get("server", "localhost"), new_dict, _dict.get("nick", "JAMTank"), _dict.get("tanque", "")) _id = self.servermodel.connect("error", self.__switch, 3) self.handlers["servermodel"].append(_id) _id = self.servermodel.connect("end-game", self.__end_multi_game) self.handlers["servermodel"].append(_id) if self.servermodel.server_run(): self.connectingplayers = ConnectingPlayers(self, _dict.get("nick", "JAMTank"), new_dict) _id = self.connectingplayers.connect("close", self.__switch, 3) self.handlers["connectingplayers"].append(_id) _id = self.connectingplayers.connect("accion", self.__accion_connecting_players_server) self.handlers["connectingplayers"].append(_id) _id = self.servermodel.connect("players", self.connectingplayers.update_playeres) self.handlers["servermodel"].append(_id) _id = self.servermodel.connect("play-enabled", self.connectingplayers.play_enabled) self.handlers["servermodel"].append(_id) self.servermodel.new_handler_registro(True) else: print "ERROR:", self.__accion_create_server elif accion == "salir": self.__switch(False, 1) def __end_multi_game(self, modelgame, _dict): #self.servermodel.juego.disconnect_by_func(self._statusgame.update) self.__play_music_intro() dialog = MultiDialogoEndGame(parent=self, _dict=_dict) dialog.run() dialog.destroy() self._statusgame.destroy() self.__switch(False, 1) def __end_single_game(self, modelgame, _dict): DICT["puntos"] += _dict[0].get("puntos", 0) DICT["disparos"] += _dict[0].get("disparos", 0) DICT["aciertos"] += _dict[0].get("aciertos", 0) keys = sorted(_dict.keys()) keys = keys[1:] vidas = False for k in keys: vidas = bool(_dict[k].get("vidas", 0)) if vidas: break if _dict[0].get("vidas", 0) and not vidas: dialog = SingleDialogoEndGame(self, "Completado Nivel %s" % self.singlemode.index, _dict[0], dict(DICT)) dialog.run() dialog.destroy() # Siguiente Nivel self.singlemode.index += 1 xid = self.get_property("window").xid self.singlemode.rungame(xid, self.gameres) self._statusgame.set_nivel(self.singlemode.index) self._statusgame.connect("volumen", self.__set_volumen, self.singlemode) self.singlemode.juego.connect("update", self._statusgame.update) else: dialog = SingleDialogoEndGame(self, "Game Over", _dict[0], dict(DICT)) dialog.run() dialog.destroy() # game over self.__play_music_intro() self._statusgame.destroy() self.__switch(False, 1) def __play_run(self, client_model): self.clientmodel.new_handler_registro(False) self.__kill_connectingplayers() xid = self.get_property("window").xid self.clientmodel.rungame(xid, self.gameres) self.clientmodel.juego._audio.set_volumen(self._efect_vol) vidas = int(int(self.clientmodel._dict["vidas"])) self._statusgame = MultiStatusGame(self, self.screen_wh, self.clientmodel.juego._ip, vidas) self._statusgame.connect("volumen", self.__set_volumen, self.clientmodel) self.clientmodel.juego.connect("update", self._statusgame.update) self.__play_music_game() def __accion_connecting_players_server(self, con_players, valor): if valor == "jugar": self.servermodel.new_handler_anuncio(False) self.servermodel.new_handler_registro(False) self.__kill_connectingplayers() xid = self.get_property("window").xid self.servermodel.rungame(xid, self.gameres) self.servermodel.juego._audio.set_volumen(self._efect_vol) vidas = int(int(self.servermodel._dict["vidas"])) self._statusgame = MultiStatusGame(self, self.screen_wh, self.servermodel.juego._ip, vidas) self._statusgame.connect("volumen", self.__set_volumen, self.servermodel) self.servermodel.juego.connect("update", self._statusgame.update) self.__play_music_game() elif valor == "cancelar": self.__switch(False, 3) def __accion_connecting_players_client(self, con_players, valor): if valor == "cancelar": self.__switch(False, 4) def __kill_client_model(self): if self.clientmodel: self.clientmodel.close_all_and_exit() for h in self.handlers.get("clientmodel", []): if self.clientmodel.handler_is_connected(h): self.clientmodel.handler_disconnect(h) for h in self.handlers.get("clientmodel", []): del(h) try: self.clientmodel.destroy() except: pass self.handlers["clientmodel"] = [] del(self.clientmodel) self.clientmodel = False def __kill_server_model(self): if self.servermodel: self.servermodel.close_all_and_exit() for h in self.handlers.get("servermodel", []): if self.servermodel.handler_is_connected(h): self.servermodel.handler_disconnect(h) for h in self.handlers.get("servermodel", []): del(h) try: self.servermodel.destroy() except: pass self.handlers["servermodel"] = [] del(self.servermodel) self.servermodel = False def __key_press_event(self, widget, event): if self.servermodel: self.servermodel.process_key_press(event) elif self.clientmodel: self.clientmodel.process_key_press(event) elif self.singlemode: self.singlemode.process_key_press(event) return False def __key_release_event(self, widget, event): if self.servermodel: self.servermodel.process_key_release(event) elif self.clientmodel: self.clientmodel.process_key_release(event) elif self.singlemode: self.singlemode.process_key_release(event) return False def __kill_create_mode(self): if self.createclientmode: for h in self.handlers.get("createclientmode", []): if self.createclientmode.handler_is_connected(h): self.createclientmode.handler_disconnect(h) for h in self.handlers.get("createclientmode", []): del(h) self.createclientmode.kill_all() try: self.createclientmode.destroy() except: pass self.handlers["createclientmode"] = [] del(self.createclientmode) self.createclientmode = False if self.createservermode: for h in self.handlers.get("createservermode", []): if self.createservermode.handler_is_connected(h): self.createservermode.handler_disconnect(h) for h in self.handlers.get("createservermode", []): del(h) try: self.createservermode.destroy() except: pass self.handlers["createservermode"] = [] del(self.createservermode) self.createservermode = False def __kill_select_mode(self): if self.selectmode: for h in self.handlers.get("selectmode", []): if self.selectmode.handler_is_connected(h): self.selectmode.handler_disconnect(h) for h in self.handlers.get("selectmode", []): del(h) try: self.selectmode.destroy() except: pass self.handlers["clientmodel"] = [] del(self.selectmode) self.selectmode = False def __kill_connectingplayers(self): if self.connectingplayers: for h in self.handlers.get("connectingplayers", []): if self.connectingplayers.handler_is_connected(h): self.connectingplayers.handler_disconnect(h) for h in self.handlers.get("connectingplayers", []): del(h) try: self.connectingplayers.destroy() except: pass self.handlers["clientmodel"] = [] del(self.connectingplayers) self.connectingplayers = False
def test_get_Player_2_character(): player2 = Player('2', 'Player2') character = player2.character assert (character == '2')
def test_get_Player_2_name(): player2 = Player('2', 'Player2') name = player2.name assert (name == 'Player2')
model = Model(inputs=input, outputs=output) print(model.summary()) memory = SequentialMemory(limit=50000, window_length=1) policy = LinearAnnealedPolicy(EpsGreedyQPolicy(), attr='eps', value_max=1., value_min=.1, value_test=.05, nb_steps=10000) # policy = BoltzmannQPolicy() dqn = DQNAgent(model=model, nb_actions=num_actions, memory=memory, nb_steps_warmup=100, target_model_update=1e-2, policy=policy) dqn.compile(Adam(lr=1e-3), metrics=['mae']) return dqn maps = [Basic()] player = Player() env = gym.make("geofriend2-v0", maps=[Basic()], player=player) dqn = build_model(env, env.action_space.n) # dqn.load_weights("saved-weights/1.264.h5f") dqn.test(env, nb_episodes=10, visualize=True, verbose=0)