def evalFunction(situation, joueur): """ the evaluation function for the min-max algorithm. It evaluates the given situation, the evaluation function increases with the quality of the situation for the player :param situation: the current situation :type situation: a game situation :param player: the current player :type player: player :returns: *(number)* -- the score of the given situation for the given player. The better the situation for the minmax player, the higher the score. The opposite for human player. """ number_moves = 0 for i in range(3): for j in range(3): if situation[i][j] != '': number_moves += 1 winner = getWinner({"":0},situation, joueur) if winner != None: if Player.get_name(joueur) == Player.get_name(winner)== 'computer' : return 1000-number_moves if Player.get_name(joueur) != 'computer' and Player.get_name(joueur) == Player.get_name(winner) : return -1000 + number_moves if winner== None: return 0
def handler(x, y, g, p1, p2, b, eve): """ handles the click :param x: x-coordinate :param y: y-coordinate :param g: situation :param p1: player :param p2: player :param b: list of buttons :param eve: the event """ global current spec = Player.get_spec(current) if g[x][y] == '': g[x][y] = spec if Player.get_name(current) != 'computer' and Player.get_name( switch_player( current, p1, p2)) == "computer" and not tictactoe.isFinished(g): g = minmax.IA(g, switch_player(current, p1, p2), current, 10, tictactoe) else: current = switch_player(current, p1, p2) __redraw(g, b) if tictactoe.isFinished(g): winner = tictactoe.getWinner(g, g, switch_player(current, p1, p2)) _disable(g, b) msg = finalState(winner) msgbox.showinfo("finished", msg)
def play(game_name, difficulty): """ Main game function process :param game_name: the game's name :type game_name: str :return: None """ global currentPlayer global mod if game_name == "nim": import nim_game as Game mod = __import__("nim_game") elif game_name == "othello": import othello as Game mod = __import__("othello") else: import tictactoe as Game mod = __import__("tictactoe") ask_players_names(Game.color) situation = Game.initSituation(game_name) while not Game.isFinished(situation): if currentPlayer is None: currentPlayer = Game.get_player1(Game.game) else: currentPlayer = swap_player_turn(currentPlayer, mod) if not Game.playerCanPlay(Game.game, situation, currentPlayer): print(currentPlayer, " can't play") currentPlayer = swap_player_turn(currentPlayer, Game) Game.displaySituation(situation) print(Player.get_name(currentPlayer), " turn") if Player.get_name(currentPlayer) == "Minmax": situation = IA.min_max(game_name, Game.game, situation, currentPlayer, difficulty) else: situation = Game.humanPlayerPlays(Game.game, currentPlayer, situation) Game.game['nb_plays'] += 1 winner = Game.getWinner(Game.game, situation, currentPlayer) if winner is None: Game.displaySituation(situation) print("equality !") else: Game.displaySituation(situation) print(Player.get_name(winner), "won")
def handler(x, y, g, p1, p2, b, dif, eve): """ handles player's clicks and manage turns of the players :param x: the x-coordinate of the move :type x: int :param y: the y-coordinate of the move :type y: int :param g: the current situation :type g: situation :param p1: the first player :type p1: player :param p2: the second player :type p2: player :param b: buttons list :type b: list :param dif: the difficulty of the game(the depth of the IA recursivity) :type dif: int :param eve: the event :type eve: event """ global current if not othello.isFinished(g): if Player.get_name(current) != 'computer' and othello.playerCanPlay( g, g, current): g = othello.clean(g) if othello.isValidMove(g, current, x, y): valid = (othello.validMoves(g, current, x, y)) for k in valid: x1, y1 = k[0], k[1] g[x1][y1] = (Player.get_spec(current)) g[x][y] = Player.get_spec(current) current = switch_player(current, p1, p2) elif not othello.playerCanPlay(g, g, current): current = switch_player(current, p1, p2) if Player.get_name(current) == 'computer' and othello.playerCanPlay( g, g, current): g = othello.clean(g) g = AlphaBeta.IA(g, current, switch_player(current, p1, p2), dif, othello) current = switch_player(current, p1, p2) hints(g, b) __redraw(g, b) othello.clean(g) if othello.isFinished(g): winner = checkwinner(g, g, current, p1, p2, othello) _disable(g, b) msg = finalState(winner) msgbox.showinfo("finished", msg)
def handler(column, sit, p1, p2, b, eve): """ handles the click :param column: the column of the button :type column: int :param sit: the current situation :type sit: situation :param p1: the first player :type p1: player :param p2: the second player :type p2: player :param b: buttons list :type b: list :param eve: the event :type eve: event """ global current global dif spec = Player.get_spec(current) if not puissance.isFinished(sit): if Player.get_name(current) != 'computer': if puissance.isValidMove(sit, column): for i in range(6): if sit[i][column] == ' ': if i == 5: sit[i][column] = Player.get_spec(current) else: continue else: sit[i - 1][column] = Player.get_spec(current) break current = switch_player(current, p1, p2) if not puissance.isFinished(sit) and Player.get_name( current) == 'computer': print(dif) sit = AlphaBeta.IA(sit, current, switch_player(current, p1, p2), dif, puissance) if dif < 8: dif += 1 current = switch_player(current, p1, p2) __redraw(sit, b) if puissance.isFinished(sit): winner = twoplayergame.checkwinner(sit, sit, current, p1, p2, puissance) _disable(sit, b) msg = finalState(winner) msgbox.showinfo("finished", msg)
def initPlayer(methods, info): """ add a player to the round """ if Plugin.bj_created: if not Plugin.round_started: name = info["prefix"].split("!")[0] if len(Plugin.player_lst) <= 5: # limit game to 6 players if not ( name in [player.get_name() for player in Plugin.player_lst] ): Plugin.player_lst.append( player.Player( len(Plugin.player_lst), Plugin.starting_chips, name ) ) methods["send"](info["address"], name + " joined the game!") else: methods["send"]( info["address"], "You are already in this round!" ) else: methods["send"](info["address"], "This round is full already") else: methods["send"]( info["address"], "The round has started, wait for a new one to join!", ) else: methods["send"](info["address"], "A game has not yet been created!")
def evalFunction(situation, player): """ the evaluation function for the min-max algorithm. It evaluates the given situation, the evaluation function increases with the quality of the situation for the player :param situation: the current situation :type situation: a game situation :param player: the current player :type player: player :returns: *(number)* -- the score of the given situation for the given player. The better the situation for the minmax player, the higher the score. The opposite for human player. """ spec = Player.get_spec(player) winner = getWinner([], situation, player) name = Player.get_name(player) edge = corner = compteur = 0 for i in range(8): for j in range(8): if isOnCorner(i, j) and situation[i][j] == spec: corner += 1 if situation[i][j] == spec: compteur += 1 if isOnEdge(i, j) and situation[i][j] == spec: edge += 1 if name == 'computer' and winner == player: return 1000 + compteur + 6 * corner + 2 * edge if name != 'computer' and winner == player: return -1000 - compteur - 6 * corner - 2 * edge if winner == None: return 0
def _input_coords(situation, player): """ takes the input value from the player :param situation: situation :param player: player :return: the value """ if Player.get_spec(player) == 'X': color = "n" else: color = 'b' print( Player.get_name(player) + '(' + colors[color] + ')' + " it's your turn") coords = input("coords of cell? ") coords = coords.split(',') x = int(coords[0]) y = int(coords[1]) try: if isCheck(situation, situation[x][y][1]): l = (checkMoves(situation, situation[x][y][1])[0]) if isOnBoard(x, y) and situation[x][y][1] == color and (x, y) in l: return (x, y) else: l = canPlay(situation, x, y) if situation[x][y][1] == color and len(l) != 0: return (x, y) except: return _input_coords(situation, player) print('illegal play') return _input_coords(situation, player)
def evalFunction(situation, player): """ the evaluation function for the min-max algorithm. It evaluates the given situation, the evaluation function increases with the quality of the situation for the player :param situation: the current situation :type situation: a game situation :param player: the current player :type player: player :returns: *(number)* -- the score of the given situation for the given player. The better the situation for the minmax player, the higher the score. The opposite for human player. """ if Player.get_spec(player) == 'X': color = "n" else: color = "b" note = 0 if getWinner("", situation, player) != None: if getWinner('', situation, player).get_name() == 'computer': return 10000 else: return -10000 else: for i in range(8): for j in range(8): if situation[i][j][1] == color: note += -len(canPlay(situation, i, j)) * 10 + minmaxValues[ situation[i][j][0]] if Player.get_name(player) == "computer": return note else: return -note
def find_winner(self): info = [] for player in self.players: info.append([player.get_name(), player.hand.best_poker_hand(self.table.cards)]) info.sort(key=lambda x: x[-1], reverse=True) print("The winner is: " + info[0][0] + " with " + str(info[0][1]))
def create(): """ creates the initial situation and draws it """ global img global current sit = tictactoe.create_game() g = tictactoe.initSituation(sit) if ask.askplayer() == 1: p1 = Player.new_player('human', 'X') p2 = Player.new_player('computer', 'O') else: p1 = Player.new_player('player1', 'X') p2 = Player.new_player('player2', 'O') p = [p1, p2] current = p[random.randint(0, 1)] if Player.get_name(current) == 'computer': g = AlphaBeta.IA(g, current, switch_player(current, p1, p2), 10, tictactoe) current = switch_player(current, p1, p2) win = tk.Tk() win.title('TicTacToe') iconpath = os.path.join(os.path.dirname(os.path.abspath(__file__)), "icons") img = [ tk.PhotoImage(file=os.path.join(iconpath, "tap.gif")), tk.PhotoImage(file=os.path.join(iconpath, "X.gif")), tk.PhotoImage(file=os.path.join(iconpath, "O.gif")) ] b = [] for i in range(3): b.insert(i, []) for j in range(3): if g[i][j] == 'X': ig = img[1] button.config(image=ig) if g[i][j] == 'O': ig = img[2] if g[i][j] == '': ig = img[0] button = tk.Button(win, padx=0, pady=0, width=180, height=180, image=ig, background='darkKhaki') button.grid(column=i, row=j) button.bind( "<Button-1>", partial(handler, (button.grid_info()['row']), (button.grid_info()['column']), g, p1, p2, b)) b[i].insert(j, button) win.mainloop()
def create(): """ creates the initial situation and draws it """ global img global current g = puissance.create_game() sit = puissance.initSituation(g) if ask.askplayer() == 1: p1 = Player.new_player('human', 'X') p2 = Player.new_player('computer', 'O') else: p1 = Player.new_player('player1', 'X') p2 = Player.new_player('player2', 'O') p = [p1, p2] current = p[random.randint(0, 1)] if Player.get_name(current) == 'computer': sit = AlphaBeta.IA(sit, current, switch_player(current, p1, p2), 6, puissance) current = switch_player(current, p1, p2) win = tk.Tk() win.title('puissance 4') iconpath = os.path.join(os.path.dirname(os.path.abspath(__file__)), "icons") img = [ tk.PhotoImage(file=os.path.join(iconpath, "blanc1.gif")), tk.PhotoImage(file=os.path.join(iconpath, "rouge.gif")), tk.PhotoImage(file=os.path.join(iconpath, "jaune.gif")) ] b = [] for i in range(7): b.insert(i, []) for j in range(6): if sit[j][i] == 'O': ig = img[2] if sit[j][i] == 'X': ig = img[1] if sit[j][i] == ' ': ig = img[0] button = tk.Button(win, padx=0, pady=0, width=90, height=90, image=ig, background='blue') button.grid(column=i, row=j) button.bind( "<Button-1>", partial(handler, (button.grid_info()['column']), sit, p1, p2, b)) b[i].insert(j, button) win.mainloop()
def leftClick(x, y, sit, p1, p2, b, eve): """ handles the left click :param column: the column of the button :type column: int :param sit: the current situation :type sit: situation :param p1: the first player :type p1: player :param p2: the second player :type p2: player :param b: buttons list :type b: list :param eve: the event :type eve: event """ global current try: if (x, y) in chess.canPlay(sit, res[0], res[1]) and (x, y) in (chess.validMoves( sit, res[0], res[1])): i, j = res[0], res[1] if (sit[i][j] == 'Pb' and x == 0) or (sit[i][j] == 'Pn' and x == 7): sit[x][y] = 'D' + sit[i][j][1] sit[i][j] = ' ' else: sit[x][y] = sit[i][j] sit[i][j] = ' ' current = switch_player(current, p1, p2) if chess.isCheck(sit, chess.Ennemy(sit[x][y])): msgbox.showinfo("Echec", "Echec ! ") __redraw(sit, b) if chess.fini(sit, current): _disable(sit, b) loser = checkwinner(sit, sit, current, p1, p2, chess) msg = loser + " Sorry you lose!" msgbox.showinfo("Checkmate", "CheckMate! " + msg) if Player.get_name(current) == 'computer': sit = AlphaBeta.IA(sit, current, switch_player(current, p1, p2), 2, chess) current = switch_player(current, p1, p2) __redraw(sit, b) if chess.fini(sit, current): _disable(sit, b) loser = checkwinner(sit, sit, current, p1, p2, chess) msg = loser + " Sorry you lose!" msgbox.showinfo("Checkmate", "CheckMate! " + msg) except: pass
def evalFunction(situation, player): """ the evaluation function for the min-max algorithm. It evaluates the given situation, the evaluation function increases with the quality of the situation for the player :param situation: the current situation :type situation: a game situation :param player: the current player :type player: player :returns: *(number)* -- the score of the given situation for the given player. The better the situation for the minmax player, the higher the score. The opposite for human player. """ winner = getWinner([], situation, player) if winner != None: if Player.get_name(player) == Player.get_name(winner) == 'computer': return 100000 elif Player.get_name(player) != 'computer' and Player.get_name( winner) != 'computer': return -100000 else: return 1 counter = note = 0 spec = Player.get_spec(player) for i in range(6): for j in range(7): if situation[i][j] == Player.get_spec(player): for xdirection, ydirection in [[0, 1], [1, 1], [1, 0], [1, -1], [0, -1], [-1, -1], [-1, 0], [-1, 1]]: counter = 0 x, y = i, j x += xdirection y += ydirection if isOnBoard(x, y): if situation[x][y] == ' ': counter += 1 x += xdirection y += ydirection while isOnBoard(x, y) and situation[x][y] == " ": counter += 1 x += xdirection y += ydirection if counter == 3: note = 10000 else: note = -10000 else: if Player.get_name(player) == 'computer': return note elif Player.get_name(player) != 'computer': return -note
def _input_pebbles(player, number_pebbles, number_message): """ reads the number of pebbles taken by player :returns: *(int)* -- the number of taken pebbles """ print( Player.get_name(player) + " it's your turn, you can take " + number_message + " pebbles.") nb_taken_pebbles = input("how many pebbles do you take ? ") try: if int(nb_taken_pebbles) in number_pebbles: return int(nb_taken_pebbles) # else : invalid input : redo input except ValueError: # input is not an integer : redo input pass print("illegal play, you can only take " + number_message + " pebbles") return _input_pebbles(player, number_pebbles, number_message)
def _input_pebbles(player, number_pebbles, number_message): """ reads the number of pebbles taken by player :returns: *(int)* -- the number of taken pebbles """ print(Player.get_name(player)+" it's your turn, you can take "+number_message+" pebbles.") nb_taken_pebbles = input("how many pebbles do you take ? ") try: if int(nb_taken_pebbles) in number_pebbles: return int(nb_taken_pebbles) # else : invalid input : redo input except ValueError: # input is not an integer : redo input pass print("illegal play, you can only take "+number_message+" pebbles") return _input_pebbles(player,number_pebbles, number_message)
def evalFunction(situation, player): """ the evaluation function for the min-max algorithm. It evaluates the given situation, the evaluation function increases with the quality of the situation for the player :param situation: the current situation :type situation: a game situation :param player: the current player :type player: player :returns: *(number)* -- the score of the given situation for the given player. The better the situation for the minmax player, the higher the score. The opposite for human player. """ winner = getWinner([], situation, player) name = Player.get_name(player) if name == 'computer' and winner == player: return -1000 + situation if name != 'computer' and winner == player: return 1000 - situation if winner == None: return 0
def checkHand(methods,info,player): ''' check the value of a player's hand ''' name = player.get_name() total = player.show_player_hand().hand_total() cards = " ".join([card.show_card() for card in player.show_player_hand().show_hand_obj()]) if total > 21: methods["send"](info["address"],name+"'s hand "+cards+" has a value of "+str(total)+" so you have been kicked out") for p in Plugin.player_lst: if p.get_name() == name: Plugin.player_lst.remove(p) if len(Plugin.player_lst) == 1: Plugin.winner = Plugin.player_lst[0].get_name() methods["send"](info["address"],"The winner is "+Plugin.winner+"!") Plugin.bj_created = False elif total == 21: methods["send"](info["address"],name+"'s hand "+cards+" has a value of 21 so you have won!") Plugin.winner = name Plugin.bj_created = False else: methods["send"](info["address"],name+"'s hand "+cards+" has a value of "+str(total)+".")
def _input_coords(situation, player): """ manage the interaction with the human player :param situation: the current situation :type situation: list :param player: player :type player: player """ print( Player.get_name(player) + '(' + Player.get_spec(player) + ')' + " it's your turn") coord = input("Enter number of a column ? ") try: y = int(coord) if isValidMove(situation, y): return (y) except: return _input_coords(situation, player) print('illegal play') return _input_coords(situation, player)
def take_action(self, player): action = self.ui.get_player_action(player.get_name()) if action == 1: player.draw_action() elif action == 2: player.meld_action() elif action == 3: player.dogma() elif action == 4: pass elif action == 5: player.hand.print_self() elif action == 6: choice = self.ui.get_color() player.board[choice].print_self() elif action == 7: player.print_symobls_count() elif action == 99: new_splay = input('Choose new splay mode for all your piles') for i in range(5): player.board[i].change_splay_mode(new_splay)
def _input_coords(game,player): """ manage the interaction with the human player :param situation: the current situation :type situation: list :param player: player :type player: player """ print(Player.get_name(player)+'('+Player.get_spec(player)+')'+" it's your turn") coords = input("coords of cell? ") coords = coords.split(',') try : x = int(coords[0]) y = int(coords[1]) if game[x][y] == '' : return (x,y) except : return _input_coords(game,player) print('illegal play, choose an empty cell') return _input_coords(game,player)
def _input_coords(situation, player): """ manage the interaction with the human player :param situation: the current situation :type situation: list :param player: player :type player: player """ print( Player.get_name(player) + '(' + Player.get_spec(player) + ')' + " it's your turn") coords = input("coords of cell? ") coords = coords.split(',') try: x = int(coords[0]) y = int(coords[1]) if isValidMove(situation, player, x, y): return (x, y) except: return _input_coords(situation, player) print('illegal play') return _input_coords(situation, player)
def play_game(player): print("\nA booming voice shakes the cave!\n" "WELCOME %s, can you find your way out? HA HA HA!" % player.get_name())
def play_game(self): passing = [3, 1, 2, 0] hand_num = 0 while max(list(self.scores.values())) < 100: for player in self._players: player.new_hand([player.get_name() for player in self._players]) deck = Deck() deck.shuffle() for player in self._players: player.add_cards_to_hand([card.name for card in deck.deal(13)]) for player in self._players: print(player.get_name(), player.get_hand()) if passing[hand_num % 4]: cards_to_pass = [player.pass_cards() for player in self._players] for i, player in enumerate(self._players): player.add_cards_to_hand(cards_to_pass[(i + passing[hand_num % 4]) % 4]) print(player.get_name(), player.get_hand()) # Player with the Two of Clubs plays first lead = 0 for i, player in enumerate(self._players): if Card(Rank.TWO, Suit.CLUBS).name in player.get_hand(): lead = i for _ in range(13): trick = [] for i in range(4): current_player = self._players[(lead + i) % 4] trick.append( Card.from_name(current_player.play_card(self._players[lead].get_name(), trick)) ) winner = (lead + resolve_trick(trick)) % 4 for player in self._players: player.collect_trick( self._players[lead].get_name(), self._players[winner].get_name(), [card.name for card in trick] ) print(f'Lead: {self._players[lead].get_name()}') print(f'Winner: {self._players[winner].get_name()}') print(f'[{trick[0]}, {trick[1]}, {trick[2]}, {trick[3]}]') lead = winner # TODO: refine this scores = [player.score() for player in self._players] for player in self._players: if max(scores) == 26: if player.score() == 0: self._scores[player.get_name()] += 26 else: self._scores[player.get_name()] += player.score() hand_num += 1 print(self._scores)
def create(): """ creates the initial situation and draws it """ sit = othello.create_game() g = othello.initSituation(sit) if ask.askplayer() == 1: p1 = Player.new_player('human', 'X') p2 = Player.new_player('computer', 'O') dif = ask.askdif() else: p1 = Player.new_player('player1', 'X') p2 = Player.new_player('player2', 'O') dif = 0 p = [p1, p2] global img global current current = p[random.randint(0, 1)] if Player.get_name(current) == 'computer' and othello.playerCanPlay( g, g, current): g = othello.clean(g) g = AlphaBeta.IA(g, current, switch_player(current, p1, p2), dif, othello) current = switch_player(current, p1, p2) win = tk.Tk() win.title('Othello') iconpath = os.path.join(os.path.dirname(os.path.abspath(__file__)), "icons") img = [ tk.PhotoImage(file=os.path.join(iconpath, "tap.gif")), tk.PhotoImage(file=os.path.join(iconpath, "noir.gif")), tk.PhotoImage(file=os.path.join(iconpath, "blanc.gif")), tk.PhotoImage(file=os.path.join(iconpath, "possible.gif")) ] b = [] for i in range(8): b.insert(i, []) for j in range(8): if g[i][j] == "O": ig = img[2] if g[i][j] == "X": ig = img[1] if g[i][j] == " ": ig = img[0] button = tk.Button(win, padx=0, pady=0, width=71, height=71, image=ig, background='green') button.grid(column=i, row=j) button.bind( "<Button-1>", partial(handler, (button.grid_info()['row']), (button.grid_info()['column']), g, p1, p2, b, dif)) b[i].insert(j, button) hints(g, b) __redraw(g, b) othello.clean(g) win.mainloop()