2016-09-30 99 views
-1

我想在Python 3 tkinter中創建一個匹配的紙牌遊戲。玩家會看到一個4x4的按鈕網格,每個按鈕都帶有一個圖像。有八對圖像。玩家點擊一個按鈕,按鈕顯示圖像;玩家點擊另一個按鈕以顯示其圖像。如果兩個按鈕顯示相同的圖像,圖像將保持到遊戲結束;否則,當我點擊另一個按鈕時,這些圖像將不再顯示。在Python中匹配對遊戲tkinter

我可以創建網格,但是,我很難讓實際的遊戲工作。以下是我迄今爲止創建的代碼。

#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

您需要創建一個ifelse語句來檢查移動的合法性,如果合法,則繼續使用腳本,否則給用戶一條消息但將其循環回用戶猜測。

+0

能否詳細說明一下? – jlammy

+0

好的。如果沒有直接向您提供代碼XD,嘗試解釋它總是很有趣,可以自行解決。基本上,一個簡單的方法,你可以做到這一點是爲每張卡片分配一個值,然後測試這些值是否匹配,如果他們沒有回到原來的位置 – TerraPhase

+0

我已經知道了,但它仍然不起作用。 – jlammy