【发布时间】:2021-08-15 05:24:28
【问题描述】:
我正在尝试用 Python 制作井字游戏,其中我使用了两个单独的文件。每个都有不同的代码和单独的类,我试图调用它们。但是,每次我尝试这样做时,都会收到此错误:
def __init__(self, letter): super().__init__(letter)
TypeError: object.__init__() takes exactly one argument (the instance to initialize)
为什么会这样?我已经导入了正确的文件(如下)并使用代码(下面)来调用它。
from player import NormalPlayer, ComputerPlayer
--
if __name__ == "__main__":
x_player = NormalPlayer("X")
o_player = ComputerPlayer("O")
ttt = TicTacToe()
play(ttt,
x_player,
o_player,
print_game = True)
我没有包含它,但是如果您需要我提供这两个文件中的所有代码,请告诉我。但是,如果您从这段代码中知道我的错误是什么,请告诉我。谢谢!
# Recognise the player as an object, with a specific letter (X or O)
class Player:
# Set the player's letter (noughts or crosses)
def __init__(self, letter): self.letter = letter
# Turn-based system
def get_move(self, game): pass
# Use the inheritance of classes to create a computer player that uses the 'Player' class
class ComputerPlayer:
# Set the computer's letter with teh super class
def __init__(self, letter): super().__init__(letter)
# Turn-based system, get a random move from all open possibilities
def get_move(self, game):
choice = random.choice(game.open_moves())
return choice
# Use the inheritance of classes for the user object that uses the 'Player' class
class NormalPlayer:
# Set the user's letter with the super class
def __init__(self, letter): super().__init__(letter)
# Turn-based system, get the player's movement choice
def get_move(self, game):
# Player's choice must first be verified
verified = False
# The spot value of the move the player wants to make
value = None
# Ask for the player's move
while not verified:
choice = input(self.letter + "\s turn. Which spot do you want to play? ")
# Check if the player's choice is valid...
try:
# Turn the input into an integer
value = int(choice)
# If the spot value is not available, catch the error and tell the player
if value not in game.open_moves():
raise ValueError
# ...if it is, then announce it
except ValueError:
# If the choice was invalid, have the player decide their move again
print("The spot value is not valid. Please choose another spot.")
return value
【问题讨论】:
-
另外,似乎有些人对这篇文章投了反对票。我不确定为什么会这样,因为我已经提供了必要的信息并收到了回复。如果一个人可以理解我的问题并回答它,为什么它会被否决?很清楚并提供了我正在使用的代码。如果您投了反对票,请告诉我我可以做些什么来使这一点更清楚。