【问题标题】:Finding out which card a user clicked on (sprites)找出用户点击了哪张卡片(精灵)
【发布时间】:2016-02-14 21:50:20
【问题描述】:

我正在编写游戏记忆的一个版本。我有两组——一组用于“封面”,一组用于卡片本身。封面是放在卡片顶部以隐藏卡片的封面。我无法弄清楚的问题是当用户点击其中一张卡片时,我使用kill() 来移除封面卡片并且下面的卡片显示(基本上它被翻转了),但是我不能弄清楚如何在组内找到卡片下方的位置。如何知道用户点击了哪张卡片?

【问题讨论】:

  • 我建议您将标题替换为类似于您最后一句话的内容。索引只是识别卡片的一种方式。请参阅我的另一个答案。

标签: python python-3.x pygame sprite


【解决方案1】:

答案取决于您如何显示图像。这是一个使用 Button 子类的mcve。这允许实例携带识别信息并使用绑定方法作为命令。

import tkinter as tk
root = tk.Tk()

class Card(tk.Button):
    hide = 'XXX'
    def __init__(self, txt):
        super().__init__(root, text=self.hide)
        self.txt = txt
        self.exposed = False
    def flip(self):
        self['text'] = self.hide if self.exposed else self.txt
        self.exposed = not self.exposed

for i, txt in enumerate(('one', 'two')):
    card = Card(txt)
    card['command'] = card.flip
    card.grid(row=0, column=i)

#root.mainloop()  # uncomment if run on command line without -i

【讨论】:

  • 哎呀,发布此答案后,我注意到标签是 pygame 而不是 tkinter。人们经常将 tkinter 用于这样的纸牌游戏。我不知道哪些 tkinter 替代品可以适应 pygame。
猜你喜欢
  • 2015-10-23
  • 1970-01-01
  • 2012-11-13
  • 1970-01-01
  • 1970-01-01
  • 2019-05-27
  • 1970-01-01
  • 2011-11-22
相关资源
最近更新 更多