【发布时间】:2016-08-19 09:48:46
【问题描述】:
我正在开发一款“纸牌游戏”。这个想法是,当用户可以同时显示最多两张卡片时,当他们点击第三张卡片时,前两张就会消失。稍后我会修改代码,这样如果用户点击的卡片相同,它们就会保持暴露状态。
问题是现在只有一张牌被曝光。当我点击另一张卡片时,第一张卡片会正面朝下。
这是函数,为什么不起作用?
def mouseclick(pos):
global exposed, click_count, turn
# add game state logic here
for card in range(len(deck)):
if pos[0] > card * w and pos[0] < card * w + w:
exposed[card] = True
click_count += 1
if click_count > 2:
click_count = 1
turn += 1
print click_count
else:
exposed[card] = False
if exposed[card] == True:
pass
print exposed
顺便说一句,除非您在 CodeSkulptor 中运行,否则该代码将无法运行: http://www.codeskulptor.org/#user41_BGhWSBJ6ln_0.py
# implementation of card game - Memory
import simplegui
import random
deck = range(0, 8)* 2
exposed = [False] * len(deck)
print exposed
print deck
w = 50
h = 100
WIDTH = w * 16 + 2
HEIGHT = 102
click_count = 0
turn = 0
# helper function to initialize globals
def new_game():
global exposed, click_count
random.shuffle(deck)
exposed = [False] * len(deck)
click_count = 0
print deck
print exposed
# event handlers
def mouseclick(pos):
global exposed, click_count, turn
# add game state logic here
for card in range(len(deck)):
if pos[0] > card * w and pos[0] < card * w + w:
exposed[card] = True
click_count += 1
if click_count > 2:
click_count = 1
turn += 1
print click_count
else:
exposed[card] = False
if exposed[card] == True:
pass
print exposed
# cards are 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 button and labels
frame = simplegui.create_frame("Memory", WIDTH, HEIGHT)
frame.add_button("Reset", new_game)
label = frame.add_label("Turns = " + str(turn))
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()
【问题讨论】:
-
错误出现在
else: exposed[card] = False。您将其设置为 False 以便它再次转身。通常mouseclick函数中的for循环不是最好的。简化你的逻辑。简化您的if语句