Blog :Hzy The blog of
Project address
# The center of all the grids
position = {(-200, 200): 0, (0, 200): 0, (200, 200): 0
, (-200, 0): 0, (0, 0): 0, (200, 0): 0
, (-200, -200): 0, (0, -200): 0, (200, -200): 0}
O
perhaps x
Dictionary , When it comes to 0 when , It is considered that this grid has not been used yet .Define the screen size
turtle.setup(width, height)
# Draw line
def draw_line(x, y, direction=None):
if direction:
turtle.seth(direction)
turtle.penup()
turtle.goto(x, y)
turtle.pendown()
turtle.forward(width)
# Well chessboard
def tic_tac_toe():
draw_line(-300, 100)
draw_line(-300, -100)
draw_line(-100, 300, 270)
draw_line(100, 300, 270)
turtle.update()
O
or X
Center point
, Click on
Whether the distance between them is less than the radius of the lattice , To determine which grid is clicked # Draw a circle where you click , Draw a picture x
def draw_flag(x, y):
global last_person
in_pos = None
can_write = False
for p in position.keys():
if (p[0] - x) ** 2 + (p[1] - y) ** 2 < 10000:
in_pos = p
if position.get(in_pos, None) == 0:
can_write = True
break
# This position can be circled or x
if can_write:
# draw x Or draw O, When True when , We draw circles , When False when , We draw x
if len(circle_list) > len(x_list):
circle_x = False
position[in_pos] = 'x'
last_person = 'x'
x_list.append(in_pos)
else:
circle_x = True
circle_list.append(in_pos)
position[in_pos] = 'o'
last_person = 'o'
# Draw a circle
if circle_x:
turtle.color("red")
turtle.seth(270)
turtle.penup()
turtle.goto(in_pos[0] - 100, in_pos[1])
turtle.pendown()
turtle.circle(100)
# draw x
else:
turtle.color("black")
for i in range(4):
turtle.penup()
turtle.goto(in_pos[0], in_pos[1])
turtle.pendown()
turtle.seth(45 + i * 90)
turtle.forward(sqrt(20000))
turtle.update()
who_win()
# Judge the winner
def who_win():
v = list(position.values())
# A victory situation , A horizontal line , A vertical line , Oblique line
win_1 = v[0] == v[1] == v[2] != 0 or v[3] == v[4] == v[5] != 0 or v[6] == v[7] == v[8] != 0
win_2 = v[0] == v[3] == v[6] != 0 or v[1] == v[4] == v[7] != 0 or v[2] == v[5] == v[8] != 0
win_3 = v[0] == v[4] == v[8] != 0 or v[2] == v[4] == v[6] != 0
if win_1 or win_2 or win_3:
turtle.goto(-120, 0)
turtle.write("game over,{} is winner".format(last_person), font=("Arial", 25, "normal"))
turtle.onscreenclick(None)