因此,我试图完成一个简单的记忆游戏作为最后一个项目,但我遇到了一些麻烦,通过我的卡搜索和匹配他们的值用户输入。 现在代码是这样的:
import random
from Graphics import *
class Card(object):
"""A card object"""
WIDTH = 25
HEIGHT = 25
def __init__(self, x, y, n):
self.x = x
self.y = y
self.n = n
p = ((x + (Card.WIDTH/2)),(y + (Card.HEIGHT/2)))
"""Creates a card with the given value and suit."""
self.value = random.random
self.color = 0
self.face = 0
self.appearance = Rectangle(Point(x, y), Point(x + Card.WIDTH, y + Card.HEIGHT))
self.appearance.setOutline(Color(255, 255, 255))
self.appearance.setFill(Color(142, 142, 142))
self.appearance.setWidth(2)
self.appearance.draw(win)
self.text = Text(p, str(n))
self.text.setFontSize(12)
self.text.draw(win)
def showFace(self):
'''flips the card over'''
self.face = 1
ran = self.value
if ran > 0 and ran < .20:
self.appearance.setFill(Color("red"))
self.color = 3
if ran > .20 and ran < .40:
self.appearance.setFill(Color("blue"))
self.color = 4
if ran > .40 and ran < .60:
self.appearance.setFill(Color("green"))
self.color = 5
if ran > .60 and ran < .80:
self.appearance.setFill(color("yellow"))
self.color = 6
if ran > .80 and ran < .100:
self.appearance.setFill(color("purple"))
self.color = 7
def unShowFace(self):
'''flips card back'''
self.face = 0
self.appearance.setFill(Color(142, 142, 142))
class Deck(object):
def __init__(self):
self.cards = []
rows = 10
columns = 10
x = 100
y = 125
n = 1
for j in range(10):
for k in range(10):
x = x+25
c = Card(x, y, n)
self.cards.append(c)
n = n + 1
y = y+25
x = 100
win = Window("Memory Game", 500, 500)
win.setBackground(Color(64, 64, 64))
# Game title
title = Text(Point(win.getWidth()//2, 60), "Memory Mania")
title.setFill(Color(95, 115 ,200))
title.fontSize = 40
title.draw(win)
class Game():
'''Runs the memory game'''
def play(self):
'''starts the game'''
self.deck = Deck()
matches = 0
#While the game is not finished
while True:
while True: #The First Card
card1 = input("Enter number of first card")
for card in self.deck.cards:
if card.n == card1:
guess1 = card
guess1.showFace()
break
while True: # The Second Card
card2 = input("Enter number of second card")
for card in self.deck.cards:
if card.n == card2:
guess2 = card
guess2.showFace()
break
if guess1.color == guess2.color:
matches = matches + 1
if matches == 50:
break
else:
print('Not an identical pair.')
guess1.unShowFace()
guess2.unShowFace()
def main():
game = Game()
game.play()
main()
但是,当我运行代码并输入第一张卡和第二张卡的值时,我得到一个错误,上面写着“UnboundLocalError:localvariable'guess1'referenced before assignment.”有没有一种方法我没有看到像我正在尝试的那样检查卡的属性?你知道吗
线路
不保证被执行。
self.deck.cards
可以为空,或者card.n == card1
永远不可能为真。你知道吗那样的话
引发错误,因为未定义
guess1
。你知道吗(
guess2
也有同样的问题。)编辑:经过进一步检查,我很肯定问题是
返回一个字符串,因为您使用的是python3,但是
card.n
是一个整数,所以card.n == card
永远不能为真。你知道吗使用
对
card2
也是这样。你知道吗相关问题 更多 >
编程相关推荐