I`ve got some problem with the following task: a user enters some cells like "XXXOO__O_". I print out it then like this (kind of a matrix/board):
---------
| X X X |
| O O _ |
| _ O _ |
---------
then the user enters two coordinates from 1 to 3, for example 2 3. After that I do some checks and if cell is "_" I replace it with "X" and then print board with replaced element again.
print("Enter cells:")
cells = input()
print("---------")
print("|", cells[0], cells[1], cells[2], "|")
print("|", cells[3], cells[4], cells[5], "|")
print("|", cells[6], cells[7], cells[8], "|")
print("---------")
while True:
coord = input("Enter the coordinates:").split()
strng = "".join(coord)
is_0_3 = 0
if strng.isdigit() == True:
for c in coord:
if int(c) > 3 or int(c) <= 0:
is_0_3 = 1
if strng.isdigit() == True and len("".join(coord)) == 2:
index = (((int(coord[0]) - 1) * 3) + (int(coord[1]) + 2)) - 3 #turning usser`s coordinates #into list index
print("index", index)
mtrx = []
for y in range(len(cells)):
mtrx.append(cells[y])
is_occupied = 0
for i, cell in enumerate(mtrx):
if i == index:
print("i==index", i)
if mtrx[index] == "X" or mtrx[index] == "O":
is_occupied = 1
if strng.isdigit() == False:
print("You should enter numbers!")
elif len("".join(coord)) != 2:
print("You should enter 2 numbers!")
elif is_0_3 == 1:
print("Coordinates should be from 1 to 3!")
elif is_occupied == 1:
print("This cell is occupied! Choose another one!")
else:
print("ma[i] before", mtrx[index])
mtrx[i] = mtrx[index].replace("_", "X")
print(mtrx[i])
print("i", i)
new_mtrx = []
print("---------")
for i in range(0, 8, 3):
row = [mtrx[i], mtrx[i + 1], mtrx[i + 2]]
new_mtrx.append(row)
print(f"| {mtrx[i]} {mtrx[i + 1]} {mtrx[i + 2]} |")
print("---------")
break
The problem is that i in the last else is always 8 and the element with coordinates 3 3 is always replaced no matter what coordinates the user entered. I don't understand why... Could you explain how can I fix it, please? For user's input 2 3 index=5 and the cell is '_', but in the last for the element with coordinates 3 3 is replaced, not the element with 2 3. I need to replace the element with coordinates user entered