我目前正在做一个记忆游戏/翻转瓷砖项目。我必须编码4个不同的类,卡片,甲板,游戏和主要。下面是卡片、甲板和游戏类的代码。在编写主类代码之前,我必须先测试所有这些类。当我测试它时,它说:
"'NoneType‘对象没有’flip‘属性“
我不知道错误是从哪里来的。下面的最后3行是我测试类Game()的方法。
class Card():
#Constructor that initializes the card value and face
def __init__(self, value):
self.card_value = value
self.card_face = False
#Getter method for Card Value
def get_value(self):
return self.card_value
#Getter method for Card Face
def flip(self):
return self.card_face
#Setter method to set Card Face
def set_face(self):
self.card_face = True
class Deck():
#Constructor that initializes the number of pairs and total number of cards in the deck
def __init__(self, pairs):
self.no_of_pairs = pairs
self.tot_cards = []
for cards in range(self.no_of_pairs):
p1 = Card(cards)
self.tot_cards.append(p1)
p2 = Card(cards)
self.tot_cards.append(p2)
#Method to deal a card
def deal(self):
if self.deck_len() == 0:
return None
else:
return self.tot_cards.pop(0)
#Method to shuffle the cards in random
def shuffle_cards(self):
random.shuffle(self.tot_cards)
#Method to Return the number of cards in the deck
def deck_len(self):
return len(self.tot_cards)
class Game():
#Constructor that initializes the deck of cards and the rows and columns in the game board and populate the board
def __init__(self, rows, columns):
self.deck = Deck((rows * columns)//2)
self.rows = rows
self.columns = columns
self.board = []
for row in range(self.rows):
self.board.append([0] * self.columns)
self.populateBoard()
self.displayBoard()
#Method to create the initial 2D list of identical pairs of cards with all facing down
def populateBoard(self):
self.deck.shuffle_cards() #shuffle the cards
for column in range(self.columns):
for row in range(self.rows):
self.board[row][column]= self.deck.deal() #place the cards facing down
#Method to display the cards in the board game
def displayBoard(self):
for row in range(self.rows):
for column in range(self.columns):
#If not opened face the card down
if self.board[row][column].flip() == False:
print('X ', end="")
#If the card is open face the card up
else:
print(str(self.board[row][column].get_value()) + " ", end="")
print("") # Print newline after each row
test = Game(8,8)
test.populateBoard()
test.displayBoard()发布于 2021-11-20 06:48:12
您的错误发生在游戏类的displayBoard函数中,条件为if。该语句为:if self.board[row][column].flip() == False:
发生错误的原因是self.board仅填充了None。
IDLE和PyCharm都会以鲜红色的文本方便地显示错误发生的位置。这称为回溯。这是您的回溯:
Traceback (most recent call last):
File "C:\Users\delta\AppData\Roaming\JetBrains\PyCharmCE2021.2\scratches\scratch_4.py", line 86, in <module>
test.displayBoard()
File "C:\Users\delta\AppData\Roaming\JetBrains\PyCharmCE2021.2\scratches\scratch_4.py", line 76, in displayBoard
if self.board[row][column].flip() == False:
AttributeError: 'NoneType' object has no attribute 'flip'https://stackoverflow.com/questions/70043767
复制相似问题