Python 生命遊戲(tkinter版)
from tkinter import messagebox as msgbox
import tkinter as tk
import webbrowser
import random
class Lifes:
def __init__(self, rows=36, cols=36):
self.row = rows+2
self.col = cols+2
self.items = [[0]*self.col for _ in range(self.row)]
self.histroy = []
self.histroySize = 30
self.running = False
self.runningSpeed = 100
def rndinit(self, rate=0.1):
self.histroy = []
for i in range(self.row):
for j in range(self.col):
rnd = random.random()
if rnd > 1-rate:
self.items[i][j]=1
def reproduce(self):
new = [[0]*self.col for _ in range(self.row)]
self.add_histroy()
if len(self.histroy) > self.histroySize:
self.histroy.pop(0)
for i in range(self.row):
for j in range(self.col):
if i*j==0 or i==self.row-1 or j==self.col-1:
new[i][j]=0
else:
lifes=0
for m in range(i-1,i+2):
for n in range(j-1,j+2):
if m==i and n==j:
continue
lifes += self.items[m][n]
if self.items[i][j]:
if lifes==2 or lifes==3:
new[i][j]=1
else:
new[i][j]=0
else:
if lifes==3:
new[i][j]=1
for idx,narray in enumerate(new):
self.items[idx] = narray
def is_stable(self):
if len(self.histroy)<self.histroySize:
return False
arr = []
for i in self.histroy:
if i not in arr:
arr.append(i)
if len(arr)<10:
return True
def add_histroy(self, Items=None):
arr = []
if Items==None:
Items=self.items[:]
for item in Items:
b = 0
for i,n in enumerate(item[::-1]):
b += n*2**i
arr.append(b)
self.histroy.append(arr)
def drawCanvas():
global tv,rect
tv = tk.Canvas(win, width=win.winfo_width(), height=win.winfo_height())
tv.pack(side = "top")
for i in range(36):
coord = 40, 40, 760, i*20 + 40
tv.create_rectangle(coord)
coord = 40, 40, i*20 + 40, 760
tv.create_rectangle(coord)
coord = 38, 38, 760, 760
tv.create_rectangle(coord,width=2)
coord = 39, 39, 760, 760
tv.create_rectangle(coord,width=2)
coord = 38, 38, 762, 762
tv.create_rectangle(coord,width=2)
R,XY = 8,[50+i*20 for i in range(36)]
rect = [[0]*36 for _ in range(36)]
for i,x in enumerate(XY):
for j,y in enumerate(XY):
rect[i][j] = tv.create_rectangle(x-R,y-R,x+R,y+R,tags=('imgButton1'))
tv.itemconfig(rect[i][j],fill='lightgray',outline='lightgray')
tv.tag_bind('imgButton1','<Button-1>',on_Click)
def drawLifes():
R,XY = 8,[50+i*20 for i in range(36)]
if Life.running:
for i,x in enumerate(XY):
for j,y in enumerate(XY):
if Life.items[i+1][j+1]:
tv.itemconfig(rect[i][j],fill='green',outline='green')
else:
tv.itemconfig(rect[i][j],fill='lightgray',outline='lightgray')
tv.update()
Life.reproduce()
if Life.is_stable():
Life.running = False
if sum(sum(Life.items,[])):
msgbox.showinfo('Message',' 生命繁殖與湮滅進入穩定狀態!!! ')
else:
msgbox.showinfo('Message',' 生命全部湮滅,進入死亡狀態!!! ')
win.after(Life.runningSpeed, drawLifes)
def StartLife():
if sum(sum(Life.items,[])):
Life.histroy = []
Life.running = True
else:
msgbox.showinfo('Message',' 請點選小方塊填入生命細胞,或者使用隨機功能! ')
def BreakLife():
Life.running = not Life.running
if Life.running:
Life.histroy.clear()
Life.add_histroy()
def RandomLife():
Life.rndinit()
Life.running = True
def ClearLife():
Life.running = False
Life.histroy = []
Life.items = [[0]*38 for _ in range(38)]
for x in range(36):
for y in range(36):
tv.itemconfig(rect[x][y],fill='lightgray',outline='lightgray')
def btnCommand(i):
if i==0: return StartLife
elif i==1: return BreakLife
elif i==2: return RandomLife
elif i==3: return ClearLife
def on_Enter(event):
tCanvas.itemconfig(tVisit, fill='magenta')
def on_Leave(event):
tCanvas.itemconfig(tVisit, fill='blue')
def on_Release(event):
url = 'https://blog.csdn.net/boysoft2002?type=blog'
webbrowser.open(url, new=0, autoraise=True)
def on_Click(event):
x,y = (event.x-40)//20,(event.y-40)//20
if not Life.running:
if Life.items[x+1][y+1]:
tv.itemconfig(rect[x][y],fill='lightgray',outline='lightgray')
else:
tv.itemconfig(rect[x][y],fill='red',outline='red')
Life.items[x+1][y+1] = not Life.items[x+1][y+1]
def on_Close():
if msgbox.askokcancel("Quit","Do you want to quit?"):
Life.running = False
print(Copyright())
win.destroy()
def Introduce():
txt = ''' 【生命遊戲】 \n\n 生存定律:
(1) 當前細胞為湮滅狀態時,當週圍有3個存活細胞時,則迭代後該細胞變成存活狀態 ( 模擬繁殖 ) 。
(2) 當前細胞為存活狀態時,外匯跟單gendan5.com當週圍的鄰居細胞少於2個存活時,該細胞變成湮滅狀態 ( 數量稀少 ) 。
(3) 當前細胞為存活狀態時,當週圍有3個以上的存活細胞時,該細胞變成湮滅狀態 ( 數量過多 ) 。
(4) 當前細胞為存活狀態時,當週圍有2個或3個存活細胞時,該細胞保持原樣。 '''
return txt
def Copyright():
return 'Lifes Game Ver1.0\nWritten by HannYang, 2022/08/01.'
if __name__ == '__main__':
win = tk.Tk()
X,Y = win.maxsize()
W,H = 1024,800
winPos = f'{W}x{H}+{(X-W)//2}+{(Y-H)//2}'
win.geometry(winPos)
win.resizable(False, False)
win.title(' 生命遊戲 Ver1.0')
win.update()
drawCanvas()
Life = Lifes()
drawLifes()
tLabel = tk.Label(win, width=30, height=20, background='lightgray')
tLabel.place(x=780, y=38)
tLabel.config(text='\n\n\n'.join((Introduce(),Copyright())))
tLabel.config(justify=tk.LEFT,anchor="nw",borderwidth=10,wraplength=210)
tButton = [None]*4
bX,bY,dY = 835, 458, 50
txt = [' 開始 ',' 暫停 ',' 隨機 ',' 清空 ']
for i in range(4):
tButton[i] = tk.Button(win, text=txt[i], command=btnCommand(i))
tButton[i].place(x=bX, y=bY+dY*i, width=120, height=40)
tCanvas = tk.Canvas(win, width=200, height=45)
tCanvas.place(x=800,y=716)
tVisit = tCanvas.create_text((88, 22), text=u" 點此訪問 Hann's CSDN 主頁 !")
tCanvas.itemconfig(tVisit, fill='blue', tags=('btnText'))
tCanvas.tag_bind('btnText','<Enter>',on_Enter)
tCanvas.tag_bind('btnText','<Leave>',on_Leave)
tCanvas.tag_bind('btnText','<ButtonRelease-1>',on_Release)
win.protocol("WM_DELETE_WINDOW", on_Close)
win.mainloop()
來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/69946337/viewspace-2911776/,如需轉載,請註明出處,否則將追究法律責任。
相關文章
- 骷髏坑人小技巧1[python]:坑爹遊戲[tkinter]Python遊戲
- Python之Tkinter:動作Python
- Python Tkinter 簡單使用Python
- python tkinter學習(1)Python
- python tkinter如何繫結事件?Python事件
- python-Tkinter整理總結Python
- Python Tkinter PanedWindow 控制元件Python控制元件
- Python之Tkinter:動作薦Python
- 生命的遊戲遊戲
- 康威生命遊戲遊戲
- 李興球Python是男人就下一百層測試程式tkinter遊戲Python遊戲
- Python的Tkinter庫總結(1)Python
- 引:Python GUI程式設計(Tkinter)PythonGUI程式設計
- Python如何使用tkinter編寫GUI程式PythonGUI
- python-GUI之tkinter的學習PythonGUI
- Python tkinter矩形縮放測試程式Python
- tkinter模組常用引數(python3)Python
- Python Tkinter元件有哪些?Python基礎入門!Python元件
- tkinter
- Python 程式設計之Tkinter的使用01Python程式設計
- python tkinter如何獲取label內容?Python
- Python tkinter 實現 指令碼工具 GUI模版Python指令碼GUI
- Python GUI程式設計:tkinter關於ttkbootstrapPythonGUI程式設計boot
- 微課|中學生可以這樣學Python(例11.2):tkinter猜數遊戲(1)Python遊戲
- 微課|中學生可以這樣學Python(例11.2):tkinter猜數遊戲(2)Python遊戲
- 微課|中學生可以這樣學Python(例11.2):tkinter猜數遊戲(3)Python遊戲
- 微課|中學生可以這樣學Python(例11.4):tkinter版圖片檢視器Python
- import tkinter與from tkinter import *的區別Import
- [Python GUI]Python內建圖形介面tkinter--入門1PythonGUI
- Python tkinter是什麼?GUI程式設計有哪些?PythonGUI程式設計
- 教你python tkinter實現簡單計算器功能Python
- 使用 Python 的 Tkinter模組 開發 IRC 客戶端Python客戶端
- python3安裝編譯_tkinter模組丟失Python編譯
- 只用lambda演算實現FizzBuzz遊戲(Python版)遊戲Python
- Python 內建介面開發框架 Tkinter入門篇 丁Python框架
- Python 內建介面開發框架 Tkinter入門篇 甲Python框架
- Python 內建介面開發框架 Tkinter入門篇 乙Python框架
- python tkinter 視窗出現未響應處理方式Python