def play_animation(self, animation_name, source, target_x, target_y): animation_params = {} animation_params['origin'] = (source.x, source.y) animation_params['target'] = (target_x, target_y) animation_params['target_angle'] = Utils.get_angle(source.x, source.y, target_x, target_y) GameState.add_animation(animation_name, animation_params)
def explosive_death(monster): # transform it into a nasty corpse! it doesn't block, can't be # attacked and doesn't move # TODO: String build this message more inteligently Utils.message('The ' + monster.name + ' EXPLODES!!!!! You gain ' + str(monster.fighter.xp) + ' experience points.', libtcod.orange) monster.char = ' ' monster.color = None monster.blocks = False monster.fighter = None monster.ai = None monster.name = '' GameState.schedule.release(monster) animation_params = {} animation_params['origin'] = (monster.x, monster.y) animation_params['target'] = (monster.x, monster.y) GameState.add_animation('Burst', animation_params) # TODO: Damage surrounding things..... ranged_component = Ranged(0, aoe=3) # TODO: BORKED!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! UI.target_mode(monster, target=monster.pos, ranged_componenet=ranged_component) monster.send_to_back()
def draw(self): Render.clear_layer(5) self.opened = True print self.width, self.height x = 5 y = 5 button_text = 'Close' button = Button(button_text, self.width / 2, self.height - 3, function=close_window, target=Render.layers['overlay_console']) dragging = False click_x = None mouse = Input.mouse while True: Input.update() Render.clear_layer(Render.layers['overlay_console']) Render.draw_rect(Render.layers['overlay_console'], x, y, self.width, self.height, frame=True, f_color=terminal.color_from_argb(255, 100, 100, 255), bk_color=terminal.color_from_argb(192, 32, 32, 128), title="POP_UP TEST!") Render.print_rect(Render.layers['overlay_console'], x + 2, y + 2, self.width - 4, self.height - 4, self.text) if mouse.lbutton and x <= mouse.cx <= x + self.width and (mouse.cy == y or dragging): if click_x is None: click_x = mouse.cx - x x = mouse.cx - click_x # (width / 2) y = mouse.cy dragging = True else: dragging = False click_x = None if button.draw(x, y) == 'close': self.opened = False Render.clear_layer(Render.layers['overlay_console']) return # libtcod.console_flush() # graphics.draw_image(x, y, enlarge=True) # graphics.draw_image(x + 1, y + 1, enlarge=True) # graphics.clear() # graphics.draw_font(0,0) GameState.render_ui()
def objects(): # libtcod.console_clear(consoles['entity_console']) Utils.clear_layer(layers['entity_console']) for object in Map.get_all_objects(): if object != GameState.get_player(): object.draw() GameState.get_player().draw()
def process_mouse_clicks(self, mouse): (map_x, map_y) = Utils.to_map_coordinates(mouse.cx, mouse.cy) if map_x is not None and map_y is not None: # walk to target tile if mouse.lbutton_pressed and GameState.continue_walking: GameState.continue_walking = False self.owner.clear_path() return 0 if mouse.lbutton_pressed and GameState.current_level.is_explored(map_x, map_y): self.owner.clear_path() GameState.continue_walking = self.owner.move_astar_xy(map_x, map_y, True) return self.end_turn(Constants.TURN_COST) if mouse.rbutton_pressed: GameState.continue_walking = False self.owner.clear_path() GameState.current_level.require_recompute() animation_params = {} animation_params['origin'] = (self.owner.x, self.owner.y) animation_params['target'] = (self.owner.x, self.owner.y) animation_params['target_angle'] = 0 GameState.add_animation('Teleport', animation_params) self.owner.x, self.owner.y = Utils.to_map_coordinates(mouse.cx, mouse.cy) animation_params = {} animation_params['origin'] = (self.owner.x, self.owner.y) animation_params['target'] = (self.owner.x, self.owner.y) animation_params['target_angle'] = 0 GameState.add_animation('Teleport', animation_params) return 1 return 0
def message(new_msg, color=None): import textwrap # split the message if necessary, among multiple lines if len(GameState.get_msg_queue()) == Constants.MSG_HEIGHT: GameState.del_msg(0) GameState.add_msg(new_msg) '''
class StateMachine(State, Receiver, InputHandler): __states = {} # _startState = StartState() # _creditState = CreditsState() # _gameState = GameState() # _charSelectState = CharSelectState() def __init__(self, type, aBatch, aBackground, aForeGround, aWindow, aMessenger): self._type = type self._startState = StartState(aBatch, aBackground, aForeGround, aWindow, type, aMessenger) self._creditState = CreditsState(aBatch, aBackground, aForeGround, aWindow, type, aMessenger) self._gameState = GameState(aBatch, aBackground, aForeGround, aWindow, type, aMessenger) self._charSelectState = CharSelectState(aBatch, aBackground, aForeGround, aWindow, type, aMessenger) self._charSettings = SettingsState(aBatch, aBackground, aForeGround, aWindow, type, aMessenger) self.__states = {self._startState, self._creditState, self._gameState, self._charSelectState, self._charSettings} def onEnter(self): pass def onExit(self): pass def onReceive(self, message): if message.msg == States.Start: self.setNotActive() self._startState.onEnter() elif message.msg == States.Credits: self.setNotActive() self._creditState.onEnter() elif message.msg == States.Game: self.setNotActive() self._gameState.onEnter() elif message.msg == States.CharSelect: self.setNotActive() self._charSelectState.onEnter() elif message.msg == States.Settings: self.setNotActive() self._charSettings.onEnter() def setNotActive(self): for state in self.__states: if state.isActive: state.onExit() state._active = False def handleKeyPress(self, symbol, modifiers): for state in self.__states: if state.isActive: state.handleKeyPress(symbol, modifiers) def handleKeyRelease(self, symbol, modifiers): for state in self.__states: if state.isActive: state.handleKeyRelease(symbol, modifiers)
def inspect_tile(x, y): global delay, map_old_x, map_old_y, new_animation if 0 < x < Constants.MAP_CONSOLE_WIDTH and 0 < y < Constants.MAP_CONSOLE_HEIGHT: # Mouse over Inspection camera_x, camera_y = GameState.get_camera() map_x, map_y = (camera_x + x, camera_y + y) if map_x is map_old_x and map_y is map_old_y: if time.time() - delay > Constants.INSPECTION_DELAY: # Post-Delay if GameState.current_level.map_array[map_x][map_y].explored: obj = [obj for obj in GameState.current_level.get_all_objects() if obj.x == map_x and obj.y == map_y] if len(obj) == 0: pass else: # print "animating..." #TODO: Re-implement Inspection (make a mode, not always on) #Animate.inspect_banner(x, y, obj[0].name, new_animation) new_animation = False else: # Pre-Delay pass else: # 88Render.clear_animations() new_animation = True map_old_x = map_x map_old_y = map_y delay = time.time()
def take_turn(self): # a basic monster takes its turn. If you can see it, it can see you monster = self.owner player = GameState.get_player() if GameState.current_level.is_visible(obj=monster): self.active = True GameState.continue_walking = False # move towards player if far away if self.active: dist = monster.distance_to(player) if dist > self.attack_range: # monster.move_astar(player) self.reload -= 1 # close enough, attack! (if the player is still alive.) elif player.fighter.hp > 0 and self.reload <= 0 and GameState.current_level.is_visible(obj=monster): """ DISABLE """ #Animate.follow_line(self.owner, player) self.play_animation('Shot', self.owner, player.x, player.y ) monster.fighter.attack(player) self.reload = 3 else: # Move away? self.reload -= 1 return Constants.TURN_COST
def take_turn(self): # a basic monster takes its turn. If you can see it, it can see you monster = self.owner player = GameState.get_player() if GameState.current_level.is_visible(obj=monster): if not self.active: self.active = True self.post_x = self.owner.x self.post_y = self.owner.y GameState.continue_walking = False if self.active: # move towards player if far away dist = monster.distance_to(player) print self.owner.name + " | " + str(dist) if dist <= 1.5 and player.fighter.hp > 0: monster.fighter.attack(player) if dist >= 6: monster.move_astar_xy(self.post_x, self.post_y) else: monster.move_astar(player) else: self.post_x = self.owner.x self.post_y = self.owner.y # self.owner.action_points += 100 # Schedule.add_to_pq((self.owner.action_points, self.owner)) return Constants.TURN_COST
def take_turn(self): # a basic monster takes its turn. If you can see it, it can see you monster = self.owner player = GameState.get_player() if GameState.current_level.is_visible(obj=monster): self.active = True GameState.continue_walking = False # move towards player if far away if self.active: dist = monster.distance_to(player) if dist > self.attack_range: # monster.move_astar(player) dest = Pathing.get_lowest_neighbor(monster.x, monster.y) # print "{0} moves to {1}.".format(monster.name, dest) monster.move_to(dest[0], dest[1]) self.reload -= 1 # close enough, attack! (if the player is still alive.) elif player.fighter.hp > 0 and self.reload <= 0 and GameState.current_level.is_visible(obj=monster): monster.fighter.attack(player) self.play_animation('Shot', self.owner, player.x, player.y) self.reload = 3 else: # Move away? self.reload -= 1 return Constants.TURN_COST
def take_turn(self): # a basic monster takes its turn. If you can see it, it can see you monster = self.owner player = GameState.get_player() if GameState.current_level.is_visible(obj=monster): self.active = True GameState.continue_walking = False if self.active: # move towards player if far away dist = GameState.current_level.map_array[monster.x][monster.y].distance_to_player # print self.owner.name + " | " + str(dist) if dist == 1 and player.fighter.hp > 0: # print "{0} fights Player.".format(monster.name) monster.fighter.attack(player) else: # print "{0} is at {1}".format(monster.name, (monster.x, monster.y)) dest = Pathing.get_lowest_neighbor(monster.x, monster.y) # print "{0} moves to {1}.".format(monster.name, dest) monster.move_to(dest[0], dest[1]) # monster.move_astar(player) # monster.move_dijkstra(player) # self.owner.action_points += 100 # Schedule.add_to_pq((self.owner.action_points, self.owner)) return Constants.TURN_COST
def executeTopAction(self, action): game = self._game gameState = GameState(game) game.processAction(action, True) atMaxDepth = (self._depth >= game._maxSimulationDepth) if game.deathTokens() == 0: score = -1000 elif not atMaxDepth: game.iteratePlayerIndex() score = game.simulateSingleTurn(self) else: score = game.score(self.initialPlayer) gameState.restoreGame() return score
def __init__(self, type, aBatch, aBackground, aForeGround, aWindow, aMessenger): self._type = type self._startState = StartState(aBatch, aBackground, aForeGround, aWindow, type, aMessenger) self._creditState = CreditsState(aBatch, aBackground, aForeGround, aWindow, type, aMessenger) self._gameState = GameState(aBatch, aBackground, aForeGround, aWindow, type, aMessenger) self._charSelectState = CharSelectState(aBatch, aBackground, aForeGround, aWindow, type, aMessenger) self._charSettings = SettingsState(aBatch, aBackground, aForeGround, aWindow, type, aMessenger) self.__states = {self._startState, self._creditState, self._gameState, self._charSelectState, self._charSettings}
def draw_stat_bars(): pos = Pos(Constants.MAP_CONSOLE_WIDTH + 4, 35) # SHOW PLAYER STAT BARS draw_box_bar(pos.x, pos.y, 14, '', GameState.get_player().fighter.hp, GameState.get_player().fighter.base_max_hp, Color("178, 0, 45"), Color("64, 0, 16"), layers['side_panel_console']) draw_box_bar(pos.x, pos.y + 1, 14, '', GameState.get_player().fighter.sp, GameState.get_player().fighter.base_max_sp, Color("0, 30, 255"), Color("0, 10, 64"), layers['side_panel_console']) draw_box_bar(pos.x, pos.y + 2, 14, '', GameState.get_player().fighter.xp, 1000, # TODO: will be NEXT_LVL_XP Color("255, 255, 0"), Color("65, 65, 0"), layers['side_panel_console']) # RENDER MONSTER HEALTH BARS temp_y = 3 for object in GameState.get_visible_objects(): if object.fighter and (object is not GameState.get_player()): # and Fov.is_visible(obj=object) if temp_y < 17: # TODO: Make constant to scale UI draw_box_bar(Constants.MAP_CONSOLE_WIDTH + 1, temp_y, 17, object.name, object.fighter.hp, object.fighter.max_hp, Color("0, 255, 0"), Color("0, 64, 0"), layers['side_panel_console']) temp_y += 2
def Reveal(): for item in Inventory.GetItems(1): if item.grade > 0 and item.option1 == 0 and GameState.IsInGame(): oPacket = Packet.COutPacket(revealHeader) oPacket.Encode4(int(time.monotonic() * 1000)) #time oPacket.Encode2(0x007F) oPacket.Encode2(item.pos) Packet.SendPacket(oPacket) time.sleep(1)
def playerVsMinMaxLocalSearch(self): """ Permainan Mode 2: Player vs BOT Minimax Local Search """ terminalState = False totalTime = 0 while not (terminalState): self.printInfo() # Giliran Player BOT Minimax Local Search if (self.currentPlayer.noPlayer != self.hplayer): print("PLAYER " + str(self.currentPlayer.noPlayer) + " MINIMAX LOCAL SEARCH TURN!") self.currentPlayer.printAllPion() # Minimax Local Search process for the BOT currentState = GameState.GameState(self.board, self.currentPlayer, self.oppositePlayer) beforeProcess = time.time() minimaxState, _eval = Minimax.minimaxLocalSearch( currentState, 3, time.time() + self.tlimit, -math.inf, math.inf, self.currentPlayer.noPlayer) self.assignState(minimaxState) deltaTime = time.time() - beforeProcess totalTime += deltaTime print(f"Execution time = {deltaTime} seconds") # Giliran Player Manusia else: print("PLAYER " + str(self.currentPlayer.noPlayer) + " TURN!") self.currentPlayer.printAllPion() chosenID = int( input("Pilih Pion ID mana yang ingin dimainkan : ")) if (chosenID == 999): self.saveGame() possible_moves = self.currentPlayer.listAllPossibleMove( chosenID, self.board) for i in range(len(possible_moves)): print(str(i + 1) + ". ", end="") possible_moves[i].printPosisi() chosenMove = int( input( "Pilih move yang diinginkan dengan memasukkan nomor : " )) self.currentPlayer.movePion(chosenID, possible_moves[chosenMove - 1], self.board) # Cek apakah sekarang merupakan kondisi terminal if (self.board.checkTerminalState(self.currentPlayer.noPlayer)): terminalState = True else: self.nextTurn() self.printInfo() print("Player " + str(self.currentPlayer.noPlayer) + " win the game!") print(totalTime)
def equip(self): # if the slot is already being used, dequip whatever is there first old_equipment = GameState.get_equipped_in_slot(self.slot) if old_equipment is not None: old_equipment.dequip() # equip object and show a message about it self.is_equipped = True Utils.message('Equipped ' + self.owner.name + ' on ' + self.slot + '.', libtcod.light_green)
def render_messages(): Render.clear_layer(layers['messages']) y = 3 + Constants.MAP_CONSOLE_HEIGHT for line in GameState.get_msg_queue(): if y < Constants.SCREEN_HEIGHT - 1: line_height = 1 Render.print_rect(layers['messages'], Constants.MSG_X, y, Constants.MSG_WIDTH, line_height, line) y += line_height
def FollowLead(): if Party.IsInParty() and Party.GetPartyBossID() != Character.GetID(): if FindClientID(Party.GetPartyBossID()) is not None: LeaderClient = Terminal.GetLocalUser( FindClientID(Party.GetPartyBossID())) if Field.GetID() == LeaderClient.mapid and GameState.GetChannel( ) != LeaderClient.channel: print("Switch to leader channel") Terminal.ChangeChannel(LeaderClient.channel)
def depth_first_search(self): self.number_of_searches = 0 cat_pos = self.cat.init_pos count = 0 mouse_pos = self.mouse_path[count] dfs_stack = [ GameState.BlindSearchGameState(self.mouse_path[count], cat_pos, None, 0) ] cat_path = [cat_pos] visited_state = [] while len(dfs_stack) > 0: self.number_of_searches += 1 current_state = dfs_stack.pop(len(dfs_stack) - 1) count = current_state.move_count visited_state.append(current_state) possible_moves = self.cat_manager.get_all_possible_moves( current_state.cat) # print(self.number_of_searches) if len(possible_moves) > 0 and 0 <= count < len( self.mouse_path) - 1: game_state = None count += 1 mouse_pos = self.mouse_path[count] for cat_pos in possible_moves: game_state = GameState.BlindSearchGameState( mouse_pos, cat_pos, current_state, count) if game_state not in visited_state: dfs_stack.append(game_state) if current_state.cat == current_state.mouse_pos and not current_state.mouse_pos == self.mouse_path[ len(self.mouse_path) - 1]: self.game_map.game_over = True break elif self.number_of_searches >= MAX_BLIND_SEARCHES and MAX_BLIND_SEARCHES != -1 and not current_state.cat == current_state.mouse_pos and current_state.mouse_pos == self.mouse_path[ len(self.mouse_path) - 1]: break while not current_state.parent_state == None: cat_path.insert(1, current_state.cat) current_state = current_state.parent_state return cat_path
def clicked(self, gameState): #If a piece was already selected, #it will replace its own piece and #remove the other piece if self.selected: self.newPiece(self.incoming.piece, self.incoming.isWhite) gameState[self.incoming.x][self.incoming.y].newPiece(" ", True) for x in range(8): for y in range(8): gameState[x][y].deselect() gs.gameChecks(gameState) #Otherwise, it will select specific tiles #depending on what piece it is else: #First it deselects every tile for x in range(8): for y in range(8): gameState[x][y].deselect() #Then it will check what piece it is and act accordingly #I moved all these methods down to make it more readable if self.piece == "Rook": tileList = pl.rookCheck(self, gameState) elif self.piece == "Knight": tileList = pl.knightCheck(self, gameState) elif self.piece == "Pawn": tileList = pl.pawnCheck(self, gameState) elif self.piece == "Bishop": tileList = pl.bishopCheck(self, gameState) elif self.piece == "King": tileList = pl.kingCheck(self, gameState) elif self.piece == "Queen": tileList = pl.bishopCheck(self, gameState) secondTileList = pl.rookCheck(self, gameState) for i in range(len(secondTileList)): tileList.append(secondTileList[i]) try: for i in range(len(tileList)): tileList[i].select(self) except: return
def move_player(self, player, board): game_state = GameState.GameState(board, self) uid = player.uid move_enum = player.get_next_move(uid, game_state) try: self.move_map[move_enum](player, board) except: self.move_map[Direction(move_enum)](player, board) board.set_claim(player.x_pos, player.y_pos, player) return (player.x_pos, player.y_pos)
def __init__(self, rows, cols): self.rows = rows self.cols = cols self.state = GameState.GameState(rows, cols) self.board = self.state.board self.master = Tk() self.master.title("Othello White's Turn") self.frame = Frame(self.master) self.frame.pack(fill=BOTH, expand=YES) self.make_canvas()
def newGame( self, numPlayers ): print 'New Game of', numPlayers, 'players' self.gameState = GameState() self.gameState.init_new(numPlayers, now()) self.state = 'REGISTRATION' self.findXMLFileName() self.mainloop(numPlayers)
def __init__(self, info_port="5557", action_port="5558"): self.id = random.randrange(0, 1000) self.state = GameState.GameState() self.player = GamePlayer.GamePlayer(self.id) self.info_port = info_port self.action_port = action_port self.context = zmq.Context() self._init_action_socket() self.join_server() self._init_info_socket()
def four_split(self, other_player, turn): new_left, new_right = 2, 2 player_self_new = Player(self.get_pid(), new_left, new_right) if self.pid == 1: next_state = GameState(2, player_self_new, other_player) elif self.pid == 2: next_state = GameState(2, other_player, player_self_new) next_state.set_turn(turn) # set new turn to the previous states turn next_state.change_turn( ) # since this method doesnt use the gen_new_state method it must call this print("\nPlayer " + str(self.get_pid()) + ": FOUR SPLIT") return next_state
def alphaBetaAI(self, gamestate, alpha, beta, depth): if self.forceAMove == True: sys.exit() if self.outOfTime == True: quit() if gamestate.getTotalChips() > 4: gamestate.flipTiles() gamestate.calculateScore() validMoves = gamestate.getValidMoves() if depth == 0: return self.mobilityHeuristic(gamestate), "Null" #return self.heuristic(gamestate), "Null" if validMoves == []: if self.possibleEndGameAB == True: return self.heuristic(gamestate), "Null" else: cmpVal, cmpMove = self.alphaBetaOpponent( GameState.GameState(gamestate, 'null', self.aiColor, self.playerColor), alpha, beta, depth - 1) return cmpVal, cmpMove self.possibleEndGameAB = False bestVal = float("-inf") bestMove = validMoves[0] for move in validMoves: cmpVal, cmpMove = self.alphaBetaOpponent( GameState.GameState(gamestate, move, self.aiColor, self.playerColor), alpha, beta, depth - 1) if cmpVal > bestVal: bestVal = cmpVal bestMove = move if beta != 'null': if cmpVal >= beta: return bestVal, bestMove if alpha == 'null' or cmpVal > alpha: alpha = cmpVal return bestVal, bestMove
def __init__(self, map): pygame.init() self.worldSize = Vector2(WORLD_MAX_X, WORLD_MAX_Y) self._cellSize = Vector2(CELL_SIZE_X, CELL_SIZE_Y) _windowSize = self.worldSize.elementwise() * self._cellSize self._window = pygame.display.set_mode( (int(_windowSize.x), int(_windowSize.y))) self._gameState = GameState(map.load_map()) self._clock = pygame.time.Clock() self._running = True self._moveCommand = Vector2(0, 0)
def test_nextRound(self): gsTemp = gs.GameState(10) self.assertEqual(gsTemp.round, 0) self.assertEqual(len(gsTemp.roundList), 1) gsTemp.nextRound() self.assertEqual(gsTemp.round, 1) self.assertEqual(len(gsTemp.roundList), 2) for i in range(5): gsTemp.nextRound() self.assertEqual(gsTemp.round, 4) self.assertEqual(len(gsTemp.roundList), 5)
def render_messages(): Utils.clear_layer(layers['messages']) y = 3 + Constants.MAP_CONSOLE_HEIGHT for (line, color) in GameState.get_msg_queue(): if y < Constants.SCREEN_HEIGHT - 1: set_foreground(layers['messages'], color) # line_height = libtcod.console_get_height_rect(consoles['panel_console'], 0, 0, Constants.MSG_WIDTH, Constants.PANEL_HEIGHT - 3, line) line_height = 1 print_rect(layers['messages'], Constants.MSG_X, y, Constants.MSG_WIDTH, line_height, line) y += line_height
def drop(self): # add to the map and remove from the player's inventory. also, place it at the player's coordinates GameState.current_level.get_all_objects().append(self.owner) GameState.inventory.remove(self.owner) player = GameState.get_player() self.owner.x = player.x self.owner.y = player.y # special case: if the object has the Equipment component, dequip it before dropping if self.owner.equipment: self.owner.equipment.dequip() Utils.message('You dropped a ' + self.owner.name + '.', libtcod.yellow)
def follow_line(source, target, projectile='-', end_tile='*', color=libtcod.yellow): if Constants.ANIMATE_ON: line = Utils.get_line((source.x, source.y), (target.x, target.y)) for loc in line: Render.clear_layer(Render.layers['animation_console']) map_x, map_y = loc GameState.render_all() x, y = Utils.to_camera_coordinates(map_x, map_y) if (x, y) == line[-1]: Render.draw_char(Render.layers['animation_console'], x, y, end_tile, color) else: Render.draw_char(Render.layers['animation_console'], x, y, projectile, color) terminal.refresh() # time.sleep(0.01325) # 0.01325 Render.clear_layer(Render.layers['animation_console'])
def pick_up(self): # add to the player's inventory and remove from the map if len(GameState.inventory) >= 26: Utils.message('Your inventory is full, cannot pick up ' + self.owner.name + '.', libtcod.red) else: GameState.inventory.append(self.owner) GameState.current_level.get_all_objects().remove(self.owner) Utils.message('You picked up a ' + self.owner.name + '!', libtcod.green) # special case: automatically equip, if the corresponding equipment slot is unused equipment = self.owner.equipment if equipment and GameState.get_equipped_in_slot(equipment.slot) is None: equipment.equip()
def getGameState(self): charRects = [] for charID, character in self.characters.items(): charRects.append( (character.player.uid, character.rect, character.health)) projectileRects = [] for projectileID, projectile in self.projectiles.items(): projectileRects.append( (projectile.character.player.uid, projectile.rect)) return GameState(charRects, projectileRects)
def __LogGM(self): GMLogs = self.__ReadGMLogs() world = Terminal.GetComboBox('LoginWorld') worldStatus = ast.literal_eval(GMLogs)['worlds'][self.__GetWorld( world)]['status'] worldsToCheck = self.__ReadWorldsToLogOut()[self.__GetWorld(world)] if worldStatus == 'online' and bool(worldsToCheck): Terminal.SetCheckBox('Auto Login', False) if GameState.IsInGame(): Terminal.Logout() if worldStatus == 'offline' and bool(worldsToCheck): Terminal.SetCheckBox("Auto Login", True)
def take_damage(self, damage): # apply damage if possible player = GameState.get_player() if damage > 0: self.hp -= damage # check for death. if there's a death function, call it if self.hp <= 0: function = self.death_function if self.owner != player: # yield experience to the player player.fighter.xp += self.xp if function is not None: function(self.owner)
def draw(): clear_canvas() global showfont sc = GameState.getlastscore() #print(sc) endbackground.draw(400,300,800,600) showfont.draw(400, 495, str(sc), (0, 56, 174)) if int(makingtime - time.time()) % 2 == 0: pressrimage.draw(700,350) update_canvas() pass
def aiforceMove(self): print 'forcing move' self.forceAMove = True self.timerStop = True validMoves = self.gamestates[self.currentState].getValidMoves() move = validMoves[0] print "AI's move is: " + move raw_input("Press Enter to confirm this move and view new board layout") self.gamestates.append( GameState.GameState(self.gamestates[self.currentState], move, self.aiColor, self.playerColor)) self.currentState += 1 self.aiMadeMove = True
def initialize(): global fov_recompute, fov_map, player # unexplored areas start black (which is the default background color) # from Render import clear_map # clear_map() map = Map.current_map() player = GameState.get_player() require_recompute() fov_map = libtcod.map_new(Constants.MAP_WIDTH, Constants.MAP_HEIGHT) for y in range(Constants.MAP_HEIGHT): for x in range(Constants.MAP_WIDTH): fov_change(x, y, map[x][y].block_sight, map[x][y].blocked)
def __LogClient(self): if GameState.IsInGame(): is_logged = self.__Items() if not is_logged: print('TMRemote> Unable to log items: {}'.format( datetime.datetime.now())) else: is_logged = self.__Disconnect() if not is_logged: print('TMRemote> Unable to log disconnect: {}'.format( datetime.datetime.now())) self.__LogGM()
def chess_b_gi(): p.init() screen = p.display.set_mode((width, height)) clock = p.time.Clock() screen.fill(p.Color("white")) gs = GameState.GameState() # TODO ??????????????? load_images() draw_game_state(screen, gs) running = True sqSelected = () playerClicks = [] while running: for e in p.event.get(): if e.type == p.QUIT: running = False elif e.type == p.MOUSEBUTTONDOWN: location = p.mouse.get_pos() col = location[0] // square_size row = location[1] // square_size if sqSelected == (row, col): sqSelected = () playerClicks = [] else: sqSelected = (row, col) playerClicks.append(sqSelected) if len(playerClicks) == 2: move = GameState.Move(playerClicks[0], playerClicks[1], gs.board) print(move.getChessNotation()) gs.makeMove(move) sqSelected = () playerClicks = [] draw_game_state(screen, gs) clock.tick(MAX_FPS) p.display.flip()
def __init__(self, **kwargs): super().__init__(**kwargs) self.state_handlers = { STATE_PLAYING: PlayingState(), STATE_FALLING: FallingState(), STATE_GAME_OVER: GameOverState() } # set framewor dependent drawing functions self.state_handlers[STATE_GAME_OVER].set_draw(self.draw_game_over) self.state_handlers[STATE_PLAYING].set_draw(self.draw_game) self.state_handlers[STATE_FALLING].set_draw(self.draw_game) self.game_state = GameState( state_handlers=self.state_handlers, current_handler=self.state_handlers[STATE_PLAYING] #, current_handler=self.state_handlers[STATE_GAME_OVER] , occupied_positions={}, running=True, current_shape=new_shape(), next_shape=new_shape(), fall_time=0, fall_speed=INITIAL_FALL_SPEED) self.game_state = self.game_state.current_handler.enter( self.game_state) self.keyboard = Window.request_keyboard(self.on_keyboard_closed, self) self.keyboard.bind(on_key_down=self.on_key_down) self.keyboard.bind(on_key_up=self.on_key_up) self.translation_tab = { 32: EVENT_FALL, 276: EVENT_LEFT, 275: EVENT_RIGHT, 273: EVENT_ROT_LEFT, 274: EVENT_ROT_RIGHT } self.keys_pressed = set() Window.clearcolor = list(map(lambda c: c / 255, BACKGROUND_COLOR)) + [1] if Window.size[0] * 0.5 / GRID_WIDTH > Window.size[ 1] * 0.7 / GRID_HEIGHT: self.block_size = Window.size[1] * 0.7 / GRID_HEIGHT else: self.block_size = Window.size[0] * 0.5 / GRID_WIDTH self.grid_size = (self.block_size * GRID_WIDTH, self.block_size * GRID_HEIGHT) self.grid_pos = (Window.size[0] * 0.5 - self.grid_size[0] * 0.5, Window.size[1] * 0.5 - self.grid_size[1] * 0.5) Clock.schedule_interval(self.game_loop, 1 / 30)
def EnterPortal(name): time.sleep(0.5) portal = Field.FindPortal(name) pos = Character.GetPos() if pos.x != portal.x: print("Portal " + str(name) + " found, teleporting...") Character.Teleport(portal.x, portal.y - 20) time.sleep(0.5) print("Teleported to portal: " + str(name) + "...") print("Trying to enter portal...") while GameState.IsInGame() and Character.GetPos().x == portal.x: if Field.GetID() == 610050000: break Character.EnterPortal() time.sleep(0.5)
def test_look_at(): print("\ntest 1: trying to look at mail while in First Floor Foyer \n") game = GameState() action = Input_Parser() action.obj = 'mail' game._look_at(action) print("\ntest 1 complete") print("\ntest 2: trying to look at mailbox while in First Floor Foyer") print("should print same response as test 1\n") action.obj = 'mailbox' game._look_at(action) print("\ntest 2 complete") print("\ntest 3: trying to look at keys while in First Floor Foyer") action.obj = 'keys' game._look_at(action) print("\ntest 3 complete") print("\ntest 4: trying to look at key peg while in First Floor Foyer") print("should print same response as test 3\n") action.obj = 'key peg' game._look_at(action) print("\ntest 4 complete")
def render_common(): import Input pos = Pos(Constants.MAP_CONSOLE_WIDTH, 0) set_foreground(layers['side_panel_console'], libtcod.Color(0, 70, 140)) """ LEVEL NUMBER """ print_rect(layers['side_panel_console'], pos.x + 1, pos.y + 1, 17, 1, "Level 1".center(17, ' ')) """ MOUSE X / Y """ print_rect( layers['side_panel_console'], pos.x + 9, pos.y + 18, 17, 2, "X: " + str(Input.mouse.cx) + " \nY: " + str(Input.mouse.cy) + " ") """ STATS """ set_foreground(layers['panel_console'], libtcod.Color(175, 175, 255)) player = GameState.get_player() print_line(layers['side_panel_console'], Constants.MAP_CONSOLE_WIDTH + 5, 18, str(player.fighter.base_str).rjust(3)) print_line(layers['side_panel_console'], Constants.MAP_CONSOLE_WIDTH + 5, 19, str(player.fighter.base_def).rjust(3)) print_line(layers['side_panel_console'], Constants.MAP_CONSOLE_WIDTH + 5, 20, str(player.fighter.base_agl).rjust(3)) print_line(layers['side_panel_console'], Constants.MAP_CONSOLE_WIDTH + 5, 21, str(player.fighter.base_stm).rjust(3)) print_line(layers['side_panel_console'], Constants.MAP_CONSOLE_WIDTH + 5, 22, str(player.fighter.base_skl).rjust(3)) print_line(layers['side_panel_console'], Constants.MAP_CONSOLE_WIDTH + 5, 23, str(player.fighter.base_int).rjust(3)) """ CONTROLS """ print_line(layers['side_panel_console'], 59, 39, "Move: NUMPAD") print_line(layers['side_panel_console'], 59, 40, "Fire: F") print_line(layers['side_panel_console'], 59, 41, "Pickup: G") print_line(layers['side_panel_console'], 59, 42, "Pop-Up Test: B") print_line(layers['side_panel_console'], 59, 43, "Decend: <") print_line(layers['side_panel_console'], 59, 44, "DEBUG: X") """ DUNGEON NAME """ pos = Pos(0, Constants.MAP_CONSOLE_HEIGHT) print_rect(layers['panel_console'], pos.x + 1, pos.y + 1, Constants.SCREEN_WIDTH - 19, 1, GameState.dungeon_name.center(57, ' '))
def Stamp(slot): silverStamp = 2049501 item = Inventory.GetItem(1, slot) stamp = Inventory.FindItemByID(silverStamp) while item.grade > 0 and item.option1 > 0 and item.option3==0 \ and stamp.valid and GameState.IsInGame(): oPacket = Packet.COutPacket(stampHeader) oPacket.Encode4(int(time.monotonic() * 1000)) #time oPacket.Encode2(stamp.pos) oPacket.Encode2(slot) Packet.SendPacket(oPacket) time.sleep(1) item = Inventory.GetItem(1, slot) stamp = Inventory.FindItemByID(silverStamp)
def render_common(): import Input pos = Pos(Constants.MAP_CONSOLE_WIDTH, 0) set_foreground(layers['side_panel_console'], libtcod.Color(0, 70, 140)) """ LEVEL NUMBER """ print_rect(layers['side_panel_console'], pos.x + 1, pos.y + 1, 17, 1, "Level 1".center(17, ' ')) """ MOUSE X / Y """ print_rect(layers['side_panel_console'], pos.x + 9, pos.y + 18, 17, 2, "X: " + str(Input.mouse.cx) + " \nY: " + str(Input.mouse.cy) + " ") """ STATS """ set_foreground(layers['panel_console'], libtcod.Color(175, 175, 255)) player = GameState.get_player() print_line(layers['side_panel_console'], Constants.MAP_CONSOLE_WIDTH + 5, 18, str(player.fighter.base_str).rjust(3)) print_line(layers['side_panel_console'], Constants.MAP_CONSOLE_WIDTH + 5, 19, str(player.fighter.base_def).rjust(3)) print_line(layers['side_panel_console'], Constants.MAP_CONSOLE_WIDTH + 5, 20, str(player.fighter.base_agl).rjust(3)) print_line(layers['side_panel_console'], Constants.MAP_CONSOLE_WIDTH + 5, 21, str(player.fighter.base_stm).rjust(3)) print_line(layers['side_panel_console'], Constants.MAP_CONSOLE_WIDTH + 5, 22, str(player.fighter.base_skl).rjust(3)) print_line(layers['side_panel_console'], Constants.MAP_CONSOLE_WIDTH + 5, 23, str(player.fighter.base_int).rjust(3)) """ CONTROLS """ print_line(layers['side_panel_console'], 59, 39, "Move: NUMPAD") print_line(layers['side_panel_console'], 59, 40, "Fire: F") print_line(layers['side_panel_console'], 59, 41, "Pickup: G") print_line(layers['side_panel_console'], 59, 42, "Pop-Up Test: B") print_line(layers['side_panel_console'], 59, 43, "Decend: <") print_line(layers['side_panel_console'], 59, 44, "DEBUG: X") """ DUNGEON NAME """ pos = Pos(0, Constants.MAP_CONSOLE_HEIGHT) print_rect(layers['panel_console'], pos.x + 1, pos.y + 1, Constants.SCREEN_WIDTH - 19, 1, GameState.dungeon_name.center(57, ' '))
def take_turn(self, fov): if self.owner.CT >= 100: self.owner.CT = 0 # a basic monster takes its turn. If you can see it, it can see you monster = self.owner player = GameState.get_player() if GameState.current_level.is_visible(obj=monster): # TO-DO: Randomize location of spawn # Randomize how often spawn occurs # move towards player if far away chance_to_spawn = libtcod.random_get_int(0, 0, 10) if chance_to_spawn >= 7: # self.split() pass else: if monster.distance_to(player) >= 2: monster.move_astar(player) # close enough, attack! (if the player is 8still alive.) elif player.fighter.hp > 0: monster.fighter.attack(player) else: return False
# # # Unit Test # Description: Test's that given a game state, that it expands accordingly, and evaluates that state correctly. # # board = [[Location((col, row)) for row in xrange(0, BOARD_LENGTH)] for col in xrange(0, BOARD_LENGTH)] p1Inventory = Inventory(PLAYER_ONE, [], [], 0) p2Inventory = Inventory(PLAYER_TWO, [], [], 0) neutralInventory = Inventory(NEUTRAL, [], [], 0) putFood(neutralInventory) putOurInventory(p1Inventory) putTheirInventory(p2Inventory) state = GameState(board, [p1Inventory, p2Inventory, neutralInventory], PLAY_PHASE, PLAYER_ONE) expectedState = state.fastclone() expectedState.inventories[PLAYER_TWO].ants = [] ourAI = AIPlayer(PLAYER_ONE) move = Move(MOVE_ANT,[(0,6)], None) retrievedState = ourAI.expandNode(state, move) if equalStates(retrievedState, expectedState): score = ourAI.evaluateState(retrievedState) if score == 1.0: print "Unit Test #1 Passed" else: print "UNIT TEST #1 FAILED"
for s in settlements: self.board.setSettlement(s.adjHex1, s.adjHex2, s.adjHex3, s.isCity, fill=self.playerColors[s.owner]) for i in range(nPlayers): if self.hand_text[i]: self.board.delete(self.hand_text[i]) p = game.players[i] text = "player Id: {0}\nWOOL: {1}\nBRICK: {2}\nORE: {3}\nLUMBER: {4}\nGRAIN: {5}\nVictory Point: {6}\nPlayer Color: {7}".format(p.playerId, p.resources[ResourceType.WOOL], p.resources[ResourceType.BRICK], p.resources[ResourceType.ORE], p.resources[ResourceType.LUMBER], p.resources[ResourceType.GRAIN], p.vp(game), self.playerColors[i]) if game.turn.currentPlayer == p.playerId: self.hand_text[i] = self.board.create_text(self.hand_positions[i], text=text, font = tkFont.Font(weight = 'bold')) else: self.hand_text[i] = self.board.create_text(self.hand_positions[i], text=text, fill = "#112233") if self.explain_text: self.board.delete(self.explain_text) if explain: if isinstance(explain, tuple): explain = "Roll: {0}, {1}".format(*explain) else: explain = str(explain) self.explain_text = self.board.create_text(self.explain_position, text=explain, anchor=NW) if __name__ == "__main__": args = map(int, sys.argv[1:]) if skip_to_good_part: View(skipToGoodPart(*args)) else: View(GameState.newGame(*args))
def take_turn(self): global vCount GameState.render_all() mouse = Input.mouse while True: # print "Waiting for input" """ On player turn this loops continuasouly waiting for user input """ Input.update() key = Input.key GameState.render_ui() """ Check mouse status """ mouse_click_value = self.process_mouse_clicks(mouse) mouse_hover_value = self.process_mouse_hover(mouse) if mouse_click_value > 0: return self.end_turn(mouse_click_value) if mouse_hover_value > 0: return self.end_turn(mouse_hover_value) """ Auto-Walking """ # TODO: Make autowalk pathing calculate paths based on NO monsters. Otherwise you can tell when paths are blocked. Stop when encounter... if GameState.continue_walking: self.owner.walk_path() # print "Auto-Walking" return self.end_turn(Constants.TURN_COST) elif not GameState.continue_walking: self.owner.clear_path() """ Basic User Input """ # TODO: Make movement cost relative to terrain. (add terrain cost to TILE) WATER / TAR / OIL / SAND = Slower, Road / Trail = Fsater # TODO: Make turns not pass as you bumb into walls. # TODO: Add 'Auto-Explore' --- Search for Not self.Explored, path to it as if you right clicked. if key == terminal.TK_KP_8 or key == terminal.TK_UP: GameState.player_move_or_interact(0, -1) return self.end_turn(Constants.TURN_COST) elif key == terminal.TK_KP_2 or key == terminal.TK_DOWN: GameState.player_move_or_interact(0, 1) return self.end_turn(Constants.TURN_COST) elif key == terminal.TK_KP_4 or key == terminal.TK_LEFT: GameState.player_move_or_interact(-1, 0) return self.end_turn(Constants.TURN_COST) elif key == terminal.TK_KP_6 or key == terminal.TK_RIGHT: GameState.player_move_or_interact(1, 0) return self.end_turn(Constants.TURN_COST) elif key == terminal.TK_KP_7: # or (terminal.TK_LEFT and terminal.TK_UP): GameState.player_move_or_interact(-1, -1) return self.end_turn(Constants.TURN_COST) elif key == terminal.TK_KP_9: GameState.player_move_or_interact(1, -1) return self.end_turn(Constants.TURN_COST) elif key == terminal.TK_KP_1: GameState.player_move_or_interact(-1, 1) return self.end_turn(Constants.TURN_COST) elif key == terminal.TK_KP_3: GameState.player_move_or_interact(1, 1) return self.end_turn(Constants.TURN_COST) elif key == terminal.TK_KP_5: return self.end_turn(Constants.TURN_COST) elif key == terminal.TK_X: GameState.current_level.require_recompute() Constants.DEBUG = not Constants.DEBUG GameState.render_all() elif key == terminal.TK_G: # pick up an item for object in GameState.current_level.get_all_objects(): # look for an item in the player's tile if object.x == self.owner.x and object.y == self.owner.y and object.item: object.item.pick_up() break elif key == terminal.TK_F: for obj in GameState.get_all_equipped(self.owner): if obj.owner.ranged: outcome = obj.owner.ranged.fire() if outcome == 'cancelled': return 0 else: return self.end_turn(Constants.TURN_COST) elif key == terminal.TK_B: title = "Beastiary" text = '\n\nDrag Header to move window\n\n' pal = UI.Palette(width=20, height=20, title='Title', text=text) pal.draw() elif key == terminal.TK_COMMA and terminal.check(terminal.TK_SHIFT): # go down stairs, if the player is on them stairs = GameState.current_level.get_stairs() if stairs.x == self.owner.x and stairs.y == self.owner.y: GameState.next_level() return 1 elif key == terminal.TK_ESCAPE: GameState.save_game() UI.display_mainMenu() elif key == terminal.TK_L: GameState.load_game() return 1 elif key == terminal.TK_T: GameState.add_animation('FadeText', {'origin': (self.owner.x, self.owner.y), 'target': (self.owner.x, self.owner.y-1)}) elif key == terminal.TK_O: print GameState.current_level.fov_map elif key == terminal.TK_RBRACKET: equipped_ranged = [equip.name for equip in GameState.inventory if equip.equipment.is_equipped and equip.ranged] if equipped_ranged[0] == "pistol": new_weapon = [equip for equip in GameState.inventory if equip.name == 'laser'] new_weapon[0].equipment.equip() elif equipped_ranged[0] == "laser": new_weapon = [equip for equip in GameState.inventory if equip.name == 'rpg'] new_weapon[0].equipment.equip() elif equipped_ranged[0] == "rpg": new_weapon = [equip for equip in GameState.inventory if equip.name == 'ice wand'] new_weapon[0].equipment.equip() elif equipped_ranged[0] == "ice wand": new_weapon = [equip for equip in GameState.inventory if equip.name == 'pistol'] new_weapon[0].equipment.equip() elif key == terminal.TK_LBRACKET: pass '''
def max_hp(self): # return actual max_hp, by summing up the bonuses from all equipped items bonus = sum(equipment.max_hp_bonus for equipment in GameState.get_all_equipped(self.owner)) return self.base_max_hp + bonus