Question

1. Use Turtle Graphics to create a tic tac toe game in Python. Write a Python program that allows for one player vs computer to play tic tac toe game, without using turtle.turtle

1. Use Turtle Graphics to create a tic tac toe game in Python. Write a Python program that allows for one player vs computer to play tic tac toe game, without using turtle.turtle

0 0
Add a comment Improve this question Transcribed image text
✔ Recommended Answer
Answer #1

Please find the code below::

回StudentProcess | accountClass tic tac toe using turtle 1 import random 2 import time 4 import turtle as t 5 class TicTacToeU

|回accountClass | ] P Studentprocess tic tac toe using turtle x def draw_grid(self): 41 42 Draw the playing grid. for cや ▼ 回StudentProcess X |回accountClass tic tac toe using turtle x 81 class HumanPlayer (Player): 82 player_typehuman 84 85 clStudentProcess accountClass tic tac toe using turtle X self.bot_game() 121 122 123 124 125 126 127 128 def human_game(self, xtic tac toe using turtle X |回accountClass 回StudentProcess return 161 162 163 164 165 self.players.reverse() self.end_game( tStudentProcess accountClassE tic tac toe using turtle X position1 position2 position3 position = 4 position = 5 position6 pos回StudentProcess | accountClass # Play on a new board new_board -board.copy new board[pos] - turn # Score the board if self.chE StudentProcess D tic tac toe using turtle 2 accountClass return (best_pos, max_score) 262 263 264 265 266 267 268 269 270 2

import random
import time

import turtle as t
class TicTacToeUI:
def __init__(self):
self.wn = t.Screen()
self.wn.title("Welcome to Tic Tac Toe!")
# Turtles
self.t_grid = t.Turtle()
self.t_marks = t.Turtle()
self.t_top_text = t.Turtle()
self.t_bottom_text = t.Turtle()
for turtle in self.wn.turtles():
turtle.hideturtle()
turtle.speed(0)
self.t_grid.pensize(2)
self.t_marks.pensize(4)
# Middle coordinates of the 9 grid sections
self._mid_cors = [(-150, 150), (0, 150), (150, 150), (-150, 0), (0, 0),
(150, 0), (-150, -150), (0, -150), (150, -150)]
# Move text writing turtles to their positions
self._mv(self.t_top_text, 0, 275)
self._mv(self.t_bottom_text, 0, -295)
  
def _mv(self, turtle, x, y):
turtle.pu()
turtle.goto(x, y)
turtle.pd()

def _draw_x(self, x, y):
self._mv(self.t_marks, x + 50, y + 50)
self.t_marks.goto(self.t_marks.xcor() - 100, self.t_marks.ycor() - 100)
self._mv(self.t_marks, self.t_marks.xcor(), self.t_marks.ycor() + 100)
self.t_marks.goto(self.t_marks.xcor() + 100, self.t_marks.ycor() - 100)

def _draw_o(self, x, y):
self._mv(self.t_marks, x, y - 50)
self.t_marks.circle(50)

def draw_grid(self):
"""Draw the playing grid."""
for cor in [75, -75]:
self._mv(self.t_grid, -225, cor)
self.t_grid.setx(225)
self._mv(self.t_grid, cor, 225)
self.t_grid.sety(-225)

def mark(self, mark, position, color='black'):
"""Draw the given mark ('x' or 'o') at the given position in the
given color."""
self.t_marks.pencolor(color)
cor = self._mid_cors[position]
if mark == 'x':
self._draw_x(*cor)
else:
self._draw_o(*cor)

def display(self, text, position, color='black'):
"""Display text at the given position ('top' or 'bottom') in the
given color.
"""
t_text = self.t_top_text if position == 'top' else self.t_bottom_text
t_text.clear()
t_text.pencolor(color)
t_text.write(text, False, 'center', ('Arial', 20, 'normal'))


class Player:
"""Base player class to be used by HumanPlayer and BotPlayer."""
def __init__(self, name, mark):
"""Initialize a player with the given name and mark."""
if mark not in ['x', 'o']:
raise ValueError("player mark must be 'x' or 'o'")
self.name = name
self.mark = mark
self.color = 'blue' if mark == 'x' else 'red'
self.wins = 0


class HumanPlayer(Player):
player_type = "human"


class BotPlayer(Player):
player_type = "bot"
  

start_time = 0
class TicTacToe:
def __init__(self, player1, player2):
"""Initialize a game of tic tac toe with the given players
(HumanPlayer or BotPlayer objects). The player with the first
move alternates each game, starting with player1.
"""
if player1.mark == player2.mark:
raise ValueError("players must not use the same mark")
self.p1 = player1
self.p2 = player2
self.turn_order = [self.p1, self.p2]
self.board = [None] * 9
self.ties = 0
self.win_lines = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6],
[1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6]]
self.UI = TicTacToeUI()
self.UI.draw_grid()
self.print_stats()
self.start_game()
self.UI.wn.mainloop()
  
  
def start_game(self):
"""Call the correct game function based on the player types."""
self.players = self.turn_order.copy()
start_time = time.clock()
first = self.players[0]
if all(player.player_type == 'human' for player in self.players):
self.UI.display(first.name, 'top', first.color)
self.UI.wn.onclick(self.human_game)
elif all(player.player_type == 'bot' for player in self.players):
self.bot_game()
else:
if first.player_type == 'bot':
self.bot_take_turn(first)
self.players.reverse()
self.UI.wn.onclick(self.human_bot_game)

