This code has multiple design issues but the immediate one seems to be how played squares are removed from the list hody
:
hody = [1, 2, 3, 4, 5, 6, 7, 8, 9]
Squares are removed by index:
elif (k == 5) and k in hody:
# ...
del(hody[k - 1])
But once a square is removed, the indexes change as the list shrinks! You can fix this simply by global text replacing the dozen and a half lines that read:
del(hody[k - 1])
to be:
hody.remove(k)
Now we’re removing the squares by value so the order of removals doesn’t matter. But there are other problems, for example:
j = 10
# ...
for i in range(j):
This loop controls the number of moves in the game. There are only nine turns maximum, but it allows for ten moves! (j
ranges from 0 through 9.)
Let’s try to rationalize this code:
from turtle import Screen, Turtle
def draw_X(x, y):
pl2.penup()
pl2.goto(x, y)
pl2.pendown()
pl2.goto(x + 80, y - 80)
pl2.penup()
pl2.goto(x + 80, y)
pl2.pendown()
pl2.goto(x, y - 80)
def draw_0(x, y):
pl1.penup()
pl1.goto(x, y)
pl1.pendown()
pl1.circle(40)
pole = Turtle()
pole.hideturtle()
pole.speed('fastest')
pole.penup()
pole.goto(-170, 170)
pole.pendown()
for _ in range(4):
pole.forward(300)
pole.right(90)
for _ in range(2):
pole.forward(100)
pole.right(90)
pole.forward(300)
pole.left(90)
pole.forward(100)
pole.left(90)
pole.forward(300)
pole.right(90)
pole.forward(100)
pole.right(90)
hody = [1, 2, 3, 4, 5, 6, 7, 8, 9]
pl1 = Turtle()
pl1.hideturtle()
pl1.color("blue")
pl2 = Turtle()
pl2.hideturtle()
pl2.color("red")
p = input("Хто буде ходити першим X чи 0 ?: ") # who will go first? X or 0?
while hody:
k = int(input("Введіть клітинку: ")) # user choose the number of area
if k in hody:
if p.lower() == "x":
if k == 1:
draw_X(-158.89, 158.89)
elif k == 2:
draw_X(-58.89, 158.89)
elif k == 3:
draw_X(40.89, 158.89)
elif k == 4:
draw_X(-158.89, 58.89)
elif k == 5:
draw_X(-59.89, 58.89)
elif k == 6:
draw_X(40.89, 58.89)
elif k == 7:
draw_X(-158.89, -42.89)
elif k == 8:
draw_X(-59.89, -40.89)
elif k == 9:
draw_X(40.89, -40.89)
p = "0" # successful move, switch players
elif p.lower() in ("0", 'o'):
if k == 1:
draw_0(-119.39, 79.44)
elif k == 2:
draw_0(-19.39, 79.44)
elif k == 3:
draw_0(81.39, 79.44)
elif k == 4:
draw_0(-119.39, -21.44)
elif k == 5:
draw_0(-19.39, -21.44)
elif k == 6:
draw_0(81.39, -21.44)
elif k == 7:
draw_0(-119.39, -121.44)
elif k == 8:
draw_0(-19.39, -121.44)
elif k == 9:
draw_0(81.39, -121.44)
p = "x" # successful move, switch players
hody.remove(k)
screen = Screen()
screen.mainloop()
Still not complete, and still not as clean as we could make it, but should be clean enough to build the next stage of the code: scoring the game?
solved How to fix “list assignment index out of range” python3