我正在尝试在Python 3 tkinter中创建一个匹配的纸牌游戏。播放器呈现4x4网格按钮,每个按钮带有图像。有八对图像。玩家点击按钮,按钮显示图像;玩家点击另一个按钮来显示其图像。如果两个按钮显示相同的图像,则图像将保持到游戏结束;否则,当我点击另一个按钮时,这两个图像都将停止显示。
我可以创建网格,但是,我无法让实际的游戏发挥作用。以下是我目前创建的代码。
#Import all necessary modules.
from tkinter import *
from tkinter import ttk
import random
#Imnporting shuffle allows us to shuffle a list.
from random import shuffle
import time
#Create canvas and assign it to variable root.
root = Tk()
#Making photo accessible
def stimage(file):
return PhotoImage(width=100,height=100,file=file)
clicks=[]
clickCount=0
faceUp=[]
score=0
back = PhotoImage(width=100, height=100, file="blank space.gif")
images = [stimage("homer.gif"), stimage("ducky.gif"), stimage("hulk.gif"), stimage("torus.gif"), stimage("ronaldo-moth.gif"), stimage("beyonce.gif"), stimage("monkey.gif"), stimage("kim.gif")]
#Function returns a button, equipped with a command that changes its background colour. It takes the argument image.
def button(n):
#Create a button with parent root, and a red colour for image. This will be the back of each card.
button = Button(root,height=100,width=100, image=back)
#Command for button. Flips over when clicked.
def flip():
global clickCount
global faceUp
clickCount+=1
#Make the card display an image.
button.config(image=images[n])
#If image of button is displayed, append to list faceUp
if button.cget("image")!=back:
#Append the button object and image index n to list faceUp
faceUp.append([button,n])
if clickCount==2:
clickCount=0
if faceUp[0][1]==faceUp[1][1]:
print("Hello")
else:
button.config(image=back)
faceUp=[]
button.config(command=flip)
return button
#Create a list of coordinates that the buttons will occupy.
coord = [[a,b] for a in range(1,5) for b in range(1,5)]
#Randomise coordinates so buttons appear in random places.
random.shuffle(coord)
buttons=[]
for i in range(8):
buttons.append(button(i))
buttons[2*i].grid(row=coord[i][0], column=coord[i][1])
buttons.append(button(i))
buttons[2*i+1].grid(row=coord[i+8][0], column=coord[i+8][1])
它不起作用,因为如果单击一个不匹配的对,该按钮就无法显示其图像。
有人可以帮忙吗?
答案 0 :(得分:0)
你需要创建一个ifelse语句来检查移动的合法性,如果它是合法的,继续使用脚本,如果否则给用户一个消息但是将其循环回用户猜测。