'New to code and bad at inheritance. Trying to make randomized tictactoe AI python3
I'm trying to make an AI that plays with the player but it keeps giving me a TypeError
:
TypeError: __init__() missing 1 required positional argument: 'sign'.
from random import choice
class Player:
def __init__(self, name, sign, board = None):
self.name = name # player's name
self.sign = sign # player's sign O or X
self.board = board
def get_sign(self):
# return an instance sign
return self.sign
def get_name(self):
# return an instance name
return self.name
def choose(self, board):
# prompt the user to choose a cell
# if the user enters a valid string and the cell on the board is empty, update the board
# otherwise print a message that the input is wrong and rewrite the prompt
# use the methods board.isempty(cell), and board.set(cell, sign)
while True:
cell = input(f"{self.name}, {self.sign}: Enter a cell [A-C][1-3]:\n")
cell = cell.upper()
#checks to see if input matches to a cell and if the cell is empty
if cell == "A1" or cell == "B1" or cell == "C1" or cell == "A2" or cell == "B2" or cell == "C2" or cell == "A3" or cell == "B3" or cell == "C3":
if board.isempty(cell):
board.set(cell, self.sign)
break
else:
print("You did not choose correctly.")
else:
print("You did not choose correctly.")
class AI(Player):
def __init__(self, name, sign, board = None):
super().__init__(board)
self.sign = sign
self.name = name
def choose(self, board):
valid_moves = ["A1", "A2", "A3", "B1", "B2", "B3", "C1", "C2", "C3"]
cell = choice(valid_moves)
board.set(cell, self.sign)
I call it in another file like this:
player1 = AI("Bob", "X", board)
Solution 1:[1]
Your problem is in the inherited class AI
.
In this class, you have created __init__
with 3 parameters and inside this __init__
you are calling the __init__
of the parent class, and this parent class is Player
. But if you check the Player
class, you will see that its __init__
has 3 parameters of which two are mandatory: name
and sign
.
In the AI class, replace
super().__init__(board)
by
super().__init__(name,sign,board)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Gino Mempin |