import turtle
turtle.speed(0)
def draw_board():
turtle.pensize(5)
turtle.pencolor('black')
for i in range(2):
turtle.penup()
turtle.goto(-300, 100 - 200 * i)
turtle.pendown()
turtle.forward(600)
for i in range(2):
turtle.penup()
turtle.goto(-100 + 200 * i, 300)
turtle.pendown()
turtle.goto(-100 + 200 * i, - 300)
def draw_x(x, y):
turtle.penup()
turtle.goto(x - 50, y - 50)
turtle.pendown()
turtle.pencolor('blue')
turtle.setheading(45)
for _ in range(4):
turtle.forward(70)
turtle.backward(70)
turtle.right(90)
def draw_o(x, y):
turtle.penup()
turtle.goto(x - 50, y - 50)
turtle.pendown()
turtle.pencolor('red')
turtle.circle(50)
def check_win(board):
for row in board:
if row.count('X') == 3 or row.count('O') == 3:
return True
for col in range(3):
col_list = [board[0][col], board[1][col], board[2][col]]
if col_list.count('X') == 3 or col_list.count('O') == 3:
return True
diag1 = [board[0][0], board[1][1], board[2][2]]
diag2 = [board[0][2], board[1][1], board[2][0]]
if diag1.count('X') == 3 or diag1.count('O') == 3 or diag2.count('X') == 3 or diag2.count('O') == 3:
return True
return False
def play_game():
board = [[' ', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' ']]
turn = 'X'
draw_board()
while True:
if turn == 'X':
x, y = turtle.pos()
x = int((x + 300) // 200) * 200 - 300
y = int((y - 300) // - 200) * 200 + 300
row = int((y - 300) // - 200)
col = int((x + 300) // 200)
if board[row][col] == ' ':
board[row][col] = 'X'
draw_x(x + 100, y - 100)
if check_win(board):
print('X获胜!')
break
turn = 'O'
else:
x, y = turtle.pos()
x = int((x + 300) // 200) * 200 - 300
y = int((y - 300) // - 200) * 200 + 300
row = int((y - 300) // - 200)
col = int((x + 300) // 200)
if board[row][col] == ' ':
board[row][col] = 'O'
draw_o(x + 100, y - 100)
if check_win(board):
print('O获胜!')
break
turn = 'X'
turtle.speed(1)
play_game()
turtle.done()