def human_game(self, x, y):
"""Start a game with two human players. Accepts the coordinates
of a user click passed by an onclick call.
"""
# Remove event binding
self.UI.wn.onclick(None)
# Get the board section of the clicked point
pos = self.get_position(x, y)
# Exit if click is outside the grid or the grid section isn't empty
if pos is None or self.board[pos] is not None:
self.UI.wn.onclick(self.human_game)
return
player = self.players[0]
self.take_turn(player, pos)
if self.check_if_won(self.board, player.mark):
self.end_game(player)
return
elif None not in self.board:
self.end_game('tie')
return
self.players.reverse()
# Reactivate event binding and display who's turn it is
self.UI.wn.onclick(self.human_game)
self.UI.display(self.players[0].name, 'top', self.players[0].color)

def bot_game(self):
"""Start a game with two bot players. Should result in a tie
every time.
"""
while None in self.board:
self.bot_take_turn(self.players[0])
if self.check_if_won(self.board, self.players[0].mark):
self.end_game(self.players[0])
return
self.players.reverse()
self.end_game('tie')

def human_bot_game(self, x, y):
"""Start a game with a human and bot player. Accepts the
coordinates of a user click passed by an onclick call.
"""
self.UI.wn.onclick(None)
usr_pos = self.get_position(x, y)
if usr_pos is None or self.board[usr_pos] is not None:
self.UI.wn.onclick(self.human_bot_game)
return
for player in self.players:
if player.player_type == 'human':
self.take_turn(player, usr_pos)
else:
self.bot_take_turn(player)
if self.check_if_won(self.board, player.mark):
self.end_game(player)
return
elif None not in self.board:
self.end_game('tie')
return
self.UI.wn.onclick(self.human_bot_game)
  
  
def print_stats(self):
"""Print or update the stats text."""
stats_text = (
f"{self.p1.name} ({self.p1.mark}): {self.p1.wins} Ties: "
f"{self.ties} {self.p2.name} ({self.p2.mark}): {self.p2.wins}")
self.UI.display(stats_text, 'bottom')
  

def get_position(self, x, y):
"""Return the grid section (0-8) of the given coordinates."""
if x > -225 and x < -75 and y > 75 and y < 225:
position = 0
elif x > -75 and x < 75 and y > 75 and y < 225:
position = 1
elif x > 75 and x < 225 and y > 75 and y < 225:
position = 2
elif x > -225 and x < -75 and y > -75 and y < 75:
position = 3
elif x > -75 and x < 75 and y > -75 and y < 75:
position = 4
elif x > 75 and x < 225 and y > -75 and y < 75:
position = 5
elif x > -225 and x < -75 and y > -225 and y < -75:
position = 6
elif x > -75 and x < 75 and y > -225 and y < -75:
position = 7
elif x > 75 and x < 225 and y > -225 and y < -75:
position = 8
else:
position = None
return position

def take_turn(self, player, position):
"""Update the board with player's move at the given position."""
self.board[position] = player.mark
print(player.name, "marks section", position)
self.UI.mark(player.mark, position, player.color)

def bot_take_turn(self, player):
"""Take a turn with the given player at the position chosen by
the minimax algorithm.
"""
self.minimax_calls = 0
pos, score = self.minimax_choose_pos(self.board, player.mark)
print(f"Minimax score: {score}, function calls: {self.minimax_calls}")
self.take_turn(player, pos)

def minimax_choose_pos(self, board, turn):
self.minimax_calls += 1
opponent = 'o' if turn == 'x' else 'x'
empty_pos = [pos for pos in range(9) if not board[pos]]
max_score = -10
for pos in empty_pos:
# Play on a new board
new_board = board.copy()
new_board[pos] = turn
# Score the board
if self.check_if_won(new_board, turn):
score = 1
elif self.check_if_won(new_board, opponent):
score = -1
elif None not in new_board:
score = 0
else:
# Game is not over, recursively check child nodes
score = -self.minimax_choose_pos(new_board, opponent)[1]
# Maximize the score
if score == 1:
# 1 is the best possible score so we can stop searching
return (pos, score)
if score > max_score:
best_pos = pos
max_score = score
return (best_pos, max_score)

def check_if_won(self, board, mark):
"""Return True if the player with the given mark has won."""
return any(all(board[p] == mark for p in l) for l in self.win_lines)

def end_game(self, winner):
if winner == 'tie':
self.ties += 1
msg = "Tie Game"
color = 'black'
else:
winner.wins += 1
msg = "{} Wins!".format(winner.name)
color = winner.color
self.UI.display(msg, 'top', color)
print(msg, "\n")
self.print_stats()
self.UI.wn.onclick("")
time.sleep(1)
self.UI.display("Time took "+str(time.clock() - start_time)+" seconds", 'top')
self.UI.wn.onclick(self.reset)

