当前位置:   article > 正文

简单的python有趣小程序,python200行有趣小程序_python简单小程序

python简单小程序

本篇文章给大家谈谈简单的python有趣小程序,以及python200行有趣小程序,希望对各位有所帮助,不要忘了收藏本站喔。

一.经典的俄罗斯方块

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. master.bind('<space>',self.Space)
  10. master.bind('<Control-Shift-Key-F12>',self.Play)
  11. master.bind('<Key-P>',self.Pause)
  12. master.bind('<Key-S>',self.StartByS)
  13. # rgb颜色值
  14. self.backg="#%02x%02x%02x" % (120,150,30) #大背景
  15. self.frontg="#%02x%02x%02x" % (40,120,150) #下一个形状颜色
  16. self.nextg="#%02x%02x%02x" % (150,100,100) #小背景
  17. self.flashg="#%02x%02x%02x" % (210,130,100) #炸的颜色
  18. self.LineDisplay=Label(master,text='Lines: ',bg='black',fg='red')
  19. self.Line=Label(master,text='0',bg='black',fg='red')
  20. self.ScoreDisplay=Label(master,text='Score: ',bg='black',fg='red')
  21. self.Score=Label(master,text='0',bg='black',fg='red')
  22. self.SpendTimeDisplay=Label(master,text='Time: ',bg='black',fg='red')
  23. self.SpendTime=Label(master,text='0.0',bg='black',fg='red')
  24. self.LineDisplay.grid(row=HEIGHT-2,column=WIDTH,columnspan=2)
  25. self.Line.grid(row=HEIGHT-2,column=WIDTH+2,columnspan=3)
  26. self.ScoreDisplay.grid(row=HEIGHT-1,column=WIDTH,columnspan=2)
  27. self.Score.grid(row=HEIGHT-1,column=WIDTH+2,columnspan=3)
  28. self.SpendTimeDisplay.grid(row=HEIGHT-4,column=WIDTH,columnspan=2)
  29. self.SpendTime.grid(row=HEIGHT-4,column=WIDTH+2,columnspan=3)
  30. self.TotalTime=0.0
  31. self.TotalLine=0
  32. self.TotalScore=0
  33. #游戏结束
  34. self.isgameover=FALSE
  35. #暂停
  36. self.isPause=FALSE
  37. #开始
  38. self.isStart=FALSE
  39. self.NextList=[] #整个小背景
  40. self.NextRowList=[] #一行小背景
  41. self.px=0
  42. self.py=0 #记录方块参考点
  43. #渲染小背景
  44. r=0;c=0
  45. for k in range(4*4):
  46. LN=Label(master,text=' ',bg=str(self.nextg),fg='white',relief=FLAT,bd=3)
  47. LN.grid(row=r,column=WIDTH+c,sticky=N+E+S+W)
  48. self.NextRowList.append(LN)
  49. c=c+1
  50. if c>=4:
  51. r=r+1;c=0
  52. self.NextList.append(self.NextRowList)
  53. self.NextRowList=[]
  54. #渲染大背景
  55. self.BlockList=[]
  56. self.BlockRowList=[]
  57. self.LabelList=[]
  58. self.LabelRowList=[]
  59. row=0;col=0
  60. for i in range(HEIGHT*WIDTH):
  61. L=Label(master,text=' ',bg=str(self.backg),fg='white',relief=FLAT,bd=4)
  62. L.grid(row=row,column=col,sticky=N+E+S+W)
  63. L.row=row;L.col=col;L.isactive=PASSIVE
  64. self.BlockRowList.append(0); #大背景每个格子初始化为0值
  65. self.LabelRowList.append(L)
  66. col=col+1
  67. if col>=WIDTH:
  68. row=row+1;col=0
  69. self.BlockList.append(self.BlockRowList)
  70. self.LabelList.append(self.LabelRowList)
  71. self.BlockRowList=[]
  72. self.LabelRowList=[]
  73. #file
  74. fw=open('text.txt','a')
  75. fw.close()
  76. hasHead=FALSE
  77. f=open('text.txt','r')
  78. if f.read(5)=='score':
  79. hasHead=TRUE
  80. f.close()
  81. self.file=open('text.txt','a')
  82. if hasHead==FALSE:
  83. self.file.write('score line time scorePtime linePtime scorePline date/n')
  84. self.file.flush()
  85. self.time=1000
  86. self.OnTimer()

