Tic-Tac-Toe

Report
Posts
1
Registration date
Sunday April 11, 2021
Status
Member
Last seen
April 11, 2021
-
Hello,

Please tell me what is my mistake and how to fix it? I need to define a play method that will take an integer from 0 to 8 as a parameter. Depending on the player whose turn it is to play, this method will call play1 or play2 on the cell corresponding to an integer. passed as an argument. Then you will need to change the value of the turn attribute so that the next player can play.


class Cell:
def __init__ (self):
self.occupied = ' '

def play1(self):
if (self.occupied == ' '):
self.occupied = 'X'
else:
print('Select another cell')

def play2(self):
if (self.occupied == ' '):
self.occupied = '0'
else:
print('Select another cell')

class Board:
def __init__(self):
cell1 = Cell()
cell2 = Cell()
cell3 = Cell()
cell4 = Cell()
cell5 = Cell()
cell6 = Cell()
cell7 = Cell()
cell8 = Cell()
cell9 = Cell()
self.grid = [cell1, cell2, cell3, cell4, cell5, cell6, cell7, cell8, cell9]
self.turn = 1
def __str__ (self):
return self.grid[0].occupied.__str__() + '|' + self.grid[1].occupied.__str__() + '|' + self.grid[2].occupied.__str__() + '\n'+\
self.grid[3].occupied.__str__() + '|' + self.grid[4].occupied.__str__() + '|' + self.grid[5].occupied.__str__() + '\n'+\
self.grid[6].occupied.__str__() + '|' + self.grid[7].occupied.__str__() + '|' + self.grid[8].occupied.__str__()
def play(self,i = range(0,9)):
for cell in self.grid[i].occupied:
if (self.turn == 1):
cell.play()
self.turn = 2
elif (self.turn ==2):
cell.play2()
self.turn = 1


board = Board()
board.play(3)
board.play(2)


print(board)


When running the code, I get the following error

AttributeError Traceback (most recent call last)
<ipython-input-18-aacd15a3412f> in <module>
43
44 board = Board()
---> 45 board.play(3)
46 board.play(2)
47 board.play(4)

<ipython-input-18-aacd15a3412f> in play(self, i)
35 for cell in self.grid[i].occupied:
36 if (self.turn == 1):
---> 37 cell.play()
38 self.turn = 2
39 elif (self.turn ==2):

AttributeError: 'str' object has no attribute 'play'

Thanks!