def reset(self, *_): # Ignore coordinates from onclick call
"""Clear game over text, reset board, and start a new game."""
self.UI.wn.onclick(None)
self.UI.t_top_text.clear()
self.UI.t_marks.clear()
self.UI.display("", 'top')
self.board = [None] * 9
self.turn_order.reverse()
self.start_game()


def main():
"""Initialize two players and a game of tic tac toe."""
p1 = HumanPlayer("Player", 'x')
p2 = BotPlayer("Bot", 'o')
game = TicTacToe(p1, p2)


if __name__ == '__main__':
main()

output:

py tio Welcome to Tic Tac Toe! tio Time took 3.260615794871795 seconds tio Player (x): 0 Ties: 0 Bot (o):1

Add a comment
Know the answer?
Add Answer to:
1. Use Turtle Graphics to create a tic tac toe game in Python. Write a Python program that allows for one player vs computer to play tic tac toe game, without using turtle.turtle
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Similar Homework Help Questions
  • 1. Use Turtle Graphics to create a tic tac toe grid in Python. Write a Python...

    1. Use Turtle Graphics to create a tic tac toe grid in Python. Write a Python program that prints a tic tac toe grid. Use Turtle Graphics to create the graphic.

  • 18. Tic-Tac-Toe Game rite a program that allows two players to play a game of tic-tac-toe. Use di...

    18. Tic-Tac-Toe Game rite a program that allows two players to play a game of tic-tac-toe. Use dimensional char array with three rows and three columns as the game board. Each element of the array should be initialized with an asterisk (*). The program should run a loop that does the following: Write . Displays the contents of the board array. . Allows player 1 to select a location on the board for an X. The program should ask the...

  • (Game: play a tic-tac-toe game) In a game of tic-tac-toe, two players take turns marking an...

    (Game: play a tic-tac-toe game) In a game of tic-tac-toe, two players take turns marking an available cell in a 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 draw (no winner) occurs when all the cells in the grid have been filled with tokens and neither player has achieved a win. Create...

  • (Tic-Tac-Toe) Create a class Tic-Tac-Toe that will enable you to write a program to play Tic-Tac-Toe....

    (Tic-Tac-Toe) Create a class Tic-Tac-Toe that will enable you to write a program to play Tic-Tac-Toe. The class contains a private 3-by-3 two-dimensional array. Use an enumeration to represent the value in each cell of the array. The enumeration’s constants should be named X, O and EMPTY (for a position that does not contain an X or an O). The constructor should initialize the board elements to EMPTY. Allow two human players. Wherever the first player moves, place an X...

  • I need to create a Tic Tac Toe program in C++. These are the requirements Write...

    I need to create a Tic Tac Toe program in C++. These are the requirements Write a program that allows the computer to play TicTacToe against a human player or allow two human players to play one another. Implement the following conditions: The player that wins the current game goes first in the next round, and their symbol is X. The other player will be O. Keep track of the number of games played, wins, and draws for each player....

  • PYTHON Exercise 2. Tic-Tac-Toe In this exercise we are going to create a Tic-Tac-Toe game. 1....

    PYTHON Exercise 2. Tic-Tac-Toe In this exercise we are going to create a Tic-Tac-Toe game. 1. Create the data structure – Nine slots that can each contain an X, an O, or a blank. – To represent the board with a dictionary, you can assign each slot a string-value key. – String values in the key-value pair to represent what’s in each slot on the board: ■ 'X' ■ 'O' ■ ‘ ‘ 2. Create a function to print the...

  • Please make this into one class. JAVA Please: Tic Tac Toe class - Write a fifth...

    Please make this into one class. JAVA Please: Tic Tac Toe class - Write a fifth game program that can play Tic Tac Toe. This game displays the lines of the Tic Tac Toe game and prompts the player to choose a move. The move is recorded on the screen and the computer picks his move from those that are left. The player then picks his next move. The program should allow only legal moves. The program should indicate when...

  • Write a program to Simulate a game of tic tac toe in c#

    Write a program to Simulate a game of tic tac toe. A game of tic tac toe has two players. A Player class is required to store /represent information about each player. The UML diagram is given below.Player-name: string-symbol :charPlayer (name:string,symbol:char)getName():stringgetSymbol():chargetInfo():string The tic tac toe board will be represented by a two dimensional array of size 3 by 3 characters. At the start of the game each cell is empty (must be set to the underscore character ‘_’). Program flow:1)    ...

  • Tic-Tac-Toe Game Write a program that allows two players to play a game of tic-tac-toe. Use...

    Tic-Tac-Toe Game Write a program that allows two players to play a game of tic-tac-toe. Use a two-dimensional char array with three rows and three columns as the game board. Each element of the array should be initialized with an asterisk (*). The program should run a loop that does the following: Displays the contents of the board array. Allows player 1 to select a location on the board for an X. The program should ask the user to enter...

  • You will create a PYTHON program for Tic-Tac-Toe game. Tic-Tac-Toe is normally played with two people....

    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...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT