大家好,今天我们开始做一个新的游戏——火柴人逃脱。 以下是效果图: 温馨提示:代码里有图片资源,你可以自己用GIMP画,也可以去下载: 图片 我们来看第一部分代码:
from tkinter import *
import time,random
这一部分没什么特别的,你可以到我的Ball专栏中看细解。
class Game:
def __init__(self):
self.tk=Tk()
self.tk.title('stick man game')
self.tk.resizable(0,0)
self.tk.wm_attributes('-topmost',1)
self.canvas=Canvas(self.tk,width=500,height=500,highlightthickness=0)
self.canvas.pack()
self.tk.update()
self.canvas_width=500
self.canvas_height=500
self.bg=PhotoImage(file='../image/background.gif')
w=self.bg.width()
h=self.bg.height()
for i in range(0,5):
for j in range(0,5):
self.canvas.create_image(i*w,j*h,image=self.bg,anchor='nw')
self.sprites=[]
self.running=True
def mainloop(self):
while 1:
if self.running==True:
for sprite in self.sprites:
sprite.move()
else:
canvas.create_text(100, 150, text='ok', fill='blue', font=('Times', 20))
self.tk.update_idletasks()
self.tk.update()
time.sleep(0.01)
以上是第二部分,它主要控制画布的各项参数(详见详解)。
class Coords:
def __init__(self,x1=0,y1=0,x2=0,y2=0):
self.x1=x1
self.y1=y1
self.x2=x2
self.y2=y2
def within_x(co1,co2):
if (co1.x1 > co2.x1 and co1.x1co2.x1 and co1.x1co1.x1 and co2.x1co2.x1 and co1.x2 co2.y1 and co1.y1co2.y1 and co1.y2co1.y1 and co2.y1co2.y1 and co1.y2=co2.x1 and co1.x2=co2.y1 and y_calc0.1:
self.last_time=time.time()
self.current_image+=self.current_image_add
if self.current_image>=2:
self.current_image_add=-1
if self.current_image0:
self.jump_count-=1
co=self.coords()
left=True
right=True
top=True
bottom=True
falling=True
if self.y>0 and co.y2>=self.game.canvas_height:
self.y=0
bottom=True
elif self.y=self.game.canvas_width:
self.x=0
right=True
elif self.x=self.game.canvas_height:
self.y=0
bottom=True
elif self.y=self.game.canvas_width:
self.x=0
right=True
elif self.x |