最終的なプロジェクトとして単純なメモリゲームを完成させようとしていますが、カードを検索してユーザー入力値と照合する際に問題が発生しました。前に参照ローカル変数 『guess1を』:Pythonのクラス属性と値の一致
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()
私は、コードを実行すると、しかし、および入力値は、第1および第2のカードのために、私はUnboundLocalError」というエラーが表示されます。コードは今のように見える何 はこれです割り当て。"私がしようとしているようにカードの属性を確認する方法がありますか?
ありがとうございました!私の考えはself.deck = Deckと書かれていました。そこに作成したリストが引き継がれます。これは本当ですか?私はユーザーが整数以外の何かを入力した場合、問題があることを知っています。すぐにチェックを追加するつもりですが、数字を入力すると同じエラーが発生します –
@ElainaTaylorは私の編集を参照してください – timgeb