我正在开发纸牌游戏。关键是当用户点击两张牌时,他们会面朝上。如果它们不一样,当他们点击第三个时,前两个消失(这还没有实现)。
我正在尝试使用变量: first_card 和 second_card 来跟踪已被点击的卡片。当用户点击卡片时,我还使用列表“公开”将值从False更改为True。
问题是,列表已更新,但变量未更新。我的意思是,当我点击第二张卡片时, 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()
答案 0 :(得分:0)
您需要定义全局状态变量,该代码崩溃并且可能不更新first_card值
import random
state = 0
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
答案 1 :(得分:0)
首先,你的it won't work unless you run it in CodeSkulptor
声明不正确,你可以在pip上找到simplegui,每个人都可以在不使用CodeSkulptor的情况下运行你的代码。我想知道获得投票的原因是什么,所以不要被他们打扰。
现在,关于你的错误...让我们考虑鼠标点击逻辑,让我们假设first_card和second_card都是在游戏开始时隐藏(值= -1)。让我们考虑一个简单的游戏逻辑,其中有两种可能的状态:
你一遍又一遍地指定无first_card = None
和second_card = None
,这是不正确的。
尝试按照这些提示再次拍摄,如果你还在努力,我会给你一个可能的解决方案。