def __init__(self, player1='Computer1', player2='Computer2', knowledge_base=None): self.player1 = Computer(name=player1, knowledge_base=knowledge_base) self.player2 = Computer(name=player2, icon=IconX(), knowledge_base=knowledge_base)
def __init__(self, fn = 'games.json'): try: with open(fn) as fh: self._games = json.load(fh) except FileNotFoundError: self._games = [] self._logger = Console() self._board = Board() self._user = User(self._board) self._computer = Computer(self._board, self._user ) self._first = None self._game_over = False self._games_file = fn
def startGame(player: Player, comp: Computer, goalNumber, minStep, maxStep): print("We will count to {}, with minimum increment: {}, and maximum increment: {}".format(goalNumber, minStep, maxStep)) time.sleep(2) currentNumber = 0 level = levelOptions() player.number = comp.number = 0 if isPlayerGoFirst(): player.isTurn = True else: comp.isTurn = True # start the game: while not player.isWinner() and not comp.isWinner(): print("-------------------------------------") print("Current counting is:", currentNumber) if player.isTurn: playerCounting(player=player, currentNumber=currentNumber, minStep=minStep, maxStep=maxStep) else: if level == "easy": comp.guessNumber(currentNumber) else: comp.calculateNumber(currentNumber) time.sleep(0.5) print("{} counts: {} \n".format(comp.name, comp.number)) # toggle turn comp.changeTurn() player.changeTurn() currentNumber = max(comp.number, player.number) else: winner(player, comp)
def countingGame(): # TODO: you can change the three constants below and try playing against the computer # goalNumber: number where a player need to reach or pass to win # minStep: minimum increment when counting # maxStep: maximum increment when counting # Make sure the condition is met: goalNumber > maxStep > minStep minStep = 1 maxStep = 3 goalNumber = 10 if goalNumber > maxStep > minStep: playerName = input("What is your name? ") # introduction and demo introduction.introduction() print() time.sleep(0.5) tutorial.runDemo() time.sleep(0.5) print() # create players player = Player(name=playerName, goalNumber=goalNumber) comp = Computer(goalNumber=goalNumber, minStep=minStep, maxStep=maxStep) # start Game gf.startGame(player=player, comp=comp, goalNumber=goalNumber, minStep=minStep, maxStep=maxStep) time.sleep(0.5) print() gf.restart(player=player, comp=comp, goalNumber=goalNumber, minStep=minStep, maxStep=maxStep) else: print("Make sure the condition is met: goalNumber > maxStep > minStep")
def __init__(self, height, width, tokens_per_player=9, max_number=9): window = c.newwin(height, width, 0, 0) super(Game, self).__init__(window) # se crean los diferentes paneles que se mostraran en la ventana del # juego self.table = Table(height, width) self.playerTable = PlayerTable(height, width) self.info = GameInfo(height, width) # se agregan los paneles a la ventana self.addElements(self.table) self.addElements(self.playerTable) self.addElements(self.info, False) # se crean las fichas del juego self.tokens = [ Token(i, j) for i in range(max_number + 1) for j in range(i, max_number + 1) ] # se repareten fichas para cada jugador if self.getFirst() == PLAYER: self.player = Human(self.getPlayerTokens(tokens_per_player)) self.computer = Computer(self.getPlayerTokens(tokens_per_player)) self.turn = PLAYER else: self.computer = Computer(self.getPlayerTokens(tokens_per_player)) self.player = Human(self.getPlayerTokens(tokens_per_player)) self.turn = COMPUTER # como se esta en proceso de desarrollo, el jugador siempre hara la # primera jugada, si se quita esta linea la probabilidad de que el # jugador vaya primero es de 50% self.turn = PLAYER # se agregan las fichas del jugador al tablero del jugador for element in self.player.tokens: self.playerTable.addElements(element) # se actualiza la informacion de los jugadores self.info.initInfo(self.player.getInfo(), self.computer.getInfo())
class TestPlayerHumanComputer: @pytest.mark.parametrize('player, exp_res', [ pytest.param( Player('Player1', [ 1, ]), 'Name: Player1\nHand: [1]', id='Player'), pytest.param( Human('Player1', [ 1, ]), 'Name: Player1\nHand: [1]', id='Human'), pytest.param(Computer('Player1', [ 1, ]), 'Name: Player1\nHand: [1]', id='Computer'), ]) def test_repr(self, player: Union[Player, Human, Computer], exp_res: str): """Testing if Players and children classes return right representation""" assert str(player) == exp_res @pytest.mark.parametrize('player, given_piece, exp_res', [ pytest.param(Computer('1', []), 1, 'win', id='Empty check_set -> win'), pytest.param(Computer('1', [ 1, ]), 1, 'win', id='Get a piece and win'), pytest.param( Computer('1', [ 2, ]), 1, 'pass', id='Get a piece and pass'), pytest.param( Computer('1', [2, 1]), 1, 'take', id='Get a piece and take'), ]) def test_computer_choice(self, player: Computer, given_piece: list, exp_res: str): """Testing if Computer class gives right answers""" assert player.take_piece(given_piece) == exp_res
def new_game(self, num_of_players: int, num_of_humans: int): self.pool: List[int] = pool_of_numbers() self.winner: Union[Human, Computer, None] = None self.cards: List[list] = deal_cards(num_of_players) self.table_of_players: List[Union[Human, Computer]] = [] if num_of_humans == num_of_players: for pl in range(num_of_players): player = Human(f'Person{pl + 1}', self.cards.pop()) self.table_of_players.append(player) else: for hm in range(num_of_humans): human = Human(f"Person{hm + 1}", self.cards.pop()) self.table_of_players.append(human) for cm in range(num_of_players - num_of_humans): computer = Computer(f"Computer{cm + 1}", self.cards.pop()) self.table_of_players.append(computer) self.start_match()
def setup_game(): # determine versus human or versus computer play_against_comp = '' while not play_against_comp in ['Y', 'N']: play_against_comp = input( '\nDo you want to play against the computer? (Y/N) ').upper() computer = True if play_against_comp == 'Y' else False # choose letters letter1 = '' name1 = input('Player 1, what shall we call you? ') name2 = '' if not computer: name2 = input('Player 2, What shall we call you? ') while not letter1 in ['X', 'O']: letter1 = input( f'{name1}, which letter do you want to be, X or O?: ').upper() letter2 = 'X' if letter1 == 'O' else 'O' # init game player1 = Human(letter1, name1) player2 = Computer(letter2) if computer else Human(letter2, name2) play_game(player1, player2, TicTacToe())
def test_computer_choice(self, player: Computer, given_piece: list, exp_res: str): """Testing if Computer class gives right answers""" assert player.take_piece(given_piece) == exp_res
return f"|{'|'.join((str(x) if len(str(x)) == 2 else ' ' + str(x) for x in nums))}|" name_string = card_top_edge = card_line1 = card_line2 = card_line3 = bottom_edge = '' for player in player_table: name_string += player.name + ' card:' + ' ' * ( 22 - len(player.name)) + ' ' card_top_edge += f"{'_' * 28} " card_line1 += f"{join_card_cells(player.card[:9])} " card_line2 += f"{join_card_cells(player.card[9:18])} " card_line3 += f"{join_card_cells(player.card[18:])} " bottom_edge += f"{'-' * 28} " print(name_string, card_top_edge, card_line1, card_line2, card_line3, bottom_edge, sep="\n") if __name__ == '__main__': pt: List[Computer] = [] name_list = ('Player1', '2fd', '3', '4') crds = deal_cards(4) print(crds) for name in name_list: user = Computer(name, crds.pop()) pt.append(user) print(user.check_set) show_cards(*pt)
def game(): player_name = input('Enter your name to start the game: ').strip() while len(player_name) == 0: player_name = input( 'Enter your name to start the game, please: ').strip() player = Player(player_name) computer = Computer() score = {player.name: 0, computer.name: 0} game_condition = True while game_condition: # This while loop is for the re-opportunity to play (game score) print(f' Welcome to the console game, {player.name}! '.center(70, '*'), end='\n\n') users_deck = [player, computer] if player.health < 100 or computer.health < 100: for user in users_deck: user.health = 100 shuffle(users_deck) # Random sequence of players moves move_counter = 0 while player.health > 0 and computer.health > 0: move_counter += 1 for user in users_deck: print(f' Player [{user.name}] move ({move_counter}) '.center( 70, '*')) if isinstance(user, Computer): user.make_some_decision(player) else: actions = [ 'mid_damage_the_enemy', 'high_damage_the_enemy', 'heal_yourself' ] print('Choose some action:', '1. Inflict middle damage(18-25hp) to the enemy', '2. Inflict high damage(10-35hp) to the enemy', '3. Heal yourself(18-25hp)', sep='\n') action_choice = actions[int(input('Enter a number: ')) - 1] if action_choice == 'heal_yourself': getattr(user, action_choice)() else: getattr(user, action_choice)(computer) print(' Players health data '.center(70, '-')) for user_hp in users_deck: # Print the health data of players after the move. print(user_hp) print('-' * 70, end='\n\n') if player.health <= 0: score[computer.name] += 1 print(f'{player.name}, you Lose!') break elif computer.health <= 0: score[player.name] += 1 print(f'Congratulations! {player.name}, you Won!') break print(' SCORE '.center(70, '*')) for key, value in score.items(): print(f'{key}: {value}') print('*' * 70) print('Play again?', '1. No', '2. Yes', sep='\n') game_condition = [False, True][int(input('Enter a number: ')) - 1]
class Game(object): #A constructor to initialize the game. The two player objects are initialized and #their grids are constucted. def __init__(self): self.u = User() self.u.make_grid() self.comp = Computer() self.comp.make_grid() #The intro for the game. def intro(self): print( "******************************************************************************" ) print( "* *" ) print( "* Battleship! *" ) print( "* *" ) print( "******************************************************************************\n" ) #The game instructions. def instructions(self): print(" 1 2 3 4 5\n") print("A O O O O O\n") print("B O O O O O\n") print("C O O O O O\n") print("D O O O O O\n") print("E O O O O O\n") print( "Welcome to the game of battleship! You will be playing against a computer" ) print( "to test your intelligence. Above is a grid with a bunch of Os. You will be " ) print( "racing the computer. Who ever hits the opponent's battleship first will win" ) print("the game.") print( "Look at the grid. The grid has a coordinate system. The top column shows the" ) print( "numbers 0-4. The first column also had the numbers 0-4. You will choose to" ) print( "locate your battleship for you computer opponent to guess on. You will choose" ) print( "the coordinate based on the row number and the column number. This will also" ) print( "be the way for you to guess the opponent's battleship. Good luck and have fun!" ) print( "_______________________________________________________________________________\n" ) #Letting the players choose location of their ships on the grid. def players_choose_point(self): self.u.choice() self.comp.choice() #This helper method will choose which player will go first. def first(self): return random.randint(0, 1) #This method will play the Battleship game with the user winning the coin toss #and gets to choose his/hers opponent's coordinates first. def player_first(self): while True: self.u.display_grid() user_guess = self.u.guess() time.sleep(1) if user_guess[1] == self.comp.computer_point_opp[0] and user_guess[ 0] == self.comp.computer_point_opp[1]: print("You sunk the computer's ship! You won! ") time.sleep(1) break else: if self.u.user_grid.g[user_guess[1]][user_guess[0]] == "X": print("You already guessed that point!") else: print("You missed the computer's ship!") self.u.user_grid.g[user_guess[1]][user_guess[0]] = "X" time.sleep(1) self.comp.display_grid() computer_guess = self.comp.guess() time.sleep(1) if computer_guess[1] == self.u.user_point_opp[ 1] and computer_guess[0] == self.u.user_point_opp[0]: print("The computer sunk your ship! You lost!") time.sleep(1) break else: if self.comp.computer_grid.g[computer_guess[1]][ computer_guess[0]] == "x": print( "The computer guessed that point! You get another shot!" ) else: print( "The computer misssed your ship! You are still alive!") self.comp.computer_grid.g[computer_guess[1]][ computer_guess[0]] = "x" time.sleep(1) #This method will play the Battleship game with the computer winning the coin toss #and gets to choose its opponent's coordinates first. def computer_first(self): while True: self.comp.display_grid() computer_guess = self.comp.guess() time.sleep(1) if computer_guess[1] == self.u.user_point_opp[ 1] and computer_guess[0] == self.u.user_point_opp[0]: print("The computer sunk your ship! You lost!") time.sleep(1.5) break else: if self.comp.computer_grid.g[computer_guess[1]][ computer_guess[0]] == "x": print( "The computer guessed that point! You get another shot!" ) else: print( "The computer misssed your ship! You are still alive!") self.comp.computer_grid.g[computer_guess[1]][ computer_guess[0]] = "x" time.sleep(1) self.u.display_grid() user_guess = self.u.guess() time.sleep(1) if user_guess[1] == self.comp.computer_point_opp[0] and user_guess[ 0] == self.comp.computer_point_opp[1]: print("You sunk the computer's ship! You won! ") time.sleep(1) break else: if self.u.user_grid.g[user_guess[1]][user_guess[0]] == "X": print("You already guessed that point!") else: print("You missed the computer's ship!") self.u.user_grid.g[user_guess[1]][user_guess[0]] = "X" time.sleep(1) #The game running. def game_loop(self): self.players_choose_point() if self.first(): print( "\nA coin was tossed to see who goes first, and you won the coin toss!" ) time.sleep(1.5) self.player_first() else: print( "\nA coin was tossed to see who goes first, and the computer won the coin toss!" ) time.sleep(1.5) self.computer_first()
def __init__(self): self.u = User() self.u.make_grid() self.comp = Computer() self.comp.make_grid()
class Game(object): #A constructor to initialize the game. The two player objects are initialized and #their grids are constucted. def __init__(self): self.u = User() self.u.make_grid() self.comp = Computer() self.comp.make_grid() #The intro for the game. def intro(self): print("******************************************************************************") print("* *") print("* Battleship! *") print("* *") print("******************************************************************************\n") #The game instructions. def instructions(self): print(" 1 2 3 4 5\n") print("A O O O O O\n") print("B O O O O O\n") print("C O O O O O\n") print("D O O O O O\n") print("E O O O O O\n") print("Welcome to the game of battleship! You will be playing against a computer") print("to test your intelligence. Above is a grid with a bunch of Os. You will be ") print("racing the computer. Who ever hits the opponent's battleship first will win") print("the game.") print("Look at the grid. The grid has a coordinate system. The top column shows the" ) print("numbers 0-4. The first column also had the numbers 0-4. You will choose to" ) print("locate your battleship for you computer opponent to guess on. You will choose") print("the coordinate based on the row number and the column number. This will also" ) print("be the way for you to guess the opponent's battleship. Good luck and have fun!") print("_______________________________________________________________________________\n") #Letting the players choose location of their ships on the grid. def players_choose_point(self): self.u.choice() self.comp.choice() #This helper method will choose which player will go first. def first(self): return random.randint(0,1) #This method will play the Battleship game with the user winning the coin toss #and gets to choose his/hers opponent's coordinates first. def player_first(self): while True: self.u.display_grid() user_guess = self.u.guess(); time.sleep(1) if user_guess[1] == self.comp.computer_point_opp[0] and user_guess[0] == self.comp.computer_point_opp[1]: print("You sunk the computer's ship! You won! ") time.sleep(1) break else: if self.u.user_grid.g[user_guess[1]][user_guess[0]] == "X": print ("You already guessed that point!") else: print("You missed the computer's ship!") self.u.user_grid.g[user_guess[1]][user_guess[0]] = "X" time.sleep(1) self.comp.display_grid() computer_guess = self.comp.guess() time.sleep(1) if computer_guess[1] == self.u.user_point_opp[1] and computer_guess[0] == self.u.user_point_opp[0]: print("The computer sunk your ship! You lost!") time.sleep(1) break else: if self.comp.computer_grid.g[computer_guess[1]][computer_guess[0]] == "x": print("The computer guessed that point! You get another shot!") else: print("The computer misssed your ship! You are still alive!") self.comp.computer_grid.g[computer_guess[1]][computer_guess[0]] = "x" time.sleep(1) #This method will play the Battleship game with the computer winning the coin toss #and gets to choose its opponent's coordinates first. def computer_first(self): while True: self.comp.display_grid() computer_guess = self.comp.guess() time.sleep(1) if computer_guess[1] == self.u.user_point_opp[1] and computer_guess[0] == self.u.user_point_opp[0]: print("The computer sunk your ship! You lost!") time.sleep(1.5) break else: if self.comp.computer_grid.g[computer_guess[1]][computer_guess[0]] == "x": print("The computer guessed that point! You get another shot!") else: print("The computer misssed your ship! You are still alive!") self.comp.computer_grid.g[computer_guess[1]][computer_guess[0]] = "x" time.sleep(1) self.u.display_grid() user_guess = self.u.guess(); time.sleep(1) if user_guess[1] == self.comp.computer_point_opp[0] and user_guess[0] == self.comp.computer_point_opp[1]: print("You sunk the computer's ship! You won! ") time.sleep(1) break else: if self.u.user_grid.g[user_guess[1]][user_guess[0]] == "X": print ("You already guessed that point!") else: print("You missed the computer's ship!") self.u.user_grid.g[user_guess[1]][user_guess[0]] = "X" time.sleep(1) #The game running. def game_loop(self): self.players_choose_point() if self.first(): print("\nA coin was tossed to see who goes first, and you won the coin toss!") time.sleep(1.5) self.player_first() else: print("\nA coin was tossed to see who goes first, and the computer won the coin toss!") time.sleep(1.5) self.computer_first()
class TicTacToe: WON = 'You have won the game!' LOST = 'The computer has won the game!' TIE = 'The game is a tie!' def __init__(self, fn = 'games.json'): try: with open(fn) as fh: self._games = json.load(fh) except FileNotFoundError: self._games = [] self._logger = Console() self._board = Board() self._user = User(self._board) self._computer = Computer(self._board, self._user ) self._first = None self._game_over = False self._games_file = fn def help(self): msg = '\nWelcome to the Tic Tac Toe game!\n' msg = msg + 'The computer will play with the letter C and you will play with the letter U. At the end of every game the winner and the state of the grid will be saved to the disk. When ask you to play enter a number between 0 and 8 representing the square on which you want to play as indicated by the following diagram:\n' self._logger.log(msg) self.diagram() def diagram(self): msg = '' msg = msg + ' | | ' + '\n' msg = msg + ' 0 | 1 | 2 ' + '\n' msg = msg + ' | | ' + '\n' msg = msg + '-----------' + '\n' msg = msg + ' | | ' + '\n' msg = msg + ' 3 | 4 | 5 ' + '\n' msg = msg + ' | | ' + '\n' msg = msg + '-----------' + '\n' msg = msg + ' | | ' + '\n' msg = msg + ' 6 | 7 | 8 ' + '\n' msg = msg + ' | | ' + '\n\n' self._logger.log(msg) def menu(self): msg = 'Menu:\n' msg = msg + ' Press 1 to start a new game.' + '\n' msg = msg + ' Press 2 to see a list of past games and their results.' + '\n' msg = msg + ' Press 3 to exit.' + '\n\n' self._logger.log(msg) def user_choice(self): self.menu() try: choice = int(input('Enter your choice: ').lower()) if choice not in list(map(int, Options)): self._logger.log(f'\nInvalid number {choice}\n') return choice except ValueError: self._logger.log('\nInvalid number.\n') raise ValueError def begin(self): self.reset() self.first() self.play() self.results() self.append() self.save() def reset(self): self._board.reset() self._game_over = False self._first = None def first(self): user_answer = input('\nWould you like to go first?(y/n): ').lower() while user_answer != 'y' and user_answer != 'n': self._logger.log('Please enter y or n.') user_answer = input('\nWould you like to go first?(y/n): ').lower() self._logger.log('\n') self._first = self._user if user_answer == 'y' else self._computer def play(self): player = self._user if self._first == None else self._first while not self._board.is_full() and not self._user.won() and not self._computer.won(): player.play() if player == self._computer: self._logger.log(str(self._board)) player = self._computer if player == self._user else self._user if self._user.won() or (not self._computer.won() and self._first == self._user): self._logger.log(str(self._board)) self._game_over = True def results(self): if self._game_over: if self._user.won(): message = TicTacToe.WON elif self._computer.won(): message = TicTacToe.LOST else: message = TicTacToe.TIE self._logger.log(message) else: self._logger.log("In order to see the results of a game you have to play it until the very end.") self._logger.log('\n') def append(self): if self._game_over: if self._user.won(): result = str(self._user) elif self._computer.won(): result = str(self._computer) else: result = "T" self._games.append({"result": result, "board": self._board.to_json()}) else: self._logger.log("In order to append a game you have to play it until the very end.") def save(self): if self._game_over: try: with open(self._games_file, 'w') as fh: json.dump(self._games, fh) except Exception as e: self._logger.log('\n') self._logger.log(str(e) + '\n') else: self._logger.log("In order to save a game you have to play it until the very end.") def history(self): if len(self._games) > 0: self._logger.log('\n******** List of past games: ********\n') i = 1 for game in self._games: if game['result'] == 'U': result = TicTacToe.WON elif game['result'] == 'C': result = TicTacToe.LOST else: result = TicTacToe.TIE self._logger.log(f'Game #{i}: {result}') board = self._board.from_json(game['board']) self._logger.log(str(board)) del(board) i += 1 else: self._logger.log('There is no record of past games yet. Play some games and comeback later.\n')
class Game(BaseContainer): """ Esta se encarga de manejar todo el ciclo del juego Parametros ---------- height(int): Entero que representa la altura de la pantalla width(int): Entero que representa el ancho de la pantalla tokens_per_player(int): Entero que indica cuantas fichas le corresponden a cada jugador max_number(int): Entero que indica el numero maximo que ira en las fichas del domino """ def __init__(self, height, width, tokens_per_player=9, max_number=9): window = c.newwin(height, width, 0, 0) super(Game, self).__init__(window) # se crean los diferentes paneles que se mostraran en la ventana del # juego self.table = Table(height, width) self.playerTable = PlayerTable(height, width) self.info = GameInfo(height, width) # se agregan los paneles a la ventana self.addElements(self.table) self.addElements(self.playerTable) self.addElements(self.info, False) # se crean las fichas del juego self.tokens = [ Token(i, j) for i in range(max_number + 1) for j in range(i, max_number + 1) ] # se repareten fichas para cada jugador if self.getFirst() == PLAYER: self.player = Human(self.getPlayerTokens(tokens_per_player)) self.computer = Computer(self.getPlayerTokens(tokens_per_player)) self.turn = PLAYER else: self.computer = Computer(self.getPlayerTokens(tokens_per_player)) self.player = Human(self.getPlayerTokens(tokens_per_player)) self.turn = COMPUTER # como se esta en proceso de desarrollo, el jugador siempre hara la # primera jugada, si se quita esta linea la probabilidad de que el # jugador vaya primero es de 50% self.turn = PLAYER # se agregan las fichas del jugador al tablero del jugador for element in self.player.tokens: self.playerTable.addElements(element) # se actualiza la informacion de los jugadores self.info.initInfo(self.player.getInfo(), self.computer.getInfo()) def getFirst(self): """ Este metodo decide que jugador va primero """ return choice([PLAYER, COMPUTER]) def getPlayerTokens(self, tokenNumber): """ Este metodo elimina y retorna un numero de fichas del total de fichas del juego """ tokens = [] while len(tokens) < tokenNumber: # se van elijiendo fichas de forma aleatoria tokens.append(self.tokens.pop(randint(0, len(self.tokens) - 1))) # se posicionan las fichas de forma que esten en la misma fila y # de forma consecutiva tokens[-1].position = [1, 1 + 8 * (len(tokens) - 1)] return tokens @applyEvent(113, COVER) # q def inputHandler(self, char): # la tecla TAB se usa para cambiar de panel, entre el panel con las # fichas del jugador y el panel con las fichas jugadas if char == 9: # TAB # solo se puede cambiar panel si no se esta ubicando una ficha if not self.table.isLocatingToken: self.linter += 1 # cuando se presiona la tecla p el jugador ha cedido el turno if char == 112: # p self.player.skippedTurns += 1 self.turn = COMPUTER else: pass # para que self.linter no tome valores no posibles self.linter %= self.linterableObjects # se maneja el turno del jugador if self.turn == PLAYER: # si el panel en el que se esta es el de las fichas del jugador if self.linter == 1: # se obtiene la ficha, si token toma el valor de None es porque # el jugador no ha realizado ninguna jugada token = self.playerTable.inputHandler(char) # se revisa si la jugada es valida if (token is not None) and self.table.isValidToken(token): # cuando la jugada es valida se obtiene la ficha token = self.player.getToken(token.numerator, token.denominator) # la ficha ya no esta en el panel del jugador self.playerTable.elements.remove((token, True)) # hay una ficha menos self.playerTable.linterableObjects -= 1 # la ficha debe estar en el panel de las fichas jugadas self.table.locateToken(token) # se cambia al panel de las fichas jugadas, para iniciar # el posicionamiento de la nueva ficha self.linter = 0 # si el panel es el de las fichas jugadas else: # se gestiona las operaciones del jugador en el panel de fichas # jugadas, si nextTurn toma el valor de True, es porque el # jugador ha terminado su jugada, es decir, ha posicionado una # ficha nextTurn = self.table.inputHandler(char) if nextTurn: self.turn = COMPUTER # se actualiza la informacion del jugador self.info.updateInfo(self.player.getInfo(), player=PLAYER) # turno de la maquina else: # se obtiene jugada del computador, si token toma el valor de None # es porque no habia jugada disponible token = self.computer.makeMove(self.table.getTokens(), self.table.right, self.table.left) if (token is not None) and self.table.isValidToken(token): # cuando la jugada es valida se obtiene la ficha token = self.computer.getToken(token.numerator, token.denominator) # se ubica la ficha del computador self.table.locateComputerToken(token) # se actualiza la informacion de la maquina self.info.updateInfo(self.computer.getInfo(), player=COMPUTER) # ahora es turno del jugador self.turn = PLAYER return NONE def write(self): """ Este metodo dibuja todo en pantalla """ # esta variable especifica si el color del borde del panel que sera # resaltado colorLinter = None for i in range(len(self.elements)): element, _ = self.elements[i] # si el i coincide con self.linter, entonces se debe resaltar el # panel if i == self.linter: colorLinter = 2 element.write(colorLinter) colorLinter = None
def __init__(self, knowledge_base=None): self.player1 = Human() self.player2 = Computer(knowledge_base=knowledge_base)
def demoGame(): # constants currentNumber = 0 minStep = 1 maxStep = 3 goalNumber = 10 # create players comp1 = Computer(goalNumber=goalNumber, minStep=minStep, maxStep=maxStep) comp2 = Computer(goalNumber=goalNumber, minStep=minStep, maxStep=maxStep) comp1.isTurn = True comp1.name = "Computer 1" comp2.name = "Computer 2" print("\n Demo Game!!! \n We will count to 10 \n Start with 0\n") loopCounter = 0 # this counter is even means both players already make their moves # start the game: while currentNumber < goalNumber: if comp1.isTurn: comp1.guessNumber(currentNumber) print("{} counts: {}".format(comp1.name, comp1.number)) else: comp2.guessNumber(currentNumber) print("{} counts: {} \n".format(comp2.name, comp2.number)) currentNumber = max(comp1.number, comp2.number) comp1.changeTurn() comp2.changeTurn() time.sleep(0.5) loopCounter += 1 if loopCounter % 2 == 0: print("-------------------------------------") print("Current counting is:", currentNumber) else: gf.winner(comp1, comp2)
def get_computer_player(self): """ Добавление игрока - компьютера :return: новый игрок """ return Computer(self.graphic)