前几天在慕课上加了高天老师的Python小游戏学习。然后跟着学习了一下,这是课堂上的案例小球碰撞。
1.如果要实现小球碰撞,首先你先要有一个小球。这是课堂上用的小球GIF图。注意:一定要GIF图才可以,
我也有试过其他类型的图片,比如jpeg,但是没有成功,下面是我用爬虫爬取小球的代码。
import requests as re
import os
url = "http://python123.io/PY15/PYG02-ball.gif"
root = "C://Users//Public//Pictures//Sample Pictures//" #存储位置的路径
path = root + url.split('/')[-1]#获得URL最后的名称作为图片名称
try:
if not os.path.exists(root):
os.mkdir(root)
if not os.path.exists(path):
r = re.get(url)
with open(path,'wb') as f:
f.write(r.content)#以二进制的形式输入到创建的文件
f.close()
print('it is secenst')
else:
print('it has haven')
except:
print('it is unseccened')
2.代码实现
import pygame,sys
pygame.init()
speed =[1,1]#作为小球移动的水平速度和垂直速度
black = 0,0,0
screen = pygame.display.set_mode((600,400))#设置窗口大小
pygame.display.set_caption('python壁球')#设置窗口的名字
ball = pygame.image.load('C:\\Users\\Public\\Pictures\\Sample Pictures\\PYG02-ball.gif')#获得小球,这里记得要两个\
ballrect = ball.get_rect()#获得图片的位置
fps = 300#帧数设计
fclock = pygame.time.Clock()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:#获得用户指令
if event.key == pygame.K_LEFT:#获得键盘向左的指令,小球水平速度减一
speed[0] = speed[0] if speed[0] == 0 else (abs(speed[0]) - 1)*int(speed[0]/abs(speed[0]))
elif event.key == pygame.K_RIGHT:#获得键盘向右的命令,小球水平速度加一
speed[0] = speed[0] + 1 if speed[0]>0 else speed[0]-1
elif event.key==pygame.K_UP:#获得键盘向上的命令,小球垂直方向速度加一
speed[1] = speed[1] +1 if speed[1]>0 else speed[1] -1
elif event.key == pygame.K_DOWN:#获得键盘向下的命令,小球垂直方向速度减一
speed[1] = speed[1] if speed[1] == 0 else (abs(speed[1]) -1)*int(speed[1]/abs(speed[1]))
ballrect = ballrect.move(speed[0],speed[1])#用pygame中的move函数,让小球移动
if ballrect.left<0 or ballrect.right>600:#当小球到达水平边缘时水平方向取反
speed[0] =-speed[0]
if ballrect.top <0 or ballrect.bottom>400::#当小球到达垂直边缘时垂直方向取反
speed[1] =- speed[1]
screen.fill(black)#设置背景颜色
screen.blit(ball,ballrect)
pygame.display.update()#不断刷新窗口
fclock.tick(fps)#帧数
总结,刚开始的时候只是跟着网上的内容写,后来遇到了一个打不开PYG02-ball.gif的错误,后来去查了一下,是要把路径给写完,而且记住用计算机上复制路径过来后一定还要在每个\后面多加一个。还有就是要学着自己写代码,高天老师讲完他的基本
代码实现思想之后,我就开始尝试着用自己的理解写出里面移动的逻辑代码。