2.实现俄罗斯方块的翻转

  1. # 俄罗斯方块的翻转
  2. def Up(self,event):
  3. BL=self.BlockList #格子的值
  4. LL=self.LabelList #格子Label
  5. Moveable=TRUE #是否可旋转
  6. #代码编写开始
  7. nowStyle = style[self.xnow][(self.ynow)]
  8. newStyle = style[self.xnow][(self.ynow+1)%4] #算出下一俄罗斯方块
  9. self.ynow = (self.ynow+1)%4 #此行代码非常重要,否则响应UP时,只能变第一次
  10. print("nowStyle:"+str(nowStyle)+"=====>>newStyle:"+str(newStyle))
  11. #根据现有形状中每个label的坐标计算出旋转后目标坐标(x,y)
  12. SourceList=[];DestList=[]
  13. for i in range(4):
  14. SourceList.append([ nowStyle[i][0]+self.px, nowStyle[i][1]+self.py])
  15. x = newStyle[i][0]+self.px
  16. y = newStyle[i][1]+self.py
  17. DestList.append([x, y])
  18. if x<0 or x>=HEIGHT or y<0 or y>=WIDTH : #or BL[x][y]==1 or LL[x][y].isactive==PASSIVE
  19. Moveable=FALSE
  20. if Moveable==TRUE:
  21. for i in range(len(SourceList)):
  22. self.Empty(SourceList[i][0],SourceList[i][1])
  23. for i in range(len(DestList)):
  24. self.Fill(DestList[i][0],DestList[i][1])
  25. def Left(self,event):
  26. BL=self.BlockList;LL=self.LabelList
  27. Moveable=TRUE
  28. for i in range(HEIGHT):
  29. for j in range(WIDTH):
  30. if LL[i][j].isactive==ACTIVE and j-1<0:Moveable=FALSE
  31. 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
  32. if Moveable==TRUE:
  33. self.py-=1
  34. for i in range(HEIGHT):
  35. for j in range(WIDTH):
  36. if j-1>=0 and LL[i][j].isactive==ACTIVE and BL[i][j-1]==0:
  37. self.Fill(i,j-1);self.Empty(i,j)
  38. def Right(self,event):
  39. BL=self.BlockList;LL=self.LabelList
  40. Moveable=TRUE
  41. for i in range(HEIGHT):
  42. for j in range(WIDTH):
  43. if LL[i][j].isactive==ACTIVE and j+1>=WIDTH:Moveable=FALSE
  44. 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
  45. if Moveable==TRUE:
  46. self.py+=1
  47. for i in range(HEIGHT-1,-1,-1):
  48. for j in range(WIDTH-1,-1,-1):
  49. if j+1<WIDTH and LL[i][j].isactive==ACTIVE and BL[i][j+1]==0:
  50. self.Fill(i,j+1);self.Empty(i,j)
  51. def Down(self,event):
  52. BL=self.BlockList;LL=self.LabelList
  53. Moveable=TRUE
  54. for i in range(HEIGHT):
  55. for j in range(WIDTH):
  56. if LL[i][j].isactive==ACTIVE and i+1>=HEIGHT:Moveable=FALSE
  57. 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
  58. if Moveable==TRUE and self.isStart :
  59. self.px+=1
  60. for i in range(HEIGHT-1,-1,-1):
  61. for j in range(WIDTH-1,-1,-1):
  62. if i+1<HEIGHT and LL[i][j].isactive==ACTIVE and BL[i+1][j]==0:
  63. self.Fill(i+1,j);self.Empty(i,j);
  64. if Moveable==FALSE:
  65. for i in range(HEIGHT):
  66. for j in range(WIDTH):
  67. LL[i][j].isactive=PASSIVE
  68. self.JudgeLineFill()
  69. self.Start()
  70. if self.isgameover==TRUE:showinfo('T_T','The game is over!');self.Distroy();return FALSE
  71. for i in range(4):
  72. for j in range(4):
  73. self.NextEmpty(i,j)
  74. self.Rnd()
  75. return Moveable
  76. def Space(self,event):
  77. while 1:
  78. 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. HEIGHT = 20
  8. #俄罗斯方块界面的宽度
  9. WIDTH = 10
  10. ACTIVE = 1
  11. PASSIVE = 0
  12. TRUE = 1
  13. FALSE = 0
  14. style = [
  15. [[(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
  16. [[(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
  17. [[(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
  18. [[(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
  19. [[(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
  20. [[(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)]],#田
  21. [[(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)]]#长条
  22. ]
  23. root=Tk();
  24. root.title('俄罗斯方块')
  25. class App(Frame):
  26. def __init__(self,master):
  27. Frame.__init__(self)
  28. master.bind('<Up>',self.Up)
  29. master.bind('<Left>',self.Left)
  30. master.bind('<Right>',self.Right)
  31. master.bind('<Down>',self.Down)
  32. master.bind('<space>',self.Space)
  33. master.bind('<Control-Shift-Key-F12>',self.Play)
  34. master.bind('<Key-P>',self.Pause)
  35. master.bind('<Key-S>',self.StartByS)
  36. # rgb颜色值
  37. self.backg="#%02x%02x%02x" % (120,150,30) #大背景
  38. self.frontg="#%02x%02x%02x" % (40,120,150) #下一个形状颜色
  39. self.nextg="#%02x%02x%02x" % (150,100,100) #小背景
  40. self.flashg="#%02x%02x%02x" % (210,130,100) #炸的颜色
  41. self.LineDisplay=Label(master,text='Lines: ',bg='black',fg='red')
  42. self.Line=Label(master,text='0',bg='black',fg='red')
  43. self.ScoreDisplay=Label(master,text='Score: ',bg='black',fg='red')
  44. self.Score=Label(master,text='0',bg='black',fg='red')
  45. self.SpendTimeDisplay=Label(master,text='Time: ',bg='black',fg='red')
  46. self.SpendTime=Label(master,text='0.0',bg='black',fg='red')
  47. self.LineDisplay.grid(row=HEIGHT-2,column=WIDTH,columnspan=2)
  48. self.Line.grid(row=HEIGHT-2,column=WIDTH+2,columnspan=3)
  49. self.ScoreDisplay.grid(row=HEIGHT-1,column=WIDTH,columnspan=2)
  50. self.Score.grid(row=HEIGHT-1,column=WIDTH+2,columnspan=3)
  51. self.SpendTimeDisplay.grid(row=HEIGHT-4,column=WIDTH,columnspan=2)
  52. self.SpendTime.grid(row=HEIGHT-4,column=WIDTH+2,columnspan=3)
  53. self.TotalTime=0.0
  54. self.TotalLine=0
  55. self.TotalScore=0
  56. #游戏结束
  57. self.isgameover=FALSE
  58. #暂停
  59. self.isPause=FALSE
  60. #开始
  61. self.isStart=FALSE
  62. self.NextList=[] #整个小背景
  63. self.NextRowList=[] #一行小背景
  64. self.px=0
  65. self.py=0 #记录方块参考点
  66. #渲染小背景
  67. r=0;c=0
  68. for k in range(4*4):
  69. LN=Label(master,text=' ',bg=str(self.nextg),fg='white',relief=FLAT,bd=3)
  70. LN.grid(row=r,column=WIDTH+c,sticky=N+E+S+W)
  71. self.NextRowList.append(LN)
  72. c=c+1
  73. if c>=4:
  74. r=r+1;c=0
  75. self.NextList.append(self.NextRowList)
  76. self.NextRowList=[]
  77. #渲染大背景
  78. self.BlockList=[]
  79. self.BlockRowList=[]
  80. self.LabelList=[]
  81. self.LabelRowList=[]
  82. row=0;col=0
  83. for i in range(HEIGHT*WIDTH):
  84. L=Label(master,text=' ',bg=str(self.backg),fg='white',relief=FLAT,bd=4)
  85. L.grid(row=row,column=col,sticky=N+E+S+W)
  86. L.row=row;L.col=col;L.isactive=PASSIVE
  87. self.BlockRowList.append(0); #大背景每个格子初始化为0值
  88. self.LabelRowList.append(L)
  89. col=col+1
  90. if col>=WIDTH:
  91. row=row+1;col=0
  92. self.BlockList.append(self.BlockRowList)
  93. self.LabelList.append(self.LabelRowList)
  94. self.BlockRowList=[]
  95. self.LabelRowList=[]
  96. #file
  97. fw=open('text.txt','a')
  98. fw.close()
  99. hasHead=FALSE
  100. f=open('text.txt','r')
  101. if f.read(5)=='score':
  102. hasHead=TRUE
  103. f.close()
  104. self.file=open('text.txt','a')
  105. if hasHead==FALSE:
  106. self.file.write('score line time scorePtime linePtime scorePline date/n')
  107. self.file.flush()
  108. self.time=1000
  109. self.OnTimer()
  110. def __del__(self):
  111. #self.file.close()
  112. pass
  113. def Pause(self,event):
  114. self.isPause=1-self.isPause
  115. def Up(self,event):
  116. BL=self.BlockList #格子的值
  117. LL=self.LabelList #格子Label
  118. Moveable=TRUE #是否可旋转
  119. #代码编写开始
  120. nowStyle = style[self.xnow][(self.ynow)]
  121. newStyle = style[self.xnow][(self.ynow+1)%4] #算出下一俄罗斯方块
  122. self.ynow = (self.ynow+1)%4 #此行代码非常重要,否则响应UP时,只能变第一次
  123. print("nowStyle:"+str(nowStyle)+"=====>>newStyle:"+str(newStyle))
  124. #根据现有形状中每个label的坐标计算出旋转后目标坐标(x,y)
  125. SourceList=[];DestList=[]
  126. for i in range(4):
  127. SourceList.append([ nowStyle[i][0]+self.px, nowStyle[i][1]+self.py])
  128. x = newStyle[i][0]+self.px
  129. y = newStyle[i][1]+self.py
  130. DestList.append([x, y])
  131. if x<0 or x>=HEIGHT or y<0 or y>=WIDTH : #or BL[x][y]==1 or LL[x][y].isactive==PASSIVE
  132. Moveable=FALSE
  133. if Moveable==TRUE:
  134. for i in range(len(SourceList)):
  135. self.Empty(SourceList[i][0],SourceList[i][1])
  136. for i in range(len(DestList)):
  137. self.Fill(DestList[i][0],DestList[i][1])
  138. def Left(self,event):
  139. BL=self.BlockList;LL=self.LabelList
  140. Moveable=TRUE
  141. for i in range(HEIGHT):
  142. for j in range(WIDTH):
  143. if LL[i][j].isactive==ACTIVE and j-1<0:Moveable=FALSE
  144. 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
  145. if Moveable==TRUE:
  146. self.py-=1
  147. for i in range(HEIGHT):
  148. for j in range(WIDTH):
  149. if j-1>=0 and LL[i][j].isactive==ACTIVE and BL[i][j-1]==0:
  150. self.Fill(i,j-1);self.Empty(i,j)
  151. def Right(self,event):
  152. BL=self.BlockList;LL=self.LabelList
  153. Moveable=TRUE
  154. for i in range(HEIGHT):
  155. for j in range(WIDTH):
  156. if LL[i][j].isactive==ACTIVE and j+1>=WIDTH:Moveable=FALSE
  157. 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
  158. if Moveable==TRUE:
  159. self.py+=1
  160. for i in range(HEIGHT-1,-1,-1):
  161. for j in range(WIDTH-1,-1,-1):
  162. if j+1<WIDTH and LL[i][j].isactive==ACTIVE and BL[i][j+1]==0:
  163. self.Fill(i,j+1);self.Empty(i,j)
  164. def Down(self,event):
  165. BL=self.BlockList;LL=self.LabelList
  166. Moveable=TRUE
  167. for i in range(HEIGHT):
  168. for j in range(WIDTH):
  169. if LL[i][j].isactive==ACTIVE and i+1>=HEIGHT:Moveable=FALSE
  170. 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
  171. if Moveable==TRUE and self.isStart :
  172. self.px+=1
  173. for i in range(HEIGHT-1,-1,-1):
  174. for j in range(WIDTH-1,-1,-1):
  175. if i+1<HEIGHT and LL[i][j].isactive==ACTIVE and BL[i+1][j]==0:
  176. self.Fill(i+1,j);self.Empty(i,j);
  177. if Moveable==FALSE:
  178. for i in range(HEIGHT):
  179. for j in range(WIDTH):
  180. LL[i][j].isactive=PASSIVE
  181. self.JudgeLineFill()
  182. self.Start()
  183. if self.isgameover==TRUE:showinfo('T_T','The game is over!');self.Distroy();return FALSE
  184. for i in range(4):
  185. for j in range(4):
  186. self.NextEmpty(i,j)
  187. self.Rnd()
  188. return Moveable
  189. def Space(self,event):
  190. while 1:
  191. if self.Down(0)==FALSE:break
  192. def OnTimer(self):
  193. if self.isStart==TRUE and self.isPause==FALSE:
  194. self.TotalTime = self.TotalTime + float(self.time)/1000
  195. self.SpendTime.config(text=str(self.TotalTime))
  196. if self.isPause==FALSE:
  197. self.Down(0)
  198. if self.TotalScore>=1000:self.time=900
  199. if self.TotalScore>=2000:self.time=750
  200. if self.TotalScore>=3000:self.time=600
  201. if self.TotalScore>=4000:self.time=400
  202. self.after(self.time,self.OnTimer) #随着分数增大,俄罗斯方块下降速度加快
  203. def JudgeLineFill(self):
  204. BL=self.BlockList;LL=self.LabelList
  205. count=0;LineList=[]
  206. for i in range(WIDTH):LineList.append(1)
  207. #display flash
  208. for i in range(HEIGHT):
  209. if BL[i]==LineList:
  210. count=count+1
  211. for k in range(WIDTH):
  212. LL[i][k].config(bg=str(self.flashg))
  213. LL[i][k].update()
  214. if count!=0:self.after(100)
  215. #delete block
  216. for i in range(HEIGHT):
  217. if BL[i]==LineList:
  218. #count=count+1
  219. for j in range(i,0,-1):
  220. for k in range(WIDTH):
  221. BL[j][k]=BL[j-1][k]
  222. LL[j][k]['relief']=LL[j-1][k].cget('relief')
  223. LL[j][k]['bg']=LL[j-1][k].cget('bg')
  224. for l in range(WIDTH):
  225. BL[0][l]=0
  226. LL[0][l].config(relief=FLAT,bg=str(self.backg))
  227. self.TotalLine=self.TotalLine+count
  228. if count==1:self.TotalScore=self.TotalScore+1*WIDTH
  229. if count==2:self.TotalScore=self.TotalScore+3*WIDTH
  230. if count==3:self.TotalScore=self.TotalScore+6*WIDTH
  231. if count==4:self.TotalScore=self.TotalScore+10*WIDTH
  232. self.Line.config(text=str(self.TotalLine))
  233. self.Score.config(text=str(self.TotalScore))
  234. def Fill(self,i,j):
  235. if j<0:return
  236. if self.BlockList[i][j]==1:self.isgameover=TRUE
  237. self.BlockList[i][j]=1
  238. self.LabelList[i][j].isactive=ACTIVE
  239. self.LabelList[i][j].config(relief=RAISED,bg=str(self.frontg))
  240. def Empty(self,i,j):
  241. self.BlockList[i][j]=0
  242. self.LabelList[i][j].isactive=PASSIVE
  243. self.LabelList[i][j].config(relief=FLAT,bg=str(self.backg))
  244. def Play(self,event):
  245. showinfo('Made in China','^_^')
  246. def NextFill(self,i,j):
  247. self.NextList[i][j].config(relief=RAISED,bg=str(self.frontg))
  248. def NextEmpty(self,i,j):
  249. self.NextList[i][j].config(relief=FLAT,bg=str(self.nextg))
  250. def Distroy(self):
  251. #save
  252. if self.TotalScore!=0:
  253. #cehkongfu
  254. savestr='%-9u%-8u%-8.2f%-14.2f%-13.2f%-14.2f%s/n' % (
  255. self.TotalScore,self.TotalLine,self.TotalTime
  256. ,self.TotalScore/self.TotalTime
  257. ,self.TotalLine/self.TotalTime
  258. ,float(self.TotalScore)/self.TotalLine
  259. ,time.strftime('%Y-%m-%d %H:%M:%S',time.localtime()))
  260. self.file.seek(0,2)
  261. self.file.write(savestr)
  262. self.file.flush()
  263. for i in range(HEIGHT):
  264. for j in range(WIDTH):
  265. self.Empty(i,j)
  266. self.TotalLine=0;self.TotalScore=0;self.TotalTime=0.0
  267. self.Line.config(text=str(self.TotalLine))
  268. self.Score.config(text=str(self.TotalScore))
  269. self.SpendTime.config(text=str(self.TotalTime))
  270. self.isgameover=FALSE
  271. self.isStart=FALSE
  272. self.time=1000
  273. for i in range(4):
  274. for j in range(4):
  275. self.NextEmpty(i,j)
  276. #游戏开始方块
  277. def Start(self):
  278. nextStyle = style[self.x][self.y] #下一形状
  279. self.xnow = self.x
  280. self.ynow = self.y #记录大背景中的方块
  281. self.py = random.randint(0,6)
  282. print("给py赋任意值:"+str(self.py))
  283. self.px = 0
  284. for ii in range(4):
  285. self.Fill(int(nextStyle[ii][0]),int(nextStyle[ii][1])+self.py)
  286. self.isStart=TRUE #游戏开始
  287. #预处理方块
  288. def Rnd(self):
  289. self.x=random.randint(0,6)
  290. self.y=random.randint(0,3)
  291. nextStyle = style[self.x][self.y] #下一形状
  292. for ii in range(4):
  293. self.NextFill(int(nextStyle[ii][0]),int(nextStyle[ii][1]))
  294. #游戏开始给出一次任意形状的方块
  295. def RndFirst(self):
  296. self.x=random.randint(0,6) #选择第一个方块style
  297. self.y=random.randint(0,3)
  298. def Show(self):
  299. self.file.seek(0)
  300. strHeadLine=self.file.readline()
  301. dictLine={}
  302. strTotalLine=''
  303. for OneLine in self.file.readlines():
  304. temp=int(OneLine[:5])
  305. dictLine[temp]=OneLine
  306. list=sorted(dictLine.items(),key=lambda d:d[0])
  307. ii=0
  308. for onerecord in reversed(list):
  309. ii=ii+1
  310. if ii<11:
  311. strTotalLine+=onerecord[1]
  312. showinfo('Ranking', strHeadLine+strTotalLine)
  313. def StartByS(self,event):
  314. self.RndFirst()
  315. self.Start()
  316. self.Rnd()
  317. def Start():
  318. app.RndFirst()
  319. app.Start()
  320. app.Rnd()
  321. def End():
  322. app.Distroy()
  323. def Set():
  324. print("设置功能待完善...")
  325. def Show():
  326. app.Show()
  327. #主菜单
  328. mainmenu=Menu(root)
  329. root['menu']=mainmenu
  330. #二级菜单:game
  331. gamemenu=Menu(mainmenu)
  332. mainmenu.add_cascade(label='游戏',menu=gamemenu)
  333. gamemenu.add_command(label='开始',command=Start)
  334. gamemenu.add_command(label='结束',command=End)
  335. gamemenu.add_separator()
  336. gamemenu.add_command(label='退出',command=root.quit)
  337. #二级菜单:set
  338. setmenu=Menu(mainmenu)
  339. mainmenu.add_cascade(label='设置',menu=setmenu)
  340. setmenu.add_command(label='设置',command=Set)
  341. #二级菜单:show
  342. showmenu=Menu(mainmenu)
  343. mainmenu.add_cascade(label='展示',menu=showmenu)
  344. showmenu.add_command(label='展示',command=Show)
  345. #绑定功能
  346. app=App(root)
  347. #程序入口
  348. root.mainloop()

二、经典的贪吃蛇游戏

1.项目源码

  1. import random
  2. import pygame
  3. import sys
  4. from pygame.locals import *
  5. Snakespeed = 9
  6. Window_Width = 800
  7. Window_Height = 500
  8. Cell_Size = 20 # Width and height of the cells
  9. # Ensuring that the cells fit perfectly in the window. eg if cell size was
  10. # 10 and window width or window height were 15 only 1.5 cells would
  11. # fit.
  12. assert Window_Width % Cell_Size == 0, "Window width must be a multiple of cell size."
  13. # Ensuring that only whole integer number of cells fit perfectly in the window.
  14. assert Window_Height % Cell_Size == 0, "Window height must be a multiple of cell size."
  15. Cell_W = int(Window_Width / Cell_Size) # Cell Width
  16. Cell_H = int(Window_Height / Cell_Size) # Cell Height
  17. White = (255, 255, 255)
  18. Black = (0, 0, 0)
  19. Red = (255, 0, 0) # Defining element colors for the program.
  20. Green = (0, 255, 0)
  21. DARKGreen = (0, 155, 0)
  22. DARKGRAY = (40, 40, 40)
  23. YELLOW = (255, 255, 0)
  24. Red_DARK = (150, 0, 0)
  25. BLUE = (0, 0, 255)
  26. BLUE_DARK = (0, 0, 150)
  27. BGCOLOR = Black # Background color
  28. UP = 'up'
  29. DOWN = 'down' # Defining keyboard keys.
  30. LEFT = 'left'
  31. RIGHT = 'right'
  32. HEAD = 0 # Syntactic sugar: index of the snake's head
  33. def main():
  34. global SnakespeedCLOCK, DISPLAYSURF, BASICFONT
  35. pygame.init()
  36. SnakespeedCLOCK = pygame.time.Clock()
  37. DISPLAYSURF = pygame.display.set_mode((Window_Width, Window_Height))
  38. BASICFONT = pygame.font.Font('freesansbold.ttf', 18)
  39. pygame.display.set_caption('Snake')
  40. showStartScreen()
  41. while True:
  42. runGame()
  43. showGameOverScreen()
  44. def runGame():
  45. # Set a random start point.
  46. startx = random.randint(5, Cell_W - 6)
  47. starty = random.randint(5, Cell_H - 6)
  48. wormCoords = [{'x': startx, 'y': starty},
  49. {'x': startx - 1, 'y': starty},
  50. {'x': startx - 2, 'y': starty}]
  51. direction = RIGHT
  52. # Start the apple in a random place.
  53. apple = getRandomLocation()
  54. while True: # main game loop
  55. for event in pygame.event.get(): # event handling loop
  56. if event.type == QUIT:
  57. terminate()
  58. elif event.type == KEYDOWN:
  59. if (event.key == K_LEFT) and direction != RIGHT:
  60. direction = LEFT
  61. elif (event.key == K_RIGHT) and direction != LEFT:
  62. direction = RIGHT
  63. elif (event.key == K_UP) and direction != DOWN:
  64. direction = UP
  65. elif (event.key == K_DOWN) and direction != UP:
  66. direction = DOWN
  67. elif event.key == K_ESCAPE:
  68. terminate()
  69. # check if the Snake has hit itself or the edge
  70. if wormCoords[HEAD]['x'] == -1 or wormCoords[HEAD]['x'] == Cell_W or wormCoords[HEAD]['y'] == -1 or \
  71. wormCoords[HEAD]['y'] == Cell_H:
  72. return # game over
  73. for wormBody in wormCoords[1:]:
  74. if wormBody['x'] == wormCoords[HEAD]['x'] and wormBody['y'] == wormCoords[HEAD]['y']:
  75. return # game over
  76. # check if Snake has eaten an apply
  77. if wormCoords[HEAD]['x'] == apple['x'] and wormCoords[HEAD]['y'] == apple['y']:
  78. # don't remove worm's tail segment
  79. apple = getRandomLocation() # set a new apple somewhere
  80. else:
  81. del wormCoords[-1] # remove worm's tail segment
  82. # move the worm by adding a segment in the direction it is moving
  83. if direction == UP:
  84. newHead = {'x': wormCoords[HEAD]['x'],
  85. 'y': wormCoords[HEAD]['y'] - 1}
  86. elif direction == DOWN:
  87. newHead = {'x': wormCoords[HEAD]['x'],
  88. 'y': wormCoords[HEAD]['y'] + 1}
  89. elif direction == LEFT:
  90. newHead = {'x': wormCoords[HEAD][
  91. 'x'] - 1, 'y': wormCoords[HEAD]['y']}
  92. elif direction == RIGHT:
  93. newHead = {'x': wormCoords[HEAD][
  94. 'x'] + 1, 'y': wormCoords[HEAD]['y']}
  95. wormCoords.insert(0, newHead)
  96. DISPLAYSURF.fill(BGCOLOR)
  97. drawGrid()
  98. drawWorm(wormCoords)
  99. drawApple(apple)
  100. drawScore(len(wormCoords) - 3)
  101. pygame.display.update()
  102. SnakespeedCLOCK.tick(Snakespeed)
  103. def drawPressKeyMsg():
  104. pressKeySurf = BASICFONT.render('Press a key to play.', True, White)
  105. pressKeyRect = pressKeySurf.get_rect()
  106. pressKeyRect.topleft = (Window_Width - 200, Window_Height - 30)
  107. DISPLAYSURF.blit(pressKeySurf, pressKeyRect)
  108. def checkForKeyPress():
  109. if len(pygame.event.get(QUIT)) > 0:
  110. terminate()
  111. keyUpEvents = pygame.event.get(KEYUP)
  112. if len(keyUpEvents) == 0:
  113. return None
  114. if keyUpEvents[0].key == K_ESCAPE:
  115. terminate()
  116. return keyUpEvents[0].key
  117. def showStartScreen():
  118. titleFont = pygame.font.Font('freesansbold.ttf', 100)
  119. titleSurf1 = titleFont.render('Snake!', True, White, DARKGreen)
  120. degrees1 = 0
  121. degrees2 = 0
  122. while True:
  123. DISPLAYSURF.fill(BGCOLOR)
  124. rotatedSurf1 = pygame.transform.rotate(titleSurf1, degrees1)
  125. rotatedRect1 = rotatedSurf1.get_rect()
  126. rotatedRect1.center = (Window_Width / 2, Window_Height / 2)
  127. DISPLAYSURF.blit(rotatedSurf1, rotatedRect1)
  128. drawPressKeyMsg()
  129. if checkForKeyPress():
  130. pygame.event.get() # clear event queue
  131. return
  132. pygame.display.update()
  133. SnakespeedCLOCK.tick(Snakespeed)
  134. degrees1 += 3 # rotate by 3 degrees each frame
  135. degrees2 += 7 # rotate by 7 degrees each frame
  136. def terminate():
  137. pygame.quit()
  138. sys.exit()
  139. def getRandomLocation():
  140. return {'x': random.randint(0, Cell_W - 1), 'y': random.randint(0, Cell_H - 1)}
  141. def showGameOverScreen():
  142. gameOverFont = pygame.font.Font('freesansbold.ttf', 100)
  143. gameSurf = gameOverFont.render('Game', True, White)
  144. overSurf = gameOverFont.render('Over', True, White)
  145. gameRect = gameSurf.get_rect()
  146. overRect = overSurf.get_rect()
  147. gameRect.midtop = (Window_Width / 2, 10)
  148. overRect.midtop = (Window_Width / 2, gameRect.height + 10 + 25)
  149. DISPLAYSURF.blit(gameSurf, gameRect)
  150. DISPLAYSURF.blit(overSurf, overRect)
  151. drawPressKeyMsg()
  152. pygame.display.update()
  153. pygame.time.wait(500)
  154. checkForKeyPress() # clear out any key presses in the event queue
  155. while True:
  156. if checkForKeyPress():
  157. pygame.event.get() # clear event queue
  158. return
  159. def drawScore(score):
  160. scoreSurf = BASICFONT.render('Score: %s' % (score), True, White)
  161. scoreRect = scoreSurf.get_rect()
  162. scoreRect.topleft = (Window_Width - 120, 10)
  163. DISPLAYSURF.blit(scoreSurf, scoreRect)
  164. def drawWorm(wormCoords):
  165. for coord in wormCoords:
  166. x = coord['x'] * Cell_Size
  167. y = coord['y'] * Cell_Size
  168. wormSegmentRect = pygame.Rect(x, y, Cell_Size, Cell_Size)
  169. pygame.draw.rect(DISPLAYSURF, DARKGreen, wormSegmentRect)
  170. wormInnerSegmentRect = pygame.Rect(
  171. x + 4, y + 4, Cell_Size - 8, Cell_Size - 8)
  172. pygame.draw.rect(DISPLAYSURF, Green, wormInnerSegmentRect)
  173. def drawApple(coord):
  174. x = coord['x'] * Cell_Size
  175. y = coord['y'] * Cell_Size
  176. appleRect = pygame.Rect(x, y, Cell_Size, Cell_Size)
  177. pygame.draw.rect(DISPLAYSURF, Red, appleRect)
  178. def drawGrid():
  179. for x in range(0, Window_Width, Cell_Size): # draw vertical lines
  180. pygame.draw.line(DISPLAYSURF, DARKGRAY, (x, 0), (x, Window_Height))
  181. for y in range(0, Window_Height, Cell_Size): # draw horizontal lines
  182. pygame.draw.line(DISPLAYSURF, DARKGRAY, (0, y), (Window_Width, y))
  183. if __name__ == '__main__':
  184. try:
  185. main()
  186. except SystemExit:
  187. 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. YouLikeMe()
  21. window=Tk()
  22. label=Label(window,text='关闭窗口也改变不了你喜欢我的事实')
  23. label.place(x=2,y=80)
  24. button=Button(window,text='确定',command=window.destroy)
  25. button.place(x=80,y=150)
  26. window.mainloop()

预览效果:
在这里插入图片描述
在这里插入图片描述

四、画玫瑰花

  1. import turtle
  2. import time
  3. turtle.speed(5) #画笔移动的速度
  4. # 设置初始位置
  5. turtle.penup() #提起画笔,移动画笔但并不会绘制图形
  6. turtle.left(90) #逆时针转动画笔90度
  7. turtle.fd(200)
  8. turtle.pendown() #放下画笔,移动画笔即开始绘制
  9. turtle.right(90)
  10. #设置画笔的大小
  11. turtle.pensize(2)
  12. # 花蕊
  13. turtle.fillcolor("red") #填充颜色
  14. turtle.begin_fill() #开始填充
  15. turtle.circle(10,180)
  16. turtle.circle(25,110)
  17. turtle.left(50)
  18. turtle.circle(60,45)
  19. turtle.circle(20,170)
  20. turtle.right(24)
  21. turtle.fd(30)
  22. turtle.left(10)
  23. turtle.circle(30,110)
  24. turtle.fd(20)
  25. turtle.left(40)
  26. turtle.circle(90,70)
  27. turtle.circle(30,150)
  28. turtle.right(30)
  29. turtle.fd(15)
  30. turtle.circle(80,90)
  31. turtle.left(15)
  32. turtle.fd(45)
  33. turtle.right(165)
  34. turtle.fd(20)
  35. turtle.left(155)
  36. turtle.circle(150,80)
  37. turtle.left(50)
  38. turtle.circle(150,90)
  39. turtle.end_fill() #结束填充
  40. # 花瓣1
  41. turtle.left(150)
  42. turtle.circle(-90,70)
  43. turtle.left(20)
  44. turtle.circle(75,105)
  45. turtle.setheading(60)
  46. turtle.circle(80,98)
  47. turtle.circle(-90,40)
  48. # 花瓣2
  49. turtle.left(180)
  50. turtle.circle(90,40)
  51. turtle.circle(-80,98)
  52. turtle.setheading(-83)
  53. # 叶子1
  54. turtle.fd(30)
  55. turtle.left(90)
  56. turtle.fd(25)
  57. turtle.left(45)
  58. turtle.fillcolor("green")
  59. turtle.begin_fill()
  60. turtle.circle(-80,90)
  61. turtle.right(90)
  62. turtle.circle(-80,90)
  63. turtle.end_fill()
  64. turtle.right(135)
  65. turtle.fd(60)
  66. turtle.left(180)
  67. turtle.fd(85)
  68. turtle.left(90)
  69. turtle.fd(80)
  70. # 叶子2
  71. turtle.right(90)
  72. turtle.right(45)
  73. turtle.fillcolor("green")
  74. turtle.begin_fill()
  75. turtle.circle(80,90)
  76. turtle.left(90)
  77. turtle.circle(80,90)
  78. turtle.end_fill()
  79. turtle.left(135)
  80. turtle.fd(60)
  81. turtle.left(180)
  82. turtle.fd(60)
  83. turtle.right(90)
  84. turtle.circle(200,50) #画一个圆 200 是半径,50 是弧度
  85. #不让自动退出,放在程序的最后一行
  86. #不然画画结束后会自动退出
  87. 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. import turtle as t
  3. t.screensize(400, 300)
  4. t.pensize(4) # 设置画笔的大小
  5. t.colormode(255) # 设置GBK颜色范围为0-255
  6. t.color((255, 155, 192), "pink") # 设置画笔颜色和填充颜色(pink)
  7. t.setup(840, 500) # 设置主窗口的大小为840*500
  8. t.speed(10) # 设置画笔速度为10
  9. # 鼻子
  10. t.pu() # 提笔
  11. t.goto(-100, 100) # 画笔前往坐标(-100,100)
  12. t.pd() # 下笔
  13. t.seth(-30) # 笔的角度为-30°
  14. t.begin_fill() # 外形填充的开始标志
  15. a = 0.4
  16. for i in range(120):
  17. if 0 <= i < 30 or 60 <= i < 90:
  18. a = a + 0.08
  19. t.lt(3) # 向左转3度
  20. t.fd(a) # 向前走a的步长
  21. else:
  22. a = a - 0.08
  23. t.lt(3)
  24. t.fd(a)
  25. t.end_fill() # 依据轮廓填充
  26. t.pu() # 提笔
  27. t.seth(90) # 笔的角度为90度
  28. t.fd(25) # 向前移动25
  29. t.seth(0) # 转换画笔的角度为0
  30. t.fd(10)
  31. t.pd()
  32. t.pencolor(255, 155, 192) # 设置画笔颜色
  33. t.seth(10)
  34. t.begin_fill()
  35. t.circle(5) # 画一个半径为5的圆
  36. t.color(160, 82, 45) # 设置画笔和填充颜色
  37. t.end_fill()
  38. t.pu()
  39. t.seth(0)
  40. t.fd(20)
  41. t.pd()
  42. t.pencolor(255, 155, 192)
  43. t.seth(10)
  44. t.begin_fill()
  45. t.circle(5)
  46. t.color(160, 82, 45)
  47. t.end_fill()
  48. # 头
  49. t.color((255, 155, 192), "pink")
  50. t.pu()
  51. t.seth(90)
  52. t.fd(41)
  53. t.seth(0)
  54. t.fd(0)
  55. t.pd()
  56. t.begin_fill()
  57. t.seth(180)
  58. t.circle(300, -30) # 顺时针画一个半径为300,圆心角为30°的园
  59. t.circle(100, -60)
  60. t.circle(80, -100)
  61. t.circle(150, -20)
  62. t.circle(60, -95)
  63. t.seth(161)
  64. t.circle(-300, 15)
  65. t.pu()
  66. t.goto(-100, 100)
  67. t.pd()
  68. t.seth(-30)
  69. a = 0.4
  70. for i in range(60):
  71. if 0 <= i < 30 or 60 <= i < 90:
  72. a = a + 0.08
  73. t.lt(3) # 向左转3度
  74. t.fd(a) # 向前走a的步长
  75. else:
  76. a = a - 0.08
  77. t.lt(3)
  78. t.fd(a)
  79. t.end_fill()
  80. # 耳朵
  81. t.color((255, 155, 192), "pink")
  82. t.pu()
  83. t.seth(90)
  84. t.fd(-7)
  85. t.seth(0)
  86. t.fd(70)
  87. t.pd()
  88. t.begin_fill()
  89. t.seth(100)
  90. t.circle(-50, 50)
  91. t.circle(-10, 120)
  92. t.circle(-50, 54)
  93. t.end_fill()
  94. t.pu()
  95. t.seth(90)
  96. t.fd(-12)
  97. t.seth(0)
  98. t.fd(30)
  99. t.pd()
  100. t.begin_fill()
  101. t.seth(100)
  102. t.circle(-50, 50)
  103. t.circle(-10, 120)
  104. t.circle(-50, 56)
  105. t.end_fill()
  106. # 眼睛
  107. t.color((255, 155, 192), "white")
  108. t.pu()
  109. t.seth(90)
  110. t.fd(-20)
  111. t.seth(0)
  112. t.fd(-95)
  113. t.pd()
  114. t.begin_fill()
  115. t.circle(15)
  116. t.end_fill()
  117. t.color("black")
  118. t.pu()
  119. t.seth(90)
  120. t.fd(12)
  121. t.seth(0)
  122. t.fd(-3)
  123. t.pd()
  124. t.begin_fill()
  125. t.circle(3)
  126. t.end_fill()
  127. t.color((255, 155, 192), "white")
  128. t.pu()
  129. t.seth(90)
  130. t.fd(-25)
  131. t.seth(0)
  132. t.fd(40)
  133. t.pd()
  134. t.begin_fill()
  135. t.circle(15)
  136. t.end_fill()
  137. t.color("black")
  138. t.pu()
  139. t.seth(90)
  140. t.fd(12)
  141. t.seth(0)
  142. t.fd(-3)
  143. t.pd()
  144. t.begin_fill()
  145. t.circle(3)
  146. t.end_fill()
  147. # 腮
  148. t.color((255, 155, 192))
  149. t.pu()
  150. t.seth(90)
  151. t.fd(-95)
  152. t.seth(0)
  153. t.fd(65)
  154. t.pd()
  155. t.begin_fill()
  156. t.circle(30)
  157. t.end_fill()
  158. # 嘴
  159. t.color(239, 69, 19)
  160. t.pu()
  161. t.seth(90)
  162. t.fd(15)
  163. t.seth(0)
  164. t.fd(-100)
  165. t.pd()
  166. t.seth(-80)
  167. t.circle(30, 40)
  168. t.circle(40, 80)
  169. # 身体
  170. t.color("red", (255, 99, 71))
  171. t.pu()
  172. t.seth(90)
  173. t.fd(-20)
  174. t.seth(0)
  175. t.fd(-78)
  176. t.pd()
  177. t.begin_fill()
  178. t.seth(-130)
  179. t.circle(100, 10)
  180. t.circle(300, 30)
  181. t.seth(0)
  182. t.fd(230)
  183. t.seth(90)
  184. t.circle(300, 30)
  185. t.circle(100, 3)
  186. t.color((255, 155, 192), (255, 100, 100))
  187. t.seth(-135)
  188. t.circle(-80, 63)
  189. t.circle(-150, 24)
  190. t.end_fill()
  191. # 手
  192. t.color((255, 155, 192))
  193. t.pu()
  194. t.seth(90)
  195. t.fd(-40)
  196. t.seth(0)
  197. t.fd(-27)
  198. t.pd()
  199. t.seth(-160)
  200. t.circle(300, 15)
  201. t.pu()
  202. t.seth(90)
  203. t.fd(15)
  204. t.seth(0)
  205. t.fd(0)
  206. t.pd()
  207. t.seth(-10)
  208. t.circle(-20, 90)
  209. t.pu()
  210. t.seth(90)
  211. t.fd(30)
  212. t.seth(0)
  213. t.fd(237)
  214. t.pd()
  215. t.seth(-20)
  216. t.circle(-300, 15)
  217. t.pu()
  218. t.seth(90)
  219. t.fd(20)
  220. t.seth(0)
  221. t.fd(0)
  222. t.pd()
  223. t.seth(-170)
  224. t.circle(20, 90)
  225. # 脚
  226. t.pensize(10)
  227. t.color((240, 128, 128))
  228. t.pu()
  229. t.seth(90)
  230. t.fd(-75)
  231. t.seth(0)
  232. t.fd(-180)
  233. t.pd()
  234. t.seth(-90)
  235. t.fd(40)
  236. t.seth(-180)
  237. t.color("black")
  238. t.pensize(15)
  239. t.fd(20)
  240. t.pensize(10)
  241. t.color((240, 128, 128))
  242. t.pu()
  243. t.seth(90)
  244. t.fd(40)
  245. t.seth(0)
  246. t.fd(90)
  247. t.pd()
  248. t.seth(-90)
  249. t.fd(40)
  250. t.seth(-180)
  251. t.color("black")
  252. t.pensize(15)
  253. t.fd(20)
  254. # 尾巴
  255. t.pensize(4)
  256. t.color((255, 155, 192))
  257. t.pu()
  258. t.seth(90)
  259. t.fd(70)
  260. t.seth(0)
  261. t.fd(95)
  262. t.pd()
  263. t.seth(0)
  264. t.circle(70, 20)
  265. t.circle(10, 330)
  266. t.circle(70, 30)
  267. 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. def Love():
  9. #Toplevel独立的顶级窗口,和父级标题一样
  10. love = Toplevel(window)
  11. love.geometry("360x200+540+360")
  12. love.title("好巧,我也是")
  13. label = Label(love,text="巧了,我也喜欢你",font =("微软雅黑",20))
  14. label.pack()
  15. label1 = Label(love,text="认识一下,加个微信呗",font =("微软雅黑",20))
  16. label1.pack()
  17. entry = Entry(love,font = ("微软雅黑",15))
  18. entry.pack()
  19. btn = Button(love,text = "确定",width = 10 , height = 1,command = close_all)
  20. btn.pack()
  21. love.protocol("WM_DELETE_WINDOW",closelove)
  22. def closelove():
  23. return
  24. #关闭所有的窗口 注意,如果父级窗口关了,下面的所有窗口均会关闭
  25. def close_all():
  26. #destory 销毁
  27. window.destroy()
  28. #关闭不喜欢框的X时
  29. def closenolove():
  30. messagebox.showinfo("再考虑一下","再考虑一下呗")
  31. return
  32. disLove()
  33. #点击不喜欢触发的事件
  34. def disLove():
  35. no_love = Toplevel(window)
  36. no_love.geometry("300x90+540+360")
  37. no_love.title("再考虑考虑")
  38. label = Label(no_love,text = "再考虑考虑呗!",font = ("微软雅黑",25))
  39. label.pack()
  40. btn = Button(no_love,text = "好的",width = 10 , height = 1,command = no_love.destroy)
  41. btn.pack()
  42. no_love.protocol("WM_DELETE_WINDOW",closenolove)
  43. # 创建窗口
  44. window =Tk() #类的实例化,创建窗口,window仅仅是个变量
  45. # 窗口标题
  46. window.title("你喜欢我吗?")
  47. # 窗口的大小 运用小写的x来连接
  48. window.geometry("380x400")
  49. #窗口位置(距离屏幕左上角) 运用+来连接
  50. window.geometry("+500+240") # geometry意为几何
  51. #上述可以写成window.geometry("380x200+500+245"),其中+是用来连接的
  52. #用户关闭窗口触发的事件
  53. window.protocol("WM_DELETE_WINDOW",closeWindow)
  54. # 标签控件,一般第一个参数均是父级窗口 ,这里传参为window fg设置颜色
  55. label = Label(window, text = "Hey,小姐姐", font = ("微软雅黑",15), fg="black")
  56. # 定位 grid(网格式) pack(包的方式) place(用的最少的一种,根据位置)
  57. label.grid(row=0,column =0) #默认值为 0 0
  58. label_1 = Label(window,text = "喜欢我吗?",font = ("微软雅黑",25))
  59. label_1.grid(row=1,column = 1,sticky = E) #sticky为对齐方式 N上S下W左E右
  60. # 显示图片
  61. photo = ImageTk.PhotoImage(file='Rose.jpg')
  62. imageLable = Label(window,image = photo)
  63. #column 组件所跨越的列数
  64. imageLable.grid(row=2,columnspan =2) #跨列操作
  65. # ques_image = ImageTk.PhotoImage(file='./Image/cache/{}'.format(image_name.group()))
  66. #按钮控件 点击触发command事件
  67. btn = Button(window,text="喜欢",width = 15,height=1,command = Love)
  68. btn.grid(row = 3,column = 0,sticky = W)
  69. btn1 =Button(window,text="不喜欢",command = disLove)
  70. btn1 .grid(row = 3,column = 1,sticky = E)
  71. #显示窗口 消息循环
  72. window .mainloop()

预览效果:
在这里插入图片描述
上图的素材贴在这里啦

在这里插入图片描述

九、黑客代码雨

  1. # -*- coding:utf-8 -*-
  2. #导入系统文件库
  3. import pygame
  4. import random
  5. from pygame.locals import *
  6. from random import randint
  7. #定义一些窗体参数及加载字体文件
  8. SCREEN_WIDTH = 900 # 窗体宽度
  9. SCREEN_HEIGHT = 600 # 窗体宽度
  10. LOW_SPEED = 4 # 字体移动最低速度
  11. HIGH_SPEED = 10 # 字体移动最快速度
  12. FONT_COLOR = (00,150,00) # 字体颜色
  13. FONT_SIZE = 5 # 字体尺寸
  14. FONT_NOM = 20 # 显示字体数量 从0开始
  15. FONT_NAME = "calibrii.ttf" # 注意字体的文件名必须与真实文件完全相同(注意ttf的大小写),且文件名不能是中文
  16. FREQUENCE = 10 # 时间频度
  17. times = 0 # 初始化时间
  18. # 定义随机参数
  19. def randomspeed() :
  20. return randint(LOW_SPEED,HIGH_SPEED)
  21. def randomposition() :
  22. return randint(0,SCREEN_WIDTH),randint(0,SCREEN_HEIGHT)
  23. def randomoname() :
  24. return randint(0,100000)
  25. def randomvalue() :
  26. return randint(0,100) # this is your own display number range
  27. #class of sprite
  28. class Word(pygame.sprite.Sprite) :
  29. def __init__(self,bornposition) :
  30. pygame.sprite.Sprite.__init__(self)
  31. self.value = randomvalue()
  32. self.font = pygame.font.Font(None,FONT_SIZE)
  33. self.image = self.font.render(str(self.value),True,FONT_COLOR)
  34. self.speed = randomspeed()
  35. self.rect = self.image.get_rect()
  36. self.rect.topleft = bornposition
  37. def update(self) :
  38. self.rect = self.rect.move(0,self.speed)
  39. if self.rect.top > SCREEN_HEIGHT :
  40. self.kill()
  41. #init the available modules
  42. pygame.init()
  43. screen = pygame.display.set_mode((SCREEN_WIDTH,SCREEN_HEIGHT))
  44. pygame.display.set_caption("ViatorSun CodeRain")
  45. clock = pygame.time.Clock()
  46. group = pygame.sprite.Group()
  47. group_count = int(SCREEN_WIDTH / FONT_NOM)
  48. #mainloop
  49. while True :
  50. time = clock.tick(FREQUENCE)
  51. for event in pygame.event.get() :
  52. if event.type == QUIT :
  53. pygame.quit()
  54. exit()
  55. screen.fill((0,0,0))
  56. for i in range(0,group_count) :
  57. group.add(Word((i * FONT_NOM,-FONT_NOM)))
  58. group.update()
  59. group.draw(screen)
  60. pygame.display.update()

预览效果:
在这里插入图片描述

十、飞机大战游戏

在这里只展示部分代码,需要的可以下载

  1. # 英雄子弹类
  2. class HeroBullet(Bullet):
  3. def __init__(self, screen, x, y):
  4. super().__init__(screen, x, y)
  5. def move(self):
  6. self.y -= settings.bullet_hero_v
  7. # 判断子弹是否出界
  8. if self.y <= -20:
  9. return True
  10. # 敌机子弹类
  11. class EnemyBullet(Bullet):
  12. def __init__(self, screen, x, y):
  13. super().__init__(screen, x, y)
  14. def move(self):
  15. self.y += settings.bullet_enemy_v
  16. # 判断子弹是否出界
  17. if self.y >= settings.screen_height:
  18. return True
  19. # 飞机基类
  20. class Plane:
  21. def __init__(self, screen, style, geo):
  22. self.screen = screen
  23. self.image = pygame.image.load(style)
  24. self.bullet_list = []
  25. self.x = geo[0]
  26. self.y = geo[1]
  27. self.is_dead = False
  28. self.finished = False
  29. self.bomb_seq = ['4','4','3','3','2','2','1','1']
  30. def __del__(self):
  31. pass
  32. def display(self):
  33. for b in self.bullet_list:
  34. b.display()
  35. # 回收子弹
  36. if b.move(): self.bullet_list.remove(b)
  37. # 爆炸效果
  38. if self.is_dead:
  39. death_x = self.x
  40. death_y = self.y
  41. death_w = self.image.get_width()
  42. death_h = self.image.get_height()
  43. try:
  44. bomb_image = './images/bomb'+self.bomb_seq.pop()+'.png'
  45. self.image = pygame.image.load(bomb_image)
  46. except:
  47. self.image = pygame.image.load('./images/bomb4.png')
  48. self.finished = True
  49. finally:
  50. x = death_x + (death_w - self.image.get_width())/2
  51. y = death_y + (death_h - self.image.get_height())/2
  52. self.screen.blit(self.image, (x, y))
  53. else:
  54. # 重新绘制飞机
  55. self.screen.blit(self.image, (self.x, self.y))
  56. def fire(self):
  57. self.bullet_list.append(Bullet(self.screen, self.x, self.y))
  58. print(len(self.bullet_list))
  59. def over(self):
  60. #print("Oops: plane over ...")
  61. #del self
  62. return self.finished
  63. # 英雄飞机
  64. class HeroPlane(Plane):
  65. def __init__(self, screen):
  66. # 英雄机初始位置
  67. geo = (200, 600)
  68. super().__init__(screen, settings.hero_style, geo)
  69. self.step = settings.move_step
  70. # 英雄机移动范围
  71. self.limit_left = -(self.image.get_width()/2)+10
  72. self.limit_right = settings.screen_width-self.image.get_width()/2-10
  73. self.limit_top = 5
  74. self.limit_bottom = settings.screen_height-self.image.get_height()
  75. def fire(self):
  76. self.bullet_list.append(HeroBullet(self.screen, self.x+53, self.y))
  77. def move_left(self):
  78. if self.x <= self.limit_left:
  79. pass
  80. else:
  81. self.x -= self.step
  82. def move_right(self):
  83. if self.x >= self.limit_right:
  84. pass
  85. else:
  86. self.x += self.step
  87. def move_up(self):
  88. if self.y <= self.limit_top:
  89. pass
  90. else:
  91. self.y -= self.step
  92. def move_down(self):
  93. if self.y >= self.limit_bottom:
  94. pass
  95. else:
  96. self.y += self.step

预览效果:
在这里插入图片描述
后期我会把这个太空飞机大战的源码地址分享到这里,感谢各位支持!

下载地址:https://download.csdn.net/download/qq_44723773/12387340

文章知识点与官方知识档案匹配,可进一步学习相关知识
算法技能树首页概览61094 人正在系统学习中
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/601150
推荐阅读
相关标签
  

闽ICP备14008679号