I need to complete the code by implementing the min function and the alpha betta pruning in order to complete the tic tac toe game using pything.
code:
# -*- coding: utf-8 -*- """ Created on: @author: """ import random from collections import namedtuple GameState = namedtuple('GameState', 'to_move, utility, board, moves') infinity = float('inf') game_result = { 1:"Player 1 Wins", -1:"Player 2 Wins", 0:"It is a Tie" } class Game: """To create a game, subclass this class and implement actions, result, utility, and terminal_test. You may override display and successors or you can inherit their default methods. You will also need to set the .initial attribute to the initial state; this can be done in the constructor.""" def actions(self, state): """Return a list of the allowable moves at this point.""" raise NotImplementedError def result(self, state, move): """Return the state that results from making a move from a state.""" raise NotImplementedError def utility(self, state, player): """Return the value of this final state to player.""" raise NotImplementedError def terminal_test(self, state): """Return True if this is a final state for the game.""" return not self.actions(state) def to_move(self, state): """Return the player whose move it is in this state.""" return state.to_move def display(self, state): """Print or otherwise display the state.""" print(state) def __repr__(self): return '<{}>'.format(self.__class__.__name__) def play_game(self, *players): """Play an n-person, move-alternating game.""" state = self.initial while True: for player in players: move = player(self, state) state = self.result(state, move) if self.terminal_test(state): self.display(state) print("Game Over.", game_result.get(self.utility(state, self.to_move(self.initial)), "Thank you for playing")) return self.utility(state, self.to_move(self.initial)) class TicTacToe(Game): """Play TicTacToe on an h x v board, with Max (first player) playing 'X'. A state has the player to move, a cached utility, a list of moves in the form of a list of (x, y) positions, and a board, in the form of a dict of {(x, y): Player} entries, where Player is 'X' or 'O'.""" def __init__(self, h=3, v=3, k=3): self.h = h self.v = v self.k = k moves = [(x, y) for x in range(1, h + 1) for y in range(1, v + 1)] self.initial = GameState(to_move='X', utility=0, board={}, moves=moves) def actions(self, state): """Legal moves are any square not yet taken.""" return state.moves def result(self, state, move): if move not in state.moves: print("\nThis is not a legal move, please play again\n") return state # Illegal move has no effect board = state.board.copy() board[move] = state.to_move moves = list(state.moves) moves.remove(move) return GameState(to_move=('O' if state.to_move == 'X' else 'X'), utility=self.compute_utility(board, move, state.to_move), board=board, moves=moves) def utility(self, state, player): """Return the value to player; 1 for win, -1 for loss, 0 otherwise.""" return state.utility if player == 'X' else -state.utility def terminal_test(self, state): """A state is terminal if it is won or there are no empty squares.""" return state.utility != 0 or len(state.moves) == 0 def display(self, state): board = state.board for x in range(1, self.h + 1): for y in range(1, self.v + 1): print(board.get((x, y), '.'), end=' ') print() def compute_utility(self, board, move, player): """If 'X' wins with this move, return 1; if 'O' wins return -1; else return 0.""" if (self.k_in_row(board, move, player, (0, 1)) or self.k_in_row(board, move, player, (1, 0)) or self.k_in_row(board, move, player, (1, -1)) or self.k_in_row(board, move, player, (1, 1))): return +1 if player == 'X' else -1 else: return 0 def k_in_row(self, board, move, player, delta_x_y): """Return true if there is a line through move on board for player.""" (delta_x, delta_y) = delta_x_y x, y = move n = 0 # n is number of moves in row while board.get((x, y)) == player: n += 1 x, y = x + delta_x, y + delta_y x, y = move while board.get((x, y)) == player: n += 1 x, y = x - delta_x, y - delta_y n -= 1 # Because we counted move itself twice return n >= self.k """ REMOVE THIS LINE def minimax_search(state, game): #Search game to determine best action; use minimax search player = game.to_move(state) # get the player to move def max_value(state): # max_value function to return v the value of a max node if game.terminal_test(state): return game.utility(state, player) v = -infinity for a in game.actions(state): v = max(v, min_value(game.result(state, a))) return v def min_value(state): # min_value function to return v the value of a min node #TO IMPLEMENT # Body of minimax: best_score = -infinity best_action = None #TO IMPLEMENT the body of the function minimax_search return best_action REMOVE THIS LINE """ """Define the players""" def random_player(game, state): """A player that chooses a legal move at random.""" return random.choice(game.actions(state)) if game.actions(state) else None def minmax_player(game, state): """A player that chooses a legal move using minmax.""" return minimax_search(state, game) def alphabeta_player(game, state): """A player that chooses a legal move using minmax with alpha-beta pruning.""" return alphabeta_search(state, game) def human_player(game, state): """Human player: make a move by querying standard input.""" print("Game board:") game.display(state) print("Available moves: {}".format(game.actions(state))) print("") move = None if game.actions(state): move_string = input('Your move? ') try: move = eval(move_string) except NameError: move = move_string else: print("no legal moves: passing turn to next player") return move # play a game of tic tac toe ttt_game = TicTacToe() ttt_game.play_game(human_player,random_player)
import numpy as np
import random
from time import sleep
def create_board():
return(np.array([[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]))
def possibilities(board):
l = []
for i in range(len(board)):
for j in range(len(board)):
if board[i][j] == 0:
l.append((i, j))
return(l)
# Select a random place for the player
def random_place(board, player):
selection = possibilities(board)
current_loc = random.choice(selection)
board[current_loc] = player
return(board)
# Checks whether the player has three
# of their marks in a horizontal row
def row_win(board, player):
for x in range(len(board)):
win = True
for y in range(len(board)):
if board[x, y] != player:
win = False
continue
if win == True:
return(win)
return(win)
# Checks whether the player has three
# of their marks in a vertical row
def col_win(board, player):
for x in range(len(board)):
win = True
for y in range(len(board)):
if board[y][x] != player:
win = False
continue
if win == True:
return(win)
return(win)
# Checks whether the player has three
# of their marks in a diagonal row
def diag_win(board, player):
win = True
for x in range(len(board)):
if board[x, x] != player:
win = False
return(win)
# Evaluates whether there is
# a winner or a tie
def evaluate(board):
winner = 0
for player in [1, 2]:
if (row_win(board, player) or
col_win(board,player) or
diag_win(board,player)):
winner = player
if np.all(board != 0) and winner == 0:
winner = -1
return winner
# Main function to start the game
def play_game():
board, winner, counter = create_board(), 0, 1
print(board)
sleep(2)
while winner == 0:
for player in [1, 2]:
board = random_place(board, player)
print("Board after " + str(counter) + " move")
print(board)
sleep(2)
counter += 1
winner = evaluate(board)
if winner != 0:
break
return(winner)
# Driver Code
print("Winner is: " + str(play_game()))
I need to complete the code by implementing the min function and the alpha betta pruning...
JAVA Only Help on the sections that say Student provide code. The student Provide code has comments that i put to state what i need help with. import java.util.Scanner; public class TicTacToe { private final int BOARDSIZE = 3; // size of the board private enum Status { WIN, DRAW, CONTINUE }; // game states private char[][] board; // board representation private boolean firstPlayer; // whether it's player 1's move private boolean gameOver; // whether...
You will create a PYTHON program for Tic-Tac-Toe game. Tic-Tac-Toe is normally played with two people. One player is X and the other player is O. Players take turns placing their X or O. If a player gets three of his/her marks on the board in a row, column, or diagonal, he/she wins. When the board fills up with neither player winning, the game ends in a draw 1) Player 1 VS Player 2: Two players are playing the game...
Please I need your help I have the code below but I need to add one thing, after player choose "No" to not play the game again, Add a HELP button or page that displays your name, the rules of the game and the month/day/year when you finished the implementation. import java.awt.*; import java.awt.event.*; import java.awt.geom.*; import javax.swing.*; import javax.swing.event.*; import java.util.Random; public class TicTacToe extends JFrame implements ChangeListener, ActionListener { private JSlider slider; private JButton oButton, xButton; private Board...
I need help finishing this excerise this is what I have: I get this output for an error: RPS_ExerciseE1.rb:171:in `+': no implicit conversion of nil into String (TypeError) from RPS_ExerciseE1.rb:171:in `display_results' from RPS_ExerciseE1.rb:89:in `play_game' from RPS_ExerciseE1.rb:240:in `block in <main>' from RPS_ExerciseE1.rb:237:in `loop' from RPS_ExerciseE1.rb:237:in `<main>' Currently, the Game class’s get_player_move method uses a regular expression to validate the player’s moves of Rock, Paper, or Scissors, rejecting any input other than one of these words. Making the player enter entire words...
In a game of Tic Tac Toe, two players take turns making an available cell in a 3 x 3 grid with their respective tokens (either X or O). When one player has placed three tokens in a horizontal, vertical, or diagonal row on the grid, the game is over and that player has won. A stalemate occurs when all the cells on the grid have been filled with tokens and neither player has achieved a win. Write a program...
JAVA TIC TAC TOE - please help me correct my code Write a program that will allow two players to play a game of TIC TAC TOE. When the program starts, it will display a tic tac toe board as below | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 The program will assign X to Player 1, and O to Player The program will ask Player 1, to...
I need help with my programming assignment. The language used should be java and the algorithm should use search trees so that you play against the computer and he chooses the best move. The tree should have all possibilities on the leaves and you could use recursion to so that it populates itself. The game can be a 3*3 board (no need the make it n*n). Please put comments so that I can understand it. Thanks The game of ‘Walls’...
The game lets players know whether they have won, lost, or tied a particular game. Modify the game so the players are told the number of games they have won, lost or tied since the start of game play. Implement this change by adding three variables named $wins, $lost, and $ties to the program's Main Script Logic section, assigning each an initial value of 0. Next, modify the analyze_results method by adding programming logic that increments the values of $wins,...
In a game of Tic Tac Toe, two players take turns making an available cell in a 3 x 3 grid with their respective tokens (either X or O). When one player has placed three tokens in a horizontal, vertical, or diagonal row on the grid, the game is over and that player has won. A stalemate occurs when all the cells on the grid have been filled with tokens and neither player has achieved a win. Write a program...
This is my code for a TicTacToe game. However, I don't know how to write JUnit tests. Please help me with my JUnit Tests. I will post below what I have so far. package cs145TicTacToe; import java.util.Scanner; /** * A multiplayer Tic Tac Toe game */ public class TicTacToe { private char currentPlayer; private char[][] board; private char winner; /** * Default constructor * Initializes the board to be 3 by 3 and...