汇智学堂-phthon小游戏(贪吃蛇游戏之二-运动动画的测试)

4.2运动动画的测试
我们将在600*600像素的画布上,实现图片上下左右的动画。下面是我们要做的事情。
1、获得图像id。
2、控制方向。

实现代码如下:

def init(self):
self.snake=PhotoImage(file=‘C:\Users\soft\Desktop\训练\PYTHON\LYG-向荣
\snake\snake\snake.gif’)
self.food=PhotoImage(file=‘C:\Users\soft\Desktop\训练\PYTHON\LYG-向荣
\snake\snake\food.gif’)
self.id1= self.canvas.create_image(40,40,anchor=NW,image=self.snake)
a=random.randint(1,30)
b=random.randint(1,30)
self.id2= self.canvas.create_image(20a,20b,anchor=NW,image=self.food)
self.x=0
self.y=0
def draw(self):
self.canvas.move(self.id1,self.x,self.y)
def turn_left(self,evt):
self.x=-20
self.y=0

file=‘C:\Users\soft\Desktop\训练\PYTHON\LYG-向荣\snake\snake\snake.gif’,读者需要根据自己存的图片路径,修改位置。
self.x,self.y作用分别是:横坐标和纵坐标的变化量。

将代码整合起来,整合后完整代码如下:

from tkinter import*
import random
import time

class Game:
def init(self):

    self.tk=Tk()
    self.canvas=Canvas(self.tk,width=600,height=600)
    self.canvas.pack()        
    self.snake=PhotoImage(file='C:\\Users\\soft\\Desktop\\训练\\PYTHON\\ \

LYG-向荣\snake\snake\snake.gif’)
self.food=PhotoImage(file=‘C:\Users\soft\Desktop\训练\PYTHON\
LYG-向荣\snake\snake\food.gif’)
self.id1= self.canvas.create_image(40,40,anchor=NW,image=self.snake)
a=random.randint(1,30)
b=random.randint(1,30)
self.id2= self.canvas.create_image(20a,20b,anchor=NW,image=self.food)
self.x=0
self.y=0

    self.canvas.bind_all('<KeyPress-Left>',self.turn_left)
    self.canvas.bind_all('<KeyPress-Right>',self.turn_right)
    self.canvas.bind_all('<KeyPress-Up>',self.turn_up)
    self.canvas.bind_all('<KeyPress-Down>',self.turn_down)        

def draw(self):
    self.canvas.move(self.id1,self.x,self.y)
def turn_left(self,evt):
    self.x=-20
    self.y=0
def turn_right(self,evt):
    self.x=20
    self.y=0
def turn_up(self,evt):
    self.y=-20
    self.x=0
def turn_down(self,evt):
    self.y=20
    self.x=0

g=Game()
while 1:
g.draw()
g.tk.update_idletasks()
g.tk.update()
v=0.1
time.sleep(v)

运行这段代码,当我们按下向右箭头时,我们的方框图片会以我们设定的速度向右移动(见图4-4)向左、向上、向下都是这样。
在这里插入图片描述
图4-4

猜你喜欢

转载自blog.csdn.net/weixin_39593940/article/details/88361999