
今天给大家分享几个有趣的Python练手项目实例,希望对Python初学者有帮助哈~
一、经典的俄罗斯方块

1. 绑定功能
1 # 绑定功能
2 class App(Frame):
3 def __init__(self,master):
4 Frame.__init__(self)
5 master.bind('<Up>',self.Up)
6 master.bind('<Left>',self.Left)
7 master.bind('<Right>',self.Right)
8 master.bind('<Down>',self.Down)
9
10 master.bind('<space>',self.Space)
11 master.bind('<Control-Shift-Key-F12>',self.Play)
12 master.bind('<Key-P>',self.Pause)
13 master.bind('<Key-S>',self.StartByS)
14
15 # rgb颜色值
16 self.backg="#%02x%02x%02x" % (120,150,30) #大背景
17 self.frontg="#%02x%02x%02x" % (40,120,150) #下一个形状颜色
18 self.nextg="#%02x%02x%02x" % (150,100,100) #小背景
19 self.flashg="#%02x%02x%02x" % (210,130,100) #炸的颜色
20
21 self.LineDisplay=Label(master,text='Lines: ',bg='black',fg='red')
22 self.Line=Label(master,text='0',bg='black',fg='red')
23 self.ScoreDisplay=Label(master,text='Score: ',bg='black',fg='red')
24 self.Score=Label(master,text='0',bg='black',fg='red')
25 self.SpendTimeDisplay=Label(master,text='Time: ',bg='black',fg='red')
26 self.SpendTime=Label(master,text='0.0',bg='black',fg='red')
27
28 self.LineDisplay.grid(row=HEIGHT-2,column=WIDTH,columnspan=2)
29 self.Line.grid(row=HEIGHT-2,column=WIDTH+2,columnspan=3)
30 self.ScoreDisplay.grid(row=HEIGHT-1,column=WIDTH,columnspan=2)
31 self.Score.grid(row=HEIGHT-1,column=WIDTH+2,columnspan=3)
32 self.SpendTimeDisplay.grid(row=HEIGHT-4,column=WIDTH,columnspan=2)
33 self.SpendTime.grid(row=HEIGHT-4,column=WIDTH+2,columnspan=3)
34
35 self.TotalTime=0.0
36 self.TotalLine=0
37 self.TotalScore=0
38
39 #游戏结束
40 self.isgameover=FALSE
41 #暂停
42 self.isPause=FALSE
43 #开始
44 self.isStart=FALSE
45 self.NextList=[] #整个小背景
46 self.NextRowList=[] #一行小背景
47
48 self.px=0
49 self.py=0 #记录方块参考点
50
51 #渲染小背景
52 r=0;c=0
53 for k in range(4*4):
54 LN=Label(master,text=' ',bg=str(self.nextg),fg='white',relief=FLAT,bd=3)
55 LN.grid(row=r,column=WIDTH+c,sticky=N+E+S+W)
56 self.NextRowList.append(LN)
57 c=c+1
58 if c>=4:
59 r=r+1;c=0
60 self.NextList.append(self.NextRowList)
61 self.NextRowList=[]
62
63 #渲染大背景
64 self.BlockList=[]
65 self.BlockRowList=[]
66 self.LabelList=[]
67 self.LabelRowList=[]
68 row=0;col=0
69 for i in range(HEIGHT*WIDTH):
70 L=Label(master,text=' ',bg=str(self.backg),fg='white',relief=FLAT,bd=4)
71 L.grid(row=row,column=col,sticky=N+E+S+W)
72 L.row=row;L.col=col;L.isactive=PASSIVE
73 self.BlockRowList.append(0); #大背景每个格子初始化为0值
74 self.LabelRowList.append(L)
75 col=col+1
76 if col>=WIDTH:
77 row=row+1;col=0
78 self.BlockList.append(self.BlockRowList)
79 self.LabelList.append(self.LabelRowList)
80 self.BlockRowList=[]
81 self.LabelRowList=[]
82
83 #file
84 fw=open('text.txt','a')
85 fw.close()
86 hasHead=FALSE
87 f=open('text.txt','r')
88 if f.read(5)=='score':
89 hasHead=TRUE
90 f.close()
91 self.file=open('text.txt','a')
92 if hasHead==FALSE:
93 self.file.write('score line time scorePtime linePtime scorePline date/n')
94 self.file.flush()
95
96 self.time=1000
97 self.OnTimer()
2. 实现俄罗斯方块的翻转
1 # 俄罗斯方块的翻转
2 def Up(self,event):
3 BL=self.BlockList #格子的值
4 LL=self.LabelList #格子Label
5
6 Moveable=TRUE #是否可旋转
7
8 #代码编写开始
9 nowStyle = style[self.xnow][(self.ynow)]
10 newStyle = style[self.xnow][(self.ynow+1)%4] #算出下一俄罗斯方块
11 self.ynow = (self.ynow+1)%4 #此行代码非常重要,否则响应UP时,只能变第一次
12
13 print("nowStyle:"+str(nowStyle)+"=====>>newStyle:"+str(newStyle))
14
15 #根据现有形状中每个label的坐标计算出旋转后目标坐标(x,y)
16 SourceList=[];DestList=[]
17
18 for i in range(4):
19 SourceList.append([ nowStyle[i][0]+self.px, nowStyle[i][1]+self.py])
20 x = newStyle[i][0]+self.px
21 y = newStyle[i][1]+self.py
22 DestList.append([x, y])
23
24 if x<0 or x>=HEIGHT or y<0 or y>=WIDTH : #or BL[x][y]==1 or LL[x][y].isactive==PASSIVE
25 Moveable=FALSE
26
27 if Moveable==TRUE:
28 for i in range(len(SourceList)):
29 self.Empty(SourceList[i][0],SourceList[i][1])
30 for i in range(len(DestList)):
31 self.Fill(DestList[i][0],DestList[i][1])
32
33 def Left(self,event):
34 BL=self.BlockList;LL=self.LabelList
35 Moveable=TRUE
36 for i in range(HEIGHT):
37 for j in range(WIDTH):
38 if LL[i][j].isactive==ACTIVE and j-1<0:Moveable=FALSE
39 if LL[i][j].isactive==ACTIVE and j-1>=0 and BL[i][j-1]==1 and LL[i][j-1].isactive==PASSIVE:Moveable=FALSE
40 if Moveable==TRUE:
41 self.py-=1
42 for i in range(HEIGHT):
43 for j in range(WIDTH):
44 if j-1>=0 and LL[i][j].isactive==ACTIVE and BL[i][j-1]==0:
45 self.Fill(i,j-1);self.Empty(i,j)
46
47 def Right(self,event):
48 BL=self.BlockList;LL=self.LabelList
49 Moveable=TRUE
50 for i in range(HEIGHT):
51 for j in range(WIDTH):
52 if LL[i][j].isactive==ACTIVE and j+1>=WIDTH:Moveable=FALSE
53 if LL[i][j].isactive==ACTIVE and j+1<WIDTH and BL[i][j+1]==1 and LL[i][j+1].isactive==PASSIVE:Moveable=FALSE
54 if Moveable==TRUE:
55 self.py+=1
56 for i in range(HEIGHT-1,-1,-1):
57 for j in range(WIDTH-1,-1,-1):
58 if j+1<WIDTH and LL[i][j].isactive==ACTIVE and BL[i][j+1]==0:
59 self.Fill(i,j+1);self.Empty(i,j)
60
61 def Down(self,event):
62 BL=self.BlockList;LL=self.LabelList
63 Moveable=TRUE
64 for i in range(HEIGHT):
65 for j in range(WIDTH):
66 if LL[i][j].isactive==ACTIVE and i+1>=HEIGHT:Moveable=FALSE
67 if LL[i][j].isactive==ACTIVE and i+1<HEIGHT and BL[i+1][j]==1 and LL[i+1][j].isactive==PASSIVE:Moveable=FALSE
68 if Moveable==TRUE and self.isStart :
69 self.px+=1
70 for i in range(HEIGHT-1,-1,-1):
71 for j in range(WIDTH-1,-1,-1):
72 if i+1<HEIGHT and LL[i][j].isactive==ACTIVE and BL[i+1][j]==0:
73 self.Fill(i+1,j);self.Empty(i,j);
74 if Moveable==FALSE:
75 for i in range(HEIGHT):
76 for j in range(WIDTH):
77 LL[i][j].isactive=PASSIVE
78 self.JudgeLineFill()
79 self.Start()
80 if self.isgameover==TRUE:showinfo('T_T','The game is over!');self.Distroy();return FALSE
81 for i in range(4):
82 for j in range(4):
83 self.NextEmpty(i,j)
84 self.Rnd()
85 return Moveable
86
87 def Space(self,event):
88 while 1:
89 if self.Down(0)==FALSE:break
3. 项目完整代码
1 #_*_ coding:utf-8 _*_
2 from tkinter import *
3 import random
4 import time
5 import tkinter.messagebox
6
7
8 #俄罗斯方块界面的高度
9 HEIGHT = 20
10
11 #俄罗斯方块界面的宽度
12 WIDTH = 10
13
14 ACTIVE = 1
15 PASSIVE = 0
16 TRUE = 1
17 FALSE = 0
18
19 style = [
20 [[(0,0),(0,1),(1,1),(2,1)],[(1,0),(1,1),(1,2),(0,2)],[(0,1),(1,1),(2,1),(2,2)],[(1,0),(2,0),(1,1),(1,2)]],#j
21 [[(1,0),(1,1),(1,2),(2,1)],[(1,0),(0,1),(1,1),(2,1)],[(1,0),(1,1),(1,2),(0,1)],[(0,1),(1,1),(2,1),(1,2)]],#T
22 [[(0,1),(1,1),(2,1),(2,0)],[(0,0),(1,0),(1,1),(1,2)],[(0,1),(1,1),(2,1),(0,2)],[(1,0),(1,1),(1,2),(2,2)]],#反L
23 [[(0,0),(0,1),(1,1),(1,2)],[(2,1),(1,1),(1,2),(0,2)],[(0,0),(0,1),(1,1),(1,2)],[(2,1),(1,1),(1,2),(0,2)]],#Z
24 [[(1,0),(1,1),(0,1),(0,2)],[(0,1),(1,1),(1,2),(2,2)],[(1,0),(1,1),(0,1),(0,2)],[(0,1),(1,1),(1,2),(2,2)]],#反Z
25 [[(0,0),(0,1),(1,1),(1,0)],[(0,0),(0,1),(1,1),(1,0)],[(0,0),(0,1),(1,1),(1,0)],[(0,0),(0,1),(1,1),(1,0)]],#田
26 [[(1,0),(1,1),(1,2),(1,3)],[(0,1),(1,1),(2,1),(3,1)],[(1,0),(1,1),(1,2),(1,3)],[(0,1),(1,1),(2,1),(3,1)]]#长条
27 ]
28
29 root=Tk();
30 root.title('俄罗斯方块')
31
32 class App(Frame):
33 def __init__(self,master):
34 Frame.__init__(self)
35 master.bind('<Up>',self.Up)
36 master.bind('<Left>',self.Left)
37 master.bind('<Right>',self.Right)
38 master.bind('<Down>',self.Down)
39
40 master.bind('<space>',self.Space)
41 master.bind('<Control-Shift-Key-F12>',self.Play)
42 master.bind('<Key-P>',self.Pause)
43 master.bind('<Key-S>',self.StartByS)
44
45 # rgb颜色值
46 self.backg="#%02x%02x%02x" % (120,150,30) #大背景
47 self.frontg="#%02x%02x%02x" % (40,120,150) #下一个形状颜色
48 self.nextg="#%02x%02x%02x" % (150,100,100) #小背景
49 self.flashg="#%02x%02x%02x" % (210,130,100) #炸的颜色
50
51 self.LineDisplay=Label(master,text='Lines: ',bg='black',fg='red')
52 self.Line=Label(master,text='0',bg='black',fg='red')
53 self.ScoreDisplay=Label(master,text='Score: ',bg='black',fg='red')
54 self.Score=Label(master,text='0',bg='black',fg='red')
55 self.SpendTimeDisplay=Label(master,text='Time: ',bg='black',fg='red')
56 self.SpendTime=Label(master,text='0.0',bg='black',fg='red')
57
58 self.LineDisplay.grid(row=HEIGHT-2,column=WIDTH,columnspan=2)
59 self.Line.grid(row=HEIGHT-2,column=WIDTH+2,columnspan=3)
60 self.ScoreDisplay.grid(row=HEIGHT-1,column=WIDTH,columnspan=2)
61 self.Score.grid(row=HEIGHT-1,column=WIDTH+2,columnspan=3)
62 self.SpendTimeDisplay.grid(row=HEIGHT-4,column=WIDTH,columnspan=2)
63 self.SpendTime.grid(row=HEIGHT-4,column=WIDTH+2,columnspan=3)
64
65 self.TotalTime=0.0
66 self.TotalLine=0
67 self.TotalScore=0
68
69 #游戏结束
70 self.isgameover=FALSE
71 #暂停
72 self.isPause=FALSE
73 #开始
74 self.isStart=FALSE
75 self.NextList=[] #整个小背景
76 self.NextRowList=[] #一行小背景
77
78 self.px=0
79 self.py=0 #记录方块参考点
80
81 #渲染小背景
82 r=0;c=0
83 for k in range(4*4):
84 LN=Label(master,text=' ',bg=str(self.nextg),fg='white',relief=FLAT,bd=3)
85 LN.grid(row=r,column=WIDTH+c,sticky=N+E+S+W)
86 self.NextRowList.append(LN)
87 c=c+1
88 if c>=4:
89 r=r+1;c=0
90 self.NextList.append(self.NextRowList)
91 self.NextRowList=[]
92
93 #渲染大背景
94 self.BlockList=[]
95 self.BlockRowList=[]
96 self.LabelList=[]
97 self.LabelRowList=[]
98 row=0;col=0
99 for i in range(HEIGHT*WIDTH):
100 L=Label(master,text=' ',bg=str(self.backg),fg='white',relief=FLAT,bd=4)
101 L.grid(row=row,column=col,sticky=N+E+S+W)
102 L.row=row;L.col=col;L.isactive=PASSIVE
103 self.BlockRowList.append(0); #大背景每个格子初始化为0值
104 self.LabelRowList.append(L)
105 col=col+1
106 if col>=WIDTH:
107 row=row+1;col=0
108 self.BlockList.append(self.BlockRowList)
109 self.LabelList.append(self.LabelRowList)
110 self.BlockRowList=[]
111 self.LabelRowList=[]
112
113 #file
114 fw=open('text.txt','a')
115 fw.close()
116 hasHead=FALSE
117 f=open('text.txt','r')
118 if f.read(5)=='score':
119 hasHead=TRUE
120 f.close()
121 self.file=open('text.txt','a')
122 if hasHead==FALSE:
123 self.file.write('score line time scorePtime linePtime scorePline date/n')
124 self.file.flush()
125
126 self.time=1000
127 self.OnTimer()
128
129 def __del__(self):
130 #self.file.close()
131 pass
132
133 def Pause(self,event):
134 self.isPause=1-self.isPause
135
136 def Up(self,event):
137 BL=self.BlockList #格子的值
138 LL=self.LabelList #格子Label
139
140 Moveable=TRUE #是否可旋转
141
142 #代码编写开始
143 nowStyle = style[self.xnow][(self.ynow)]
144 newStyle = style[self.xnow][(self.ynow+1)%4] #算出下一俄罗斯方块
145 self.ynow = (self.ynow+1)%4 #此行代码非常重要,否则响应UP时,只能变第一次
146
147 print("nowStyle:"+str(nowStyle)+"=====>>newStyle:"+str(newStyle))
148
149 #根据现有形状中每个label的坐标计算出旋转后目标坐标(x,y)
150 SourceList=[];DestList=[]
151
152 for i in range(4):
153 SourceList.append([ nowStyle[i][0]+self.px, nowStyle[i][1]+self.py])
154 x = newStyle[i][0]+self.px
155 y = newStyle[i][1]+self.py
156 DestList.append([x, y])
157
158 if x<0 or x>=HEIGHT or y<0 or y>=WIDTH : #or BL[x][y]==1 or LL[x][y].isactive==PASSIVE
159 Moveable=FALSE
160
161 if Moveable==TRUE:
162 for i in range(len(SourceList)):
163 self.Empty(SourceList[i][0],SourceList[i][1])
164 for i in range(len(DestList)):
165 self.Fill(DestList[i][0],DestList[i][1])
166
167 def Left(self,event):
168 BL=self.BlockList;LL=self.LabelList
169 Moveable=TRUE
170 for i in range(HEIGHT):
171 for j in range(WIDTH):
172 if LL[i][j].isactive==ACTIVE and j-1<0:Moveable=FALSE
173 if LL[i][j].isactive==ACTIVE and j-1>=0 and BL[i][j-1]==1 and LL[i][j-1].isactive==PASSIVE:Moveable=FALSE
174 if Moveable==TRUE:
175 self.py-=1
176 for i in range(HEIGHT):
177 for j in range(WIDTH):
178 if j-1>=0 and LL[i][j].isactive==ACTIVE and BL[i][j-1]==0:
179 self.Fill(i,j-1);self.Empty(i,j)
180
181 def Right(self,event):
182 BL=self.BlockList;LL=self.LabelList
183 Moveable=TRUE
184 for i in range(HEIGHT):
185 for j in range(WIDTH):
186 if LL[i][j].isactive==ACTIVE and j+1>=WIDTH:Moveable=FALSE
187 if LL[i][j].isactive==ACTIVE and j+1<WIDTH and BL[i][j+1]==1 and LL[i][j+1].isactive==PASSIVE:Moveable=FALSE
188 if Moveable==TRUE:
189 self.py+=1
190 for i in range(HEIGHT-1,-1,-1):
191 for j in range(WIDTH-1,-1,-1):
192 if j+1<WIDTH and LL[i][j].isactive==ACTIVE and BL[i][j+1]==0:
193 self.Fill(i,j+1);self.Empty(i,j)
194
195 def Down(self,event):
196 BL=self.BlockList;LL=self.LabelList
197 Moveable=TRUE
198 for i in range(HEIGHT):
199 for j in range(WIDTH):
200 if LL[i][j].isactive==ACTIVE and i+1>=HEIGHT:Moveable=FALSE
201 if LL[i][j].isactive==ACTIVE and i+1<HEIGHT and BL[i+1][j]==1 and LL[i+1][j].isactive==PASSIVE:Moveable=FALSE
202 if Moveable==TRUE and self.isStart :
203 self.px+=1
204 for i in range(HEIGHT-1,-1,-1):
205 for j in range(WIDTH-1,-1,-1):
206 if i+1<HEIGHT and LL[i][j].isactive==ACTIVE and BL[i+1][j]==0:
207 self.Fill(i+1,j);self.Empty(i,j);
208 if Moveable==FALSE:
209 for i in range(HEIGHT):
210 for j in range(WIDTH):
211 LL[i][j].isactive=PASSIVE
212 self.JudgeLineFill()
213 self.Start()
214 if self.isgameover==TRUE:showinfo('T_T','The game is over!');self.Distroy();return FALSE
215 for i in range(4):
216 for j in range(4):
217 self.NextEmpty(i,j)
218 self.Rnd()
219 return Moveable
220
221 def Space(self,event):
222 while 1:
223 if self.Down(0)==FALSE:break
224
225 def OnTimer(self):
226 if self.isStart==TRUE and self.isPause==FALSE:
227 self.TotalTime = self.TotalTime + float(self.time)/1000
228 self.SpendTime.config(text=str(self.TotalTime))
229
230 if self.isPause==FALSE:
231 self.Down(0)
232 if self.TotalScore>=1000:self.time=900
233 if self.TotalScore>=2000:self.time=750
234 if self.TotalScore>=3000:self.time=600
235 if self.TotalScore>=4000:self.time=400
236 self.after(self.time,self.OnTimer) #随着分数增大,俄罗斯方块下降速度加快
237
238 def JudgeLineFill(self):
239 BL=self.BlockList;LL=self.LabelList
240 count=0;LineList=[]
241 for i in range(WIDTH):LineList.append(1)
242 #display flash
243 for i in range(HEIGHT):
244 if BL[i]==LineList:
245 count=count+1
246 for k in range(WIDTH):
247 LL[i][k].config(bg=str(self.flashg))
248 LL[i][k].update()
249 if count!=0:self.after(100)
250 #delete block
251 for i in range(HEIGHT):
252 if BL[i]==LineList:
253 #count=count+1
254 for j in range(i,0,-1):
255 for k in range(WIDTH):
256 BL[j][k]=BL[j-1][k]
257 LL[j][k]['relief']=LL[j-1][k].cget('relief')
258 LL[j][k]['bg']=LL[j-1][k].cget('bg')
259 for l in range(WIDTH):
260 BL[0][l]=0
261 LL[0][l].config(relief=FLAT,bg=str(self.backg))
262 self.TotalLine=self.TotalLine+count
263 if count==1:self.TotalScore=self.TotalScore+1*WIDTH
264 if count==2:self.TotalScore=self.TotalScore+3*WIDTH
265 if count==3:self.TotalScore=self.TotalScore+6*WIDTH
266 if count==4:self.TotalScore=self.TotalScore+10*WIDTH
267 self.Line.config(text=str(self.TotalLine))
268 self.Score.config(text=str(self.TotalScore))
269
270 def Fill(self,i,j):
271 if j<0:return
272 if self.BlockList[i][j]==1:self.isgameover=TRUE
273 self.BlockList[i][j]=1
274 self.LabelList[i][j].isactive=ACTIVE
275 self.LabelList[i][j].config(relief=RAISED,bg=str(self.frontg))
276
277 def Empty(self,i,j):
278 self.BlockList[i][j]=0
279 self.LabelList[i][j].isactive=PASSIVE
280 self.LabelList[i][j].config(relief=FLAT,bg=str(self.backg))
281
282 def Play(self,event):
283 showinfo('Made in China','^_^')
284
285 def NextFill(self,i,j):
286 self.NextList[i][j].config(relief=RAISED,bg=str(self.frontg))
287
288 def NextEmpty(self,i,j):
289 self.NextList[i][j].config(relief=FLAT,bg=str(self.nextg))
290
291 def Distroy(self):
292 #save
293 if self.TotalScore!=0:
294 #cehkongfu
295 savestr='%-9u%-8u%-8.2f%-14.2f%-13.2f%-14.2f%s/n' % (
296 self.TotalScore,self.TotalLine,self.TotalTime
297 ,self.TotalScore/self.TotalTime
298 ,self.TotalLine/self.TotalTime
299 ,float(self.TotalScore)/self.TotalLine
300 ,time.strftime('%Y-%m-%d %H:%M:%S',time.localtime()))
301 self.file.seek(0,2)
302 self.file.write(savestr)
303 self.file.flush()
304
305 for i in range(HEIGHT):
306 for j in range(WIDTH):
307 self.Empty(i,j)
308 self.TotalLine=0;self.TotalScore=0;self.TotalTime=0.0
309 self.Line.config(text=str(self.TotalLine))
310 self.Score.config(text=str(self.TotalScore))
311 self.SpendTime.config(text=str(self.TotalTime))
312 self.isgameover=FALSE
313 self.isStart=FALSE
314 self.time=1000
315 for i in range(4):
316 for j in range(4):
317 self.NextEmpty(i,j)
318
319 #游戏开始方块
320 def Start(self):
321 nextStyle = style[self.x][self.y] #下一形状
322 self.xnow = self.x
323 self.ynow = self.y #记录大背景中的方块
324 self.py = random.randint(0,6)
325 print("给py赋任意值:"+str(self.py))
326 self.px = 0
327 for ii in range(4):
328 self.Fill(int(nextStyle[ii][0]),int(nextStyle[ii][1])+self.py)
329 self.isStart=TRUE #游戏开始
330
331 #预处理方块
332 def Rnd(self):
333 self.x=random.randint(0,6)
334 self.y=random.randint(0,3)
335 nextStyle = style[self.x][self.y] #下一形状
336 for ii in range(4):
337 self.NextFill(int(nextStyle[ii][0]),int(nextStyle[ii][1]))
338
339 #游戏开始给出一次任意形状的方块
340 def RndFirst(self):
341 self.x=random.randint(0,6) #选择第一个方块style
342 self.y=random.randint(0,3)
343
344 def Show(self):
345 self.file.seek(0)
346 strHeadLine=self.file.readline()
347 dictLine={}
348 strTotalLine=''
349 for OneLine in self.file.readlines():
350 temp=int(OneLine[:5])
351 dictLine[temp]=OneLine
352
353 list=sorted(dictLine.items(),key=lambda d:d[0])
354 ii=0
355 for onerecord in reversed(list):
356 ii=ii+1
357 if ii<11:
358 strTotalLine+=onerecord[1]
359 showinfo('Ranking', strHeadLine+strTotalLine)
360
361 def StartByS(self,event):
362 self.RndFirst()
363 self.Start()
364 self.Rnd()
365
366 def Start():
367 app.RndFirst()
368 app.Start()
369 app.Rnd()
370
371 def End():
372 app.Distroy()
373
374 def Set():
375 print("设置功能待完善...")
376
377 def Show():
378 app.Show()
379
380 #主菜单
381 mainmenu=Menu(root)
382 root['menu']=mainmenu
383
384 #二级菜单:game
385 gamemenu=Menu(mainmenu)
386 mainmenu.add_cascade(label='游戏',menu=gamemenu)
387 gamemenu.add_command(label='开始',command=Start)
388 gamemenu.add_command(label='结束',command=End)
389 gamemenu.add_separator()
390 gamemenu.add_command(label='退出',command=root.quit)
391
392 #二级菜单:set
393 setmenu=Menu(mainmenu)
394 mainmenu.add_cascade(label='设置',menu=setmenu)
395 setmenu.add_command(label='设置',command=Set)
396
397 #二级菜单:show
398 showmenu=Menu(mainmenu)
399 mainmenu.add_cascade(label='展示',menu=showmenu)
400 showmenu.add_command(label='展示',command=Show)
401
402 #绑定功能
403
404 app=App(root)
405 #程序入口
406 root.mainloop()
二、经典的贪吃蛇游戏
1. 项目源码
1 import random
2 import pygame
3 import sys
4 from pygame.locals import *
5
6 Snakespeed = 9
7 Window_Width = 800
8 Window_Height = 500
9 Cell_Size = 20 # Width and height of the cells
10 # Ensuring that the cells fit perfectly in the window. eg if cell size was
11 # 10 and window width or window height were 15 only 1.5 cells would
12 # fit.
13 assert Window_Width % Cell_Size == 0, "Window width must be a multiple of cell size."
14 # Ensuring that only whole integer number of cells fit perfectly in the window.
15 assert Window_Height % Cell_Size == 0, "Window height must be a multiple of cell size."
16 Cell_W = int(Window_Width / Cell_Size) # Cell Width
17 Cell_H = int(Window_Height / Cell_Size) # Cell Height
18
19 White = (255, 255, 255)
20 Black = (0, 0, 0)
21 Red = (255, 0, 0) # Defining element colors for the program.
22 Green = (0, 255, 0)
23 DARKGreen = (0, 155, 0)
24 DARKGRAY = (40, 40, 40)
25 YELLOW = (255, 255, 0)
26 Red_DARK = (150, 0, 0)
27 BLUE = (0, 0, 255)
28 BLUE_DARK = (0, 0, 150)
29
30 BGCOLOR = Black # Background color
31
32 UP = 'up'
33 DOWN = 'down' # Defining keyboard keys.
34 LEFT = 'left'
35 RIGHT = 'right'
36
37 HEAD = 0 # Syntactic sugar: index of the snake's head
38
39
40 def main():
41 global SnakespeedCLOCK, DISPLAYSURF, BASICFONT
42
43 pygame.init()
44 SnakespeedCLOCK = pygame.time.Clock()
45 DISPLAYSURF = pygame.display.set_mode((Window_Width, Window_Height))
46 BASICFONT = pygame.font.Font('freesansbold.ttf', 18)
47 pygame.display.set_caption('Snake')
48
49 showStartScreen()
50 while True:
51 runGame()
52 showGameOverScreen()
53
54
55 def runGame():
56 # Set a random start point.
57 startx = random.randint(5, Cell_W - 6)
58 starty = random.randint(5, Cell_H - 6)
59 wormCoords = [{'x': startx, 'y': starty},
60 {'x': startx - 1, 'y': starty},
61 {'x': startx - 2, 'y': starty}]
62 direction = RIGHT
63
64 # Start the apple in a random place.
65 apple = getRandomLocation()
66
67 while True: # main game loop
68 for event in pygame.event.get(): # event handling loop
69 if event.type == QUIT:
70 terminate()
71 elif event.type == KEYDOWN:
72 if (event.key == K_LEFT) and direction != RIGHT:
73 direction = LEFT
74 elif (event.key == K_RIGHT) and direction != LEFT:
75 direction = RIGHT
76 elif (event.key == K_UP) and direction != DOWN:
77 direction = UP
78 elif (event.key == K_DOWN) and direction != UP:
79 direction = DOWN
80 elif event.key == K_ESCAPE:
81 terminate()
82
83 # check if the Snake has hit itself or the edge
84 if wormCoords[HEAD]['x'] == -1 or wormCoords[HEAD]['x'] == Cell_W or wormCoords[HEAD]['y'] == -1 or \
85 wormCoords[HEAD]['y'] == Cell_H:
86 return # game over
87 for wormBody in wormCoords[1:]:
88 if wormBody['x'] == wormCoords[HEAD]['x'] and wormBody['y'] == wormCoords[HEAD]['y']:
89 return # game over
90
91 # check if Snake has eaten an apply
92 if wormCoords[HEAD]['x'] == apple['x'] and wormCoords[HEAD]['y'] == apple['y']:
93 # don't remove worm's tail segment
94 apple = getRandomLocation() # set a new apple somewhere
95 else:
96 del wormCoords[-1] # remove worm's tail segment
97
98 # move the worm by adding a segment in the direction it is moving
99 if direction == UP:
100 newHead = {'x': wormCoords[HEAD]['x'],
101 'y': wormCoords[HEAD]['y'] - 1}
102 elif direction == DOWN:
103 newHead = {'x': wormCoords[HEAD]['x'],
104 'y': wormCoords[HEAD]['y'] + 1}
105 elif direction == LEFT:
106 newHead = {'x': wormCoords[HEAD][
107 'x'] - 1, 'y': wormCoords[HEAD]['y']}
108 elif direction == RIGHT:
109 newHead = {'x': wormCoords[HEAD][
110 'x'] + 1, 'y': wormCoords[HEAD]['y']}
111 wormCoords.insert(0, newHead)
112 DISPLAYSURF.fill(BGCOLOR)
113 drawGrid()
114 drawWorm(wormCoords)
115 drawApple(apple)
116 drawScore(len(wormCoords) - 3)
117 pygame.display.update()
118 SnakespeedCLOCK.tick(Snakespeed)
119
120
121 def drawPressKeyMsg():
122 pressKeySurf = BASICFONT.render('Press a key to play.', True, White)
123 pressKeyRect = pressKeySurf.get_rect()
124 pressKeyRect.topleft = (Window_Width - 200, Window_Height - 30)
125 DISPLAYSURF.blit(pressKeySurf, pressKeyRect)
126
127
128 def checkForKeyPress():
129 if len(pygame.event.get(QUIT)) > 0:
130 terminate()
131 keyUpEvents = pygame.event.get(KEYUP)
132 if len(keyUpEvents) == 0:
133 return None
134 if keyUpEvents[0].key == K_ESCAPE:
135 terminate()
136 return keyUpEvents[0].key
137
138
139 def showStartScreen():
140 titleFont = pygame.font.Font('freesansbold.ttf', 100)
141 titleSurf1 = titleFont.render('Snake!', True, White, DARKGreen)
142 degrees1 = 0
143 degrees2 = 0
144 while True:
145 DISPLAYSURF.fill(BGCOLOR)
146 rotatedSurf1 = pygame.transform.rotate(titleSurf1, degrees1)
147 rotatedRect1 = rotatedSurf1.get_rect()
148 rotatedRect1.center = (Window_Width / 2, Window_Height / 2)
149 DISPLAYSURF.blit(rotatedSurf1, rotatedRect1)
150
151 drawPressKeyMsg()
152
153 if checkForKeyPress():
154 pygame.event.get() # clear event queue
155 return
156 pygame.display.update()
157 SnakespeedCLOCK.tick(Snakespeed)
158 degrees1 += 3 # rotate by 3 degrees each frame
159 degrees2 += 7 # rotate by 7 degrees each frame
160
161
162 def terminate():
163 pygame.quit()
164 sys.exit()
165
166
167 def getRandomLocation():
168 return {'x': random.randint(0, Cell_W - 1), 'y': random.randint(0, Cell_H - 1)}
169
170
171 def showGameOverScreen():
172 gameOverFont = pygame.font.Font('freesansbold.ttf', 100)
173 gameSurf = gameOverFont.render('Game', True, White)
174 overSurf = gameOverFont.render('Over', True, White)
175 gameRect = gameSurf.get_rect()
176 overRect = overSurf.get_rect()
177 gameRect.midtop = (Window_Width / 2, 10)
178 overRect.midtop = (Window_Width / 2, gameRect.height + 10 + 25)
179
180 DISPLAYSURF.blit(gameSurf, gameRect)
181 DISPLAYSURF.blit(overSurf, overRect)
182 drawPressKeyMsg()
183 pygame.display.update()
184 pygame.time.wait(500)
185 checkForKeyPress() # clear out any key presses in the event queue
186
187 while True:
188 if checkForKeyPress():
189 pygame.event.get() # clear event queue
190 return
191
192
193 def drawScore(score):
194 scoreSurf = BASICFONT.render('Score: %s' % (score), True, White)
195 scoreRect = scoreSurf.get_rect()
196 scoreRect.topleft = (Window_Width - 120, 10)
197 DISPLAYSURF.blit(scoreSurf, scoreRect)
198
199
200 def drawWorm(wormCoords):
201 for coord in wormCoords:
202 x = coord['x'] * Cell_Size
203 y = coord['y'] * Cell_Size
204 wormSegmentRect = pygame.Rect(x, y, Cell_Size, Cell_Size)
205 pygame.draw.rect(DISPLAYSURF, DARKGreen, wormSegmentRect)
206 wormInnerSegmentRect = pygame.Rect(
207 x + 4, y + 4, Cell_Size - 8, Cell_Size - 8)
208 pygame.draw.rect(DISPLAYSURF, Green, wormInnerSegmentRect)
209
210
211 def drawApple(coord):
212 x = coord['x'] * Cell_Size
213
214
215 y = coord['y'] * Cell_Size
216 appleRect = pygame.Rect(x, y, Cell_Size, Cell_Size)
217 pygame.draw.rect(DISPLAYSURF, Red, appleRect)
218
219
220 def drawGrid():
221 for x in range(0, Window_Width, Cell_Size): # draw vertical lines
222 pygame.draw.line(DISPLAYSURF, DARKGRAY, (x, 0), (x, Window_Height))
223 for y in range(0, Window_Height, Cell_Size): # draw horizontal lines
224 pygame.draw.line(DISPLAYSURF, DARKGRAY, (0, y), (Window_Width, y))
225
226
227 if __name__ == '__main__':
228 try:
229 main()
230 except SystemExit:
231 pass
预览效果:
三、关不掉的窗口
1.项目源码
1 from tkinter import *
2 class YouLikeMe:
3 def __init__(self):
4 window=Tk()
5 label=Label(window,text='你是不是喜欢我?')
6 self.btyes=Button(window,text='不是',height=1,width=6)
7 self.btno=Button(window,text='是的',height=1,width=6)
8 label.place(x=60,y=70)
9 self.btyes.place(x=40,y=130)
10 self.btno.place(x=120,y=130)
11 self.btyes.bind('<Enter>',self.event1)#将按钮与鼠标事件绑定,<Enter>是指鼠标光标进入按钮区域
12 self.btno.bind('<Enter>',self.event2)
13 window.mainloop()
14 def event1(self,event):#切换按钮文字
15 self.btyes['text']='是的'
16 self.btno['text']='不是'
17 def event2(self,event):
18 self.btyes['text']='不是'
19 self.btno['text']='是的'
20
21 YouLikeMe()
22 window=Tk()
23 label=Label(window,text='关闭窗口也改变不了你喜欢我的事实')
24 label.place(x=2,y=80)
25 button=Button(window,text='确定',command=window.destroy)
26 button.place(x=80,y=150)
27 window.mainloop()
预览效果:
四、画玫瑰花
1 import turtle
2 import time
3 turtle.speed(5) #画笔移动的速度
4
5
6
7 # 设置初始位置
8
9 turtle.penup() #提起画笔,移动画笔但并不会绘制图形
10 turtle.left(90) #逆时针转动画笔90度
11 turtle.fd(200)
12 turtle.pendown() #放下画笔,移动画笔即开始绘制
13 turtle.right(90)
14 #设置画笔的大小
15 turtle.pensize(2)
16
17 # 花蕊
18
19 turtle.fillcolor("red") #填充颜色
20 turtle.begin_fill() #开始填充
21 turtle.circle(10,180)
22 turtle.circle(25,110)
23 turtle.left(50)
24 turtle.circle(60,45)
25 turtle.circle(20,170)
26 turtle.right(24)
27 turtle.fd(30)
28 turtle.left(10)
29 turtle.circle(30,110)
30 turtle.fd(20)
31 turtle.left(40)
32 turtle.circle(90,70)
33 turtle.circle(30,150)
34 turtle.right(30)
35 turtle.fd(15)
36 turtle.circle(80,90)
37 turtle.left(15)
38 turtle.fd(45)
39 turtle.right(165)
40 turtle.fd(20)
41 turtle.left(155)
42 turtle.circle(150,80)
43 turtle.left(50)
44 turtle.circle(150,90)
45 turtle.end_fill() #结束填充
46
47 # 花瓣1
48
49 turtle.left(150)
50 turtle.circle(-90,70)
51 turtle.left(20)
52 turtle.circle(75,105)
53 turtle.setheading(60)
54 turtle.circle(80,98)
55 turtle.circle(-90,40)
56
57
58
59 # 花瓣2
60 turtle.left(180)
61 turtle.circle(90,40)
62 turtle.circle(-80,98)
63 turtle.setheading(-83)
64
65 # 叶子1
66 turtle.fd(30)
67 turtle.left(90)
68 turtle.fd(25)
69 turtle.left(45)
70 turtle.fillcolor("green")
71 turtle.begin_fill()
72 turtle.circle(-80,90)
73 turtle.right(90)
74 turtle.circle(-80,90)
75 turtle.end_fill()
76
77
78
79 turtle.right(135)
80 turtle.fd(60)
81 turtle.left(180)
82 turtle.fd(85)
83 turtle.left(90)
84 turtle.fd(80)
85
86
87 # 叶子2
88 turtle.right(90)
89 turtle.right(45)
90 turtle.fillcolor("green")
91 turtle.begin_fill()
92 turtle.circle(80,90)
93 turtle.left(90)
94 turtle.circle(80,90)
95 turtle.end_fill()
96
97
98 turtle.left(135)
99 turtle.fd(60)
100 turtle.left(180)
101 turtle.fd(60)
102 turtle.right(90)
103 turtle.circle(200,50) #画一个圆 200 是半径,50 是弧度
104
105 #不让自动退出,放在程序的最后一行
106 #不然画画结束后会自动退出
107 turtle.done()
预览效果:
五、优美的彩虹线条
1 import turtle
2 q = turtle.Pen()
3 turtle.bgcolor("black")
4 sides = 7
5 colors =["red","orange","yellow","green","cyan","blue","blue","purple"]
6 for x in range(360):
7 q.pencolor(colors[x%sides])
8 q.forward(x*3/sides+x)
9 q.left(360/sides+1)
10 q.width(x*sides/200)
预览效果
六、实时钟表
1 # -*- coding:utf-8 –*-
2 # 用turtlr画时钟
3 # 以自定义shape的方式实现
4 import turtle as t
5 import datetime as d
6 def skip(step): # 抬笔,跳到一个地方
7 t.penup()
8 t.forward(step)
9 t.pendown()
10 def drawClock(radius): # 画表盘
11 t.speed(0)
12 t.mode("logo") # 以Logo坐标、角度方式
13 t.hideturtle()
14 t.pensize(7)
15 t.home() # 回到圆点
16 for j in range(60):
17 skip(radius)
18 if (j % 5 == 0):
19 t.forward(20)
20 skip(-radius - 20)
21 else:
22 t.dot(5)
23 skip(-radius)
24 t.right(6)
25 def makePoint(pointName, len): # 钟的指针,时针、分针、秒针
26 t.penup()
27 t.home()
28 t.begin_poly()
29 t.back(0.1 * len)
30 t.forward(len * 1.1)
31 t.end_poly()
32 poly = t.get_poly()
33 t.register_shape(pointName, poly) # 注册为一个shape
34 def drawPoint(): # 画指针
35 global hourPoint, minPoint, secPoint, fontWriter
36 makePoint("hourPoint", 100)
37 makePoint("minPoint", 120)
38 makePoint("secPoint", 140)
39 hourPoint = t.Pen() # 每个指针是一只新turtle
40 hourPoint.shape("hourPoint")
41 hourPoint.shapesize(1, 1, 6)
42 minPoint = t.Pen()
43 minPoint.shape("minPoint")
44 minPoint.shapesize(1, 1, 4)
45 secPoint = t.Pen()
46 secPoint.shape("secPoint")
47 secPoint.pencolor('red')
48 fontWriter = t.Pen()
49 fontWriter.pencolor('gray')
50 fontWriter.hideturtle()
51 def getWeekName(weekday):
52 weekName = ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期日']
53 return weekName[weekday]
54 def getDate(year, month, day):
55 return "%s-%s-%s" % (year, month, day)
56 def realTime():
57 curr = d.datetime.now()
58 curr_year = curr.year
59 curr_month = curr.month
60 curr_day = curr.day
61 curr_hour = curr.hour
62 curr_minute = curr.minute
63 curr_second = curr.second
64 curr_weekday = curr.weekday()
65 t.tracer(False)
66 secPoint.setheading(360 / 60 * curr_second)
67 minPoint.setheading(360 / 60 * curr_minute)
68 hourPoint.setheading(360 / 12 * curr_hour + 30 / 60 * curr_minute)
69 fontWriter.clear()
70 fontWriter.home()
71 fontWriter.penup()
72 fontWriter.forward(80)
73 # 用turtle写文字
74 fontWriter.write(getWeekName(curr_weekday), align="center", font=("Courier", 14, "bold"))
75 fontWriter.forward(-160)
76 fontWriter.write(getDate(curr_year, curr_month, curr_day), align="center", font=("Courier", 14, "bold"))
77 t.tracer(True)
78 print(curr_second)
79 t.ontimer(realTime, 100) # 每隔100毫秒调用一次realTime()
80 def main():
81 t.tracer(False)
82 drawClock(160)
83 drawPoint()
84 realTime()
85 t.tracer(True)
86 t.mainloop()
87 if __name__ == '__main__':
88 main()
预览效果:
七、画佩奇
1 # coding: utf-8
2
3 import turtle as t
4
5 t.screensize(400, 300)
6 t.pensize(4) # 设置画笔的大小
7 t.colormode(255) # 设置GBK颜色范围为0-255
8 t.color((255, 155, 192), "pink") # 设置画笔颜色和填充颜色(pink)
9 t.setup(840, 500) # 设置主窗口的大小为840*500
10 t.speed(10) # 设置画笔速度为10
11 # 鼻子
12 t.pu() # 提笔
13 t.goto(-100, 100) # 画笔前往坐标(-100,100)
14 t.pd() # 下笔
15 t.seth(-30) # 笔的角度为-30°
16 t.begin_fill() # 外形填充的开始标志
17 a = 0.4
18 for i in range(120):
19 if 0 <= i < 30 or 60 <= i < 90:
20 a = a + 0.08
21 t.lt(3) # 向左转3度
22 t.fd(a) # 向前走a的步长
23 else:
24 a = a - 0.08
25 t.lt(3)
26 t.fd(a)
27 t.end_fill() # 依据轮廓填充
28 t.pu() # 提笔
29 t.seth(90) # 笔的角度为90度
30 t.fd(25) # 向前移动25
31 t.seth(0) # 转换画笔的角度为0
32 t.fd(10)
33 t.pd()
34 t.pencolor(255, 155, 192) # 设置画笔颜色
35 t.seth(10)
36 t.begin_fill()
37 t.circle(5) # 画一个半径为5的圆
38 t.color(160, 82, 45) # 设置画笔和填充颜色
39 t.end_fill()
40 t.pu()
41 t.seth(0)
42 t.fd(20)
43 t.pd()
44 t.pencolor(255, 155, 192)
45 t.seth(10)
46 t.begin_fill()
47 t.circle(5)
48 t.color(160, 82, 45)
49 t.end_fill()
50 # 头
51 t.color((255, 155, 192), "pink")
52 t.pu()
53 t.seth(90)
54 t.fd(41)
55 t.seth(0)
56 t.fd(0)
57 t.pd()
58 t.begin_fill()
59 t.seth(180)
60 t.circle(300, -30) # 顺时针画一个半径为300,圆心角为30°的园
61 t.circle(100, -60)
62 t.circle(80, -100)
63 t.circle(150, -20)
64 t.circle(60, -95)
65 t.seth(161)
66 t.circle(-300, 15)
67 t.pu()
68 t.goto(-100, 100)
69 t.pd()
70 t.seth(-30)
71 a = 0.4
72 for i in range(60):
73 if 0 <= i < 30 or 60 <= i < 90:
74 a = a + 0.08
75 t.lt(3) # 向左转3度
76 t.fd(a) # 向前走a的步长
77 else:
78 a = a - 0.08
79 t.lt(3)
80 t.fd(a)
81 t.end_fill()
82 # 耳朵
83 t.color((255, 155, 192), "pink")
84 t.pu()
85 t.seth(90)
86 t.fd(-7)
87 t.seth(0)
88 t.fd(70)
89 t.pd()
90 t.begin_fill()
91 t.seth(100)
92 t.circle(-50, 50)
93 t.circle(-10, 120)
94 t.circle(-50, 54)
95 t.end_fill()
96 t.pu()
97 t.seth(90)
98 t.fd(-12)
99 t.seth(0)
100 t.fd(30)
101 t.pd()
102 t.begin_fill()
103 t.seth(100)
104 t.circle(-50, 50)
105 t.circle(-10, 120)
106 t.circle(-50, 56)
107 t.end_fill()
108 # 眼睛
109 t.color((255, 155, 192), "white")
110 t.pu()
111 t.seth(90)
112 t.fd(-20)
113 t.seth(0)
114 t.fd(-95)
115 t.pd()
116 t.begin_fill()
117 t.circle(15)
118 t.end_fill()
119 t.color("black")
120 t.pu()
121 t.seth(90)
122 t.fd(12)
123 t.seth(0)
124 t.fd(-3)
125 t.pd()
126 t.begin_fill()
127 t.circle(3)
128 t.end_fill()
129 t.color((255, 155, 192), "white")
130 t.pu()
131 t.seth(90)
132 t.fd(-25)
133 t.seth(0)
134 t.fd(40)
135 t.pd()
136 t.begin_fill()
137 t.circle(15)
138 t.end_fill()
139 t.color("black")
140 t.pu()
141 t.seth(90)
142 t.fd(12)
143 t.seth(0)
144 t.fd(-3)
145 t.pd()
146 t.begin_fill()
147 t.circle(3)
148 t.end_fill()
149 # 腮
150 t.color((255, 155, 192))
151 t.pu()
152 t.seth(90)
153 t.fd(-95)
154 t.seth(0)
155 t.fd(65)
156 t.pd()
157 t.begin_fill()
158 t.circle(30)
159 t.end_fill()
160 # 嘴
161 t.color(239, 69, 19)
162 t.pu()
163 t.seth(90)
164 t.fd(15)
165 t.seth(0)
166 t.fd(-100)
167 t.pd()
168 t.seth(-80)
169 t.circle(30, 40)
170 t.circle(40, 80)
171 # 身体
172 t.color("red", (255, 99, 71))
173 t.pu()
174 t.seth(90)
175 t.fd(-20)
176 t.seth(0)
177 t.fd(-78)
178 t.pd()
179 t.begin_fill()
180 t.seth(-130)
181 t.circle(100, 10)
182 t.circle(300, 30)
183 t.seth(0)
184 t.fd(230)
185 t.seth(90)
186 t.circle(300, 30)
187 t.circle(100, 3)
188 t.color((255, 155, 192), (255, 100, 100))
189 t.seth(-135)
190 t.circle(-80, 63)
191 t.circle(-150, 24)
192 t.end_fill()
193 # 手
194 t.color((255, 155, 192))
195 t.pu()
196 t.seth(90)
197 t.fd(-40)
198 t.seth(0)
199 t.fd(-27)
200 t.pd()
201 t.seth(-160)
202 t.circle(300, 15)
203 t.pu()
204 t.seth(90)
205 t.fd(15)
206 t.seth(0)
207 t.fd(0)
208 t.pd()
209 t.seth(-10)
210 t.circle(-20, 90)
211 t.pu()
212 t.seth(90)
213 t.fd(30)
214 t.seth(0)
215 t.fd(237)
216 t.pd()
217 t.seth(-20)
218 t.circle(-300, 15)
219 t.pu()
220 t.seth(90)
221 t.fd(20)
222 t.seth(0)
223 t.fd(0)
224 t.pd()
225 t.seth(-170)
226 t.circle(20, 90)
227 # 脚
228 t.pensize(10)
229 t.color((240, 128, 128))
230 t.pu()
231 t.seth(90)
232 t.fd(-75)
233 t.seth(0)
234 t.fd(-180)
235 t.pd()
236 t.seth(-90)
237 t.fd(40)
238 t.seth(-180)
239 t.color("black")
240 t.pensize(15)
241 t.fd(20)
242 t.pensize(10)
243 t.color((240, 128, 128))
244 t.pu()
245 t.seth(90)
246 t.fd(40)
247 t.seth(0)
248 t.fd(90)
249 t.pd()
250 t.seth(-90)
251 t.fd(40)
252 t.seth(-180)
253 t.color("black")
254 t.pensize(15)
255 t.fd(20)
256 # 尾巴
257 t.pensize(4)
258 t.color((255, 155, 192))
259 t.pu()
260 t.seth(90)
261 t.fd(70)
262 t.seth(0)
263 t.fd(95)
264 t.pd()
265 t.seth(0)
266 t.circle(70, 20)
267 t.circle(10, 330)
268 t.circle(70, 30)
269 t.done()
预览效果:
八、表白程序
1 from tkinter import * #_all_ = [a,b]
2 from tkinter import messagebox
3 from PIL import ImageTk
4 def closeWindow():
5 messagebox.showinfo(title="警告",message = "不许关闭,好好回答")
6 return
7
8 #点击喜欢触发的方法
9 def Love():
10 #Toplevel独立的*窗口,和父级标题一样
11 love = Toplevel(window)
12 love.geometry("360x200+540+360")
13 love.title("好巧,我也是")
14 label = Label(love,text="巧了,我也喜欢你",font =("微软雅黑",20))
15 label.pack()
16 label1 = Label(love,text="认识一下,加个微信呗",font =("微软雅黑",20))
17 label1.pack()
18 entry = Entry(love,font = ("微软雅黑",15))
19 entry.pack()
20 btn = Button(love,text = "确定",width = 10 , height = 1,command = close_all)
21 btn.pack()
22 love.protocol("WM_DELETE_WINDOW",closelove)
23
24 def closelove():
25 return
26
27 #关闭所有的窗口 注意,如果父级窗口关了,下面的所有窗口均会关闭
28 def close_all():
29 #destory 销毁
30 window.destroy()
31 #关闭不喜欢框的X时
32 def closenolove():
33 messagebox.showinfo("再考虑一下","再考虑一下呗")
34 return
35 disLove()
36
37 #点击不喜欢触发的事件
38 def disLove():
39 no_love = Toplevel(window)
40 no_love.geometry("300x90+540+360")
41 no_love.title("再考虑考虑")
42 label = Label(no_love,text = "再考虑考虑呗!",font = ("微软雅黑",25))
43 label.pack()
44 btn = Button(no_love,text = "好的",width = 10 , height = 1,command = no_love.destroy)
45 btn.pack()
46 no_love.protocol("WM_DELETE_WINDOW",closenolove)
47
48
49
50 # 创建窗口
51 window =Tk() #类的实例化,创建窗口,window仅仅是个变量
52
53 # 窗口标题
54 window.title("你喜欢我吗?")
55
56 # 窗口的大小 运用小写的x来连接
57 window.geometry("380x400")
58
59 #窗口位置(距离屏幕左上角) 运用+来连接
60 window.geometry("+500+240") # geometry意为几何
61 #上述可以写成window.geometry("380x200+500+245"),其中+是用来连接的
62
63 #用户关闭窗口触发的事件
64 window.protocol("WM_DELETE_WINDOW",closeWindow)
65
66 # 标签控件,一般第一个参数均是父级窗口 ,这里传参为window fg设置颜色
67 label = Label(window, text = "Hey,小姐姐", font = ("微软雅黑",15), fg="black")
68
69 # 定位 grid(网格式) pack(包的方式) place(用的最少的一种,根据位置)
70 label.grid(row=0,column =0) #默认值为 0 0
71
72 label_1 = Label(window,text = "喜欢我吗?",font = ("微软雅黑",25))
73 label_1.grid(row=1,column = 1,sticky = E) #sticky为对齐方式 N上S下W左E右
74
75 # 显示图片
76 photo = ImageTk.PhotoImage(file='Rose.jpg')
77 imageLable = Label(window,image = photo)
78 #column 组件所跨越的列数
79 imageLable.grid(row=2,columnspan =2) #跨列操作
80
81
82 # ques_image = ImageTk.PhotoImage(file='./Image/cache/{}'.format(image_name.group()))
83
84
85
86 #按钮控件 点击触发command事件
87 btn = Button(window,text="喜欢",width = 15,height=1,command = Love)
88 btn.grid(row = 3,column = 0,sticky = W)
89
90 btn1 =Button(window,text="不喜欢",command = disLove)
91 btn1 .grid(row = 3,column = 1,sticky = E)
92 #显示窗口 消息循环
93 window .mainloop()
预览效果:
上图的素材贴在这里啦
九、黑客代码雨
1 # -*- coding:utf-8 -*-
2
3 #导入系统文件库
4 import pygame
5 import random
6 from pygame.locals import *
7 from random import randint
8
9
10 #定义一些窗体参数及加载字体文件
11 SCREEN_WIDTH = 900 # 窗体宽度
12 SCREEN_HEIGHT = 600 # 窗体宽度
13 LOW_SPEED = 4 # 字体移动最低速度
14 HIGH_SPEED = 10 # 字体移动最快速度
15 FONT_COLOR = (00,150,00) # 字体颜色
16 FONT_SIZE = 5 # 字体尺寸
17 FONT_NOM = 20 # 显示字体数量 从0开始
18 FONT_NAME = "calibrii.ttf" # 注意字体的文件名必须与真实文件完全相同(注意ttf的大小写),且文件名不能是中文
19 FREQUENCE = 10 # 时间频度
20 times = 0 # 初始化时间
21
22
23 # 定义随机参数
24 def randomspeed() :
25 return randint(LOW_SPEED,HIGH_SPEED)
26 def randomposition() :
27 return randint(0,SCREEN_WIDTH),randint(0,SCREEN_HEIGHT)
28 def randomoname() :
29 return randint(0,100000)
30 def randomvalue() :
31 return randint(0,100) # this is your own display number range
32
33
34 #class of sprite
35 class Word(pygame.sprite.Sprite) :
36 def __init__(self,bornposition) :
37 pygame.sprite.Sprite.__init__(self)
38 self.value = randomvalue()
39 self.font = pygame.font.Font(None,FONT_SIZE)
40 self.image = self.font.render(str(self.value),True,FONT_COLOR)
41 self.speed = randomspeed()
42 self.rect = self.image.get_rect()
43 self.rect.topleft = bornposition
44
45 def update(self) :
46 self.rect = self.rect.move(0,self.speed)
47 if self.rect.top > SCREEN_HEIGHT :
48 self.kill()
49
50
51 #init the available modules
52 pygame.init()
53 screen = pygame.display.set_mode((SCREEN_WIDTH,SCREEN_HEIGHT))
54 pygame.display.set_caption("ViatorSun CodeRain")
55 clock = pygame.time.Clock()
56 group = pygame.sprite.Group()
57 group_count = int(SCREEN_WIDTH / FONT_NOM)
58
59
60 #mainloop
61 while True :
62 time = clock.tick(FREQUENCE)
63 for event in pygame.event.get() :
64 if event.type == QUIT :
65 pygame.quit()
66 exit()
67
68 screen.fill((0,0,0))
69 for i in range(0,group_count) :
70 group.add(Word((i * FONT_NOM,-FONT_NOM)))
71
72 group.update()
73 group.draw(screen)
74 pygame.display.update()
75
预览效果:
十、飞机大战游戏
在这里只展示部分代码,需要的可以下载
1 # 英雄子弹类
2 class HeroBullet(Bullet):
3 def __init__(self, screen, x, y):
4 super().__init__(screen, x, y)
5
6 def move(self):
7 self.y -= settings.bullet_hero_v
8 # 判断子弹是否出界
9 if self.y <= -20:
10 return True
11
12
13 # 敌机子弹类
14 class EnemyBullet(Bullet):
15 def __init__(self, screen, x, y):
16 super().__init__(screen, x, y)
17
18 def move(self):
19 self.y += settings.bullet_enemy_v
20 # 判断子弹是否出界
21 if self.y >= settings.screen_height:
22 return True
23
24
25 # 飞机基类
26 class Plane:
27 def __init__(self, screen, style, geo):
28 self.screen = screen
29 self.image = pygame.image.load(style)
30 self.bullet_list = []
31 self.x = geo[0]
32 self.y = geo[1]
33 self.is_dead = False
34 self.finished = False
35 self.bomb_seq = ['4','4','3','3','2','2','1','1']
36
37 def __del__(self):
38 pass
39
40 def display(self):
41 for b in self.bullet_list:
42 b.display()
43 # 回收子弹
44 if b.move(): self.bullet_list.remove(b)
45
46 # 爆炸效果
47 if self.is_dead:
48 death_x = self.x
49 death_y = self.y
50 death_w = self.image.get_width()
51 death_h = self.image.get_height()
52 try:
53 bomb_image = './images/bomb'+self.bomb_seq.pop()+'.png'
54 self.image = pygame.image.load(bomb_image)
55 except:
56 self.image = pygame.image.load('./images/bomb4.png')
57 self.finished = True
58 finally:
59 x = death_x + (death_w - self.image.get_width())/2
60 y = death_y + (death_h - self.image.get_height())/2
61 self.screen.blit(self.image, (x, y))
62
63 else:
64 # 重新绘制飞机
65 self.screen.blit(self.image, (self.x, self.y))
66
67 def fire(self):
68 self.bullet_list.append(Bullet(self.screen, self.x, self.y))
69 print(len(self.bullet_list))
70
71 def over(self):
72 #print("Oops: plane over ...")
73 #del self
74 return self.finished
75
76
77 # 英雄飞机
78 class HeroPlane(Plane):
79 def __init__(self, screen):
80 # 英雄机初始位置
81 geo = (200, 600)
82 super().__init__(screen, settings.hero_style, geo)
83
84 self.step = settings.move_step
85 # 英雄机移动范围
86 self.limit_left = -(self.image.get_width()/2)+10
87 self.limit_right = settings.screen_width-self.image.get_width()/2-10
88 self.limit_top = 5
89 self.limit_bottom = settings.screen_height-self.image.get_height()
90
91 def fire(self):
92 self.bullet_list.append(HeroBullet(self.screen, self.x+53, self.y))
93
94 def move_left(self):
95 if self.x <= self.limit_left:
96 pass
97 else:
98 self.x -= self.step
99
100 def move_right(self):
101 if self.x >= self.limit_right:
102 pass
103 else:
104 self.x += self.step
105
106 def move_up(self):
107 if self.y <= self.limit_top:
108 pass
109 else:
110 self.y -= self.step
111
112 def move_down(self):
113 if self.y >= self.limit_bottom:
114 pass
115 else:
116 self.y += self.step
预览效果:
后期我会把这个太空飞机大战的源码地址分享到这里,感谢各位支持!