私はカードゲームに取り組んでいます。ポイントは、ユーザーが2枚のカードをクリックすると、カードが上になることです。それらが同じでない場合、3番目のものをクリックすると、最初の2つが消えます(これはまだ実装されていません)。この変数が更新されないのはなぜですか
私は変数に使用しようとしている:first_cardとsecond_cardをクリックされているカードを追跡します。また、ユーザーがカードをクリックしたときに「公開」の値をFalseからTrueに変更するリストを使用しています。
問題は、リストが更新されるが、変数が更新されないということです。つまり、2番目のカードをクリックすると、first_cardの値はであり、値はです。これは変数を初期化した値です。なぜこうなった?
はとにかく、ここのコードは(あなたがCodeSkulptorでそれを実行しない限り、それは動作しません)です。 http://www.codeskulptor.org/#user41_RwBwWy2tSI_2.py
# implementation of card game - Memory
import simplegui
import random
deck = range(0, 8)* 2
exposed = [False] * len(deck)
print exposed
w = 50
h = 100
WIDTH = w * 16 + 2
HEIGHT = 102
first_card = 0
second_card = 0
# helper function to initialize globals
def new_game():
global exposed, state
random.shuffle(deck)
exposed = [False] * len(deck)
state = 0
print deck
print exposed
# define event handlers
def mouseclick(pos):
global state, exposed, first_card, second_card
first_card = None
second_card = None
position = pos[0] // 50
for index in range(len(deck)):
if position == index and exposed[index] != True:
if state == 0:
#exposed = [False] * len(deck)
exposed[position] = True
first_card = position
state = 1
elif state == 1:
#exposed = [False] * len(deck)
exposed[index] = True
second_card = index
state = 2
elif state == 2:
#exposed = [False] * len(deck)
exposed[index] = True
second_card = first_card
first_card = index
state = 1
print state
print "first card", first_card
print "second card", second_card
print exposed
# cards are logically 50x100 pixels in size
def draw(canvas):
line = 1
x = 1
y = 1
for i in range(len(deck)):
if exposed[i] == True:
canvas.draw_text(str(deck[i]), [(0.3* w) + w * i, (y + h) * 0.66], 40, "Black")
else:
canvas.draw_polygon([[x, y], [x + w, y], [x + w, y + h], [x, y + h]], line, "White", '#55aa55')
x += w
# create frame and add a button and labels
frame = simplegui.create_frame("Memory", WIDTH, HEIGHT)
frame.add_button("Reset", new_game)
label = frame.add_label("Turns = ")
frame.set_canvas_background("White")
# register event handlers
frame.set_mouseclick_handler(mouseclick)
frame.set_draw_handler(draw)
# get things rolling
new_game()
frame.start()
mouseclick関数の先頭には、必ずNoneに設定されているので、確かに。 –
* "CodeSkulptorで実行しない限り動作しません" * - なぜですか?あなたはそうすることができますか? – jonrsharpe
あなたは単純なGUIライブラリを必要としません。そのコードは、あなたが彼にdownvotingされている痛みのあるemabarassingをデバッグするのは簡単ですmouseclickメソッドにいくつかのランダムなタプルのpos値を追加し、彼を助けてください – lapinkoira