def startGame(self): if not self.gameIsRunning: for i, btn in enumerate(self.buttons): btn.clicked.connect( getattr(self, "button" + str(i) + "pressed")) self.gameIsRunning = True self.playerOne = -1 self.playerTwo = -2 self.game = GameLogic(self.playerOne, self.playerTwo)
def initialize_game_variables(self, game_mode): # Initialize the game board and the GameLogic object # Who is yellow? Who red? colour_p1 = 2 colour_p2 = 1 if game_mode == "TeachAgents" or game_mode=="Singleplayer": # Player 1 self.p1 = hp.HumanPlayer(colour_p1) self.p2 = ap.AgentPlayer(colour_p2, "qlearner", self.connect_mode, game_mode) self.p1.set_opponent(self.p2) self.trace = Trace.Trace(self.p2, self.p1) self.p1.set_trace(self.trace) self.p2.set_trace(self.trace) elif game_mode == "Multiplayer": self.p1 = hp.HumanPlayer(colour_p1) self.p2 = hp.HumanPlayer(colour_p2) elif game_mode == "Options": pass elif game_mode == "AgentsLearn": self.p1 = ap.AgentPlayer(colour_p1, "qlearner", self.connect_mode, "AgentsLearn") self.p2 = ap.AgentPlayer(colour_p2, "qlearner", self.connect_mode, "AgentsLearn") self.trace = Trace.Trace(self.p2, self.p1) self.p1.set_trace(self.trace) self.p2.set_trace(self.trace) self.p1.set_opponent(self.p2) self.p2.set_opponent(self.p1) self.game_board = Board.Board(cfg.BOARD_SIZE[0], cfg.BOARD_SIZE[1], game_mode) (self.board_rows, self.board_cols) = self.game_board.get_dimensions() self.game_logic = gl.GameLogic(self.game_board, self.connect_mode)
def run_battleship(cls, speed): """ :param speed(optional): This is the run method for the battleship program. It creates an instance for the logic class ArrangemenBoardAndBoats, board class, gamelogic, and the scorestat class. The method is constructed to run as long as boats exist in the board. When a boat is removed, it is added to a scorestad dictionary. The program is created to stop when 9 boats are added to the scorestat. The speed parameter is optional and can be added to the logic to slow down the game simulation. :return: """ log = Log() arrangelogic = ArrangeBoardAndBoats() boards = arrangelogic.place_boats() gamelogic = GameLogic() scorestat = Scorestat() while True: players = ["Stian", "Bot"] for i, b in enumerate(boards): if i == 0: player = players[0] else: player = players[1] gamelogic.play(b, players, i, speed, player=player) log.print_log(scorestat.get_scoredict())
pobj = eng.findObjectByName("player") back = eng.findObjectByName("background") _enemsClass = [] _lasersClass = [] _enemLasersClass = [] for i in range(5): _enemsClass.append(Enemy.Enemy(enemies[i], eng)) _lasersClass.append(Projectile.Projectile(playerLasers[i], eng, -5)) _enemLasersClass.append( EnemyProjectile.EnemyProjectile(enemyLasers[i], eng, 4)) enemControl = EnemyController.EnemyController(_enemsClass, _enemLasersClass) hero = Player.Player(pobj, eng, _lasersClass) gameRules = GameLogic.GameLogic() scoreUI = UI.UI(scoreText, eng, 0, "Score: ") livesUI = UI.UI(livesText, eng, 3, "Lives: ") statusUI = UI.UI(statusText, eng, " ", "Game Over") quit = False pause = False waitForKeyUp = True while (not quit): if not pause: eng.startFrame() eng.clearScreen() inputReceived = inSys.checkForInput() if (inputReceived == "quit"):
bord: Board): self.game_logic = game_logic self.players = players self.bord = bord # itertools has a nice way to implement next player: # import itertools # self.players = itertools.cycle(players) def next_player(self) -> PlayerBase: # return next(self.players) the_game.step_counter += 1 return self.players[the_game.step_counter % 2] def start_game(self): while not self.game_logic.is_win(): current_player = self.next_player() print(f"{current_player.name} playing ... ") self.bord.print_board() step = current_player.next_step() self.bord.set_step(current_player.symbol, step) game_logic = GameLogic() board = Board(3) hp = HumanPlayer("Amiel", 'X', board) cp = ComputerPlayer("My Computer", '0', board) players = [hp, cp] the_game = TheGame(game_logic, players, board) the_game.start_game()
def done_scanning(): print( "I am running!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" ) global game_has_just_started global game_logic global list_of_piles # send data to Logic list_of_tableu_piles, list_of_foundation_piles, waste_cards = make_separate_lists( list_of_piles) list_of_tableu_piles, list_of_foundation_piles, waste_cards = sortLists( list_of_tableu_piles, list_of_foundation_piles, waste_cards) if game_has_just_started: game_has_just_started = False print("********************************************************") print("Sending the following to logic:") print(f"Tableu_piles: {list_of_tableu_piles}") print(f"Foundation_piles: {list_of_foundation_piles}") print(f"waste_cards: {waste_cards}") print(" ") game_logic = GameLogic.GameLogic(waste_cards, list_of_tableu_piles, list_of_foundation_piles) else: list_of_tableu_piles, list_of_foundation_piles, new_waste_cards \ = make_separate_lists(list_of_piles_only_containing_newly_detected_cards) list_of_tableu_piles, list_of_foundation_piles, new_waste_cards \ = sortLists(list_of_tableu_piles, list_of_foundation_piles, new_waste_cards) if len(new_waste_cards) != 0: last_waste_card = new_waste_cards[len(new_waste_cards) - 1] game_logic.update_logic_scan(last_waste_card, list_of_tableu_piles, list_of_foundation_piles) print("********************************************************") print("Sending the following to logic:") print(f"Tableu_piles: {list_of_tableu_piles}") print(f"Foundation_piles: {list_of_foundation_piles}") print(f"waste_cards: {last_waste_card}") print(" ") else: game_logic.update_logic_scan(None, list_of_tableu_piles, list_of_foundation_piles) print("********************************************************") print("Sending the following to logic:") print(f"Tableu_piles: {list_of_tableu_piles}") print(f"Foundation_piles: {list_of_foundation_piles}") print(f"waste_cards: None") print(" ") # game_logic.update_logic_scan(new_waste_cards, list_of_tableu_piles, list_of_foundation_piles) # We clear the lists of newly detected cards for pile in range(12): list_of_piles_only_containing_newly_detected_cards[pile].clear() move = game_logic.calculate_move() game_logic.update_logic_move(move) list_of_tableu_piles, list_of_foundation_piles, list_of_waste_cards = game_logic.get_piles( ) print("Getting the following piles from logic:") print(f"Tableu_piles: {list_of_tableu_piles}") print(f"Foundation_piles: {list_of_foundation_piles}") print(f"waste_cards: {list_of_waste_cards}") print(" ") update_card_piles(list_of_tableu_piles, list_of_foundation_piles, list_of_waste_cards) counter = game_logic.get_unknown_counter() print("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!") print(counter) return move
) # Sets the alarm for 3 seconds, meaning that the client waits for 3 seconds for the server response. # If the server haven't given any response whithin 3 seconds, then the client tries more 2 times to resent the message # After it, client displays a message saying that the server is offline #checkChoice(msg) # Checks if the player sended the choice message else: print "It's not your turn. Wait until your opponent finishes the play!" """ ----------------------------------------------------------""" signal.signal(signal.SIGALRM, timeOutHandler) # Timeout signal handler client = socket.socket( socket.AF_INET, socket.SOCK_DGRAM) # Socket used to communicate with the server # Select will wait for the socket and console input inputs = [client, sys.stdin] board = GameLogic() # Game Board """ ----------------------------------------------------------""" """ --------------------- Main Loop --------------------------""" while True: ins, outs, exs = select.select(inputs, [], [], 0) #select devolve para a lista ins quem esta a espera de ler for i in ins: # i == sys.stdin - alguem escreveu na consola, vamos ler e enviar if i == sys.stdin: # sys.stdin.readline() le da consola msg = sys.stdin.readline() # envia mensagem da consola para o servidor sendMessage(client, msg, (SERVER_IP, SERVER_PORT)) tries = 0 # Resets the timeout tries # i == client - o servidor enviou uma mensagem para o socket if i == client:
# labels to draw on images class_file = open(model_classes, "r") input_labels = [line.rstrip("\n") for line in class_file.readlines()] print("Found {} input labels: {} ...".format(len(input_labels), input_labels)) # **** game_has_ended = False game_has_just_started = True # Used to display different info at the start of the game some_move = None is_confirming_move = False # the confirming_move-state is when the player is doing the move physically. game_logic = None tableu_piles = {} foundation_piles = {} waste_pile = [] game_logic = GameLogic.GameLogic(None, None, None) extra_move = 0 # Used to fix a bug where we need to press 'e' twice. move_text = "" # This is the big game loop. It continues until the game has ended. while not game_has_ended: # We check if we had a move from last frame. if some_move is not None: if some_move[0] == "NA": is_confirming_move = False # Getting the piles from the logic. tableu_piles, foundation_piles, waste_pile = game_logic.get_piles() # Getting a frame from camera. ret, img = video_stream.read()
def run(self, game_mode, gameNumber=1000000): # Main loop in the game if game_mode !='Options': self.initialize_game_variables(game_mode) while (gameNumber > 0): self.game_board = Board.Board(cfg.BOARD_SIZE[0], cfg.BOARD_SIZE[1],game_mode) (self.board_rows, self.board_cols) = self.game_board.get_dimensions() self.game_logic = gl.GameLogic(self.game_board, self.connect_mode) self.background.fill(cfg.BLACK) self.game_board.draw(self.background, game_mode) self.game.set_game_over(False) turn_ended = False uninitialized = True current_type = 1 if game_mode == "TeachAgents" or game_mode == "Singleplayer": human_turn = (self.p1.get_coin_type() == current_type) elif game_mode == "Multiplayer": human_turn = True elif game_mode == "Options": pass elif game_mode == "AgentsLearn": human_turn = False p1_turn = (self.p1.get_coin_type() == current_type) (first_slot_X, first_slot_Y) = self.game_board.get_slot(0,0).get_position() coin = Coin.Coin(current_type) self.game.set_game_over_screen(False) while not self.game.get_game_over(): if uninitialized: coin = Coin.Coin(current_type) coin.set_position(first_slot_X, first_slot_Y - Slot.Slot.SIZE) coin.set_column(0) uninitialized = False coin_inserted = False coin.draw(self.background, False) current_player = self.p1 if p1_turn else self.p2 if not human_turn: temp = current_player.complete_move(coin, self.game_board, self.game_logic, self.background) self.game.set_game_over(temp) coin_inserted = True uninitialized = True # handle the keyboard events for event in pygame.event.get(): if event.type == pygame.MOUSEBUTTONDOWN: position = pygame.mouse.get_pos() clicked = self.game_board.onClick(position, self.menu, self.game) if game_mode == "AgentsLearn" or game_mode == "TeachAgents": #execfile( "main.py", {'GAMES_NUMBER':5000}) #os.system('python main.py 50000') #os.execl(sys.executable, os.path.abspath(__file__), *sys.argv) #return if clicked: os.execv(sys.executable, ['python'] + sys.argv) if event.type == pygame.QUIT: self.game.set_game_over(True) return elif event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: exit() if event.key == pygame.K_RIGHT and human_turn: if (coin.get_column() + 1 < self.board_cols): coin.move_right(self.background) elif event.key == pygame.K_LEFT and human_turn: if (coin.get_column() - 1 >= 0): coin.move_left(self.background) elif event.key == pygame.K_RETURN and human_turn and not coin_inserted: try: temp = self.game_board.insert_coin(coin, self.background, self.game_logic) self.game.set_game_over(temp) last_action_human = coin.col if not game_mode == "Multiplayer": current_player.complete_move(self.game_board, last_action_human, self.game_logic) uninitialized = True coin_inserted = True except exception.ColumnFullException as e: pass if self.game.get_game_over(): winner = self.game_logic.determine_winner_name() if winner!="STOP": winner_value = self.game_logic.get_winner() if (game_mode == "AgentsLearn" or game_mode=="TeachAgents"): self.win_list[winner_value]+=1 self.game.set_game_over_screen(True) pygame.display.set_caption(str("Connect 4 : yellow {}, tie {}, red {}").format(self.win_list[1], self.win_list[0], self.win_list[2])) if coin_inserted: if game_mode == "TeachAgents" or game_mode=="Singleplayer": human_turn = not human_turn current_type = 1 if current_type == 2 else 2 p1_turn = not p1_turn pygame.display.flip() self.screen.blit(self.background, (0, 0)) gameNumber -= 1 if game_mode == "AgentsLearn" : self.main_menu() else: if winner!="STOP": self.game.game_over(winner, self.menu, self.screen) self.main_menu() else: # Display the game over screen self.options.set_options_mode(True) self.menu.set_menu_mode(False) self.background.fill(cfg.LIGHT_BLUE) self.options.draw_options(self.games_number, self.speed_train, self.music, self.epsilon) self.games_number, self.speed_train, self.music, self.epsilon = self.options.running_options(self.games_number, self.speed_train, self.music, self.epsilon, self.screen, self.menu) self.main_menu()
cells_y = initialParameters['cells_y'] size = width, height = cellSize * cells_x, cellSize * cells_y #cells_x = width // cellSize #cells_y = height // cellSize print("Ancho: " + str(cells_x)) print("Alto: " + str(cells_y)) backgroundColor = 25, 25, 25 title = pygame.display.set_caption("Game of Life") screen = pygame.display.set_mode(size) game = GameLogic.GameLogic(cells_x, cells_y) paused = True oneStep = False lastCellClicked = (-1, -1) epochs = 1 #game loop while True: if oneStep: paused = True oneStep = False for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit()
import GameLogic as gl testGame = gl.GameLogic() testGame.startGame(2) testGame.dealCard() print(testGame.getPile()) card = testGame.getPile()[0] print(card) for card in testGame.getPlayerHand(0): cardVal = testGame.getCardValue(card) % 100 print(testGame.getCardValue(card)) print(cardVal)
def __init__(self, game_logic: GameLogic, players: List[PlayerBase], bord: Board): self.game_logic = game_logic self.players = self.players = itertools.cycle(players) self.bord = bord def next_player(self) -> PlayerBase: return next(self.players) def start_game(self): game_end = False current_player = "" while not game_end: current_player = self.next_player() print(f"{current_player.name} playing ... ") self.bord.print_board() step = current_player.next_step() self.bord.set_step(current_player.symbol, step) game_end = self.game_logic.is_win(current_player.symbol) print(f"----- Player {current_player.name} Win !!! ") board = Board(3) game_logic = GameLogic(board) hp = HumanPlayer("Amiel", 'X', board) cp = ComputerPlayer("My Computer", '0', board) players = [hp, cp] the_game = TheGame(game_logic, players, board) the_game.start_game()