tft每日頭條

 > 遊戲

 > 蛇形填數python代碼

蛇形填數python代碼

遊戲 更新时间:2024-07-23 12:27:43
項目創作的初衷:

早期的一個項目,創作品思想源自于數字華容道(n-puzzle),是一種智力遊戲,十五數字推盤遊戲的闆上會有十五個方塊和一個大小相當于一個方塊的空位(供方塊移動之用),當15個數字依次排序并且最後一個格子為空位即代表挑戰成功。

首先把問題場景化,通過程序遊戲的形式,讓大家直觀簡單地操作,容易接受,也便于交流和傳播,同時在遊戲中思考和解決問題。

蛇形填數python代碼(51.Python益智遊戲-數字華容道)1

初始程序界面

蛇形填數python代碼(51.Python益智遊戲-數字華容道)2

挑戰成功完成的界面

實現過程和完整代碼:

程序UI沒有使用PyQt,而是用Python自帶的tkinter庫,界面元素主要使用按鈕來完成。

每次開局,都采取随機打亂方式,但是需要一些注意,必須要保證有解(兩兩交換!)

import tkinter as tk import tkinter.messagebox import random root = tk.Tk() root.geometry("400x420") root.title("益智遊戲—數字華容道") lb1=tk.Label(root,text="請移動闆上的方塊,讓所有的方塊順着數字的次序排列。",font=("",11)) lb1.grid(padx=5,pady=5,row=0,column=1,columnspan=4) count=0 lb2=tk.Label(root,text="完成步數: " str(count),font=("",10)) lb2.grid(padx=2,pady=2,row=5,column=3) id=[i for i in range(15)] imgid=[i 1 for i in range(16)] finish=[0,4,8,12,1,5,9,13,2,6,10,14,3,7,11,15] def msg(): tk.messagebox.showinfo(title="恭喜!",message="恭喜你,挑戰成功!") def move(index, t,r,c): #print(index,t,r,c) k=r-1 (c-1)*4 r0=imgid.index(16)%4 1 c0=imgid.index(16)//4 1 k0=r0-1 (c0-1)*4 #print(k,k0) def change(): buttons[k].config(text="16",bg="white",fg="white") buttons[k0].config(text=imgid[k], bg="tan",fg="black") imgid[k],imgid[k0]=imgid[k0],imgid[k] tmp=[ imgid.index(i 1) for i in range(16)] #print(tmp) global count count=count 1 lb2.config(text="完成步數: " str(count)) if(tmp==finish): msg() if(r==r0 and c0-c==1) or (r==r0 and c0-c==-1) or (r0-r==1 and c==c0) or (r0-r==-1 and c==c0): #print(k,t,"move right") change() #print(imgid) buttons = [] #随機兩兩交換,保證有解! def shuffleid(): for i in range(8): a=random.choice(id) b=random.choice(id) c=random.choice(id) d=random.choice(id) while (a==b or a==c or a==d or b==c or b==d or c==d): a=random.choice(id) b=random.choice(id) c=random.choice(id) d=random.choice(id) #print(a,b,c,d) imgid[a],imgid[b]=imgid[b],imgid[a] imgid[c],imgid[d]=imgid[d],imgid[c] #print(imgid) def init(): shuffleid() for i in imgid: n=i if(n==16): fg="white" bg="white" else: fg="black" bg="tan" r=imgid.index(i)%4 1 c=imgid.index(i)//4 1 num=imgid.index(i) button = tk.Button(root, bg=bg, text=n,fg=fg,font=("",12),width=10,height=4,relief=tk.GROOVE, command=lambda index=num, n=n,r=r,c=c: move(index, n,r,c)) button.grid(padx=4, pady=4, row=r, column=c) # Add a reference to the button to 'buttons' buttons.append(button) init() def restart(): shuffleid() global count count=0 for i in imgid: n=i if(n==16): fg="white" bg="white" else: fg="black" bg="tan" r=imgid.index(i)%4 1 c=imgid.index(i)//4 1 num=imgid.index(i) buttons[imgid.index(i)].config(text=i,bg=bg,fg=fg) #print(imgid) bt1=tk.Button(root,text="重新開始",command=restart) bt1.grid(padx=2,pady=2,row=5,column=2,columnspan=1) root.mainloop()

,

更多精彩资讯请关注tft每日頭條,我们将持续为您更新最新资讯!

查看全部

相关遊戲资讯推荐

热门遊戲资讯推荐

网友关注

Copyright 2023-2024 - www.tftnews.com All Rights Reserved