制作这个游戏,需要用到pygame模块,
下载pygame步骤:
在安装的python目录下找到Scripts文件
进入Scripts文件中在目录栏输入cmd进入命令行模式
在控制台输入pip install pygame==2.5.2 -i https://mirrors.aliyun.com/pypi/simple/
2.5.2是pygame的版本,根据个人需求可以安装其他版本, -i https://mirrors.aliyun.com/pypi/simple/是用阿里云镜像库下载(速度快).我已经安装过了就不演示了.
安装成功后,运行代码:
小球会自动移动,碰到边缘处会反弹,按"↑"或"W"会加速垂直的速度,按"↓"或"S"会减速垂直的速度,当速度减到0时,小球会静止.按"←"和"→"或"A"和"D"会加速或减速水平方向的速度,速度减到0时,小球会静止.
代码:
#hello world game
#1.引入pygame和其他模块
import pygame,sys
#2.初始化
pygame.init()
size=width,height=800,600
screen=pygame.display.set_mode((size),pygame.RESIZABLE)#宽,高
pygame.display.set_caption("ball rotate")#标题
ball=pygame.image.load("ball.gif")
ballrect=ball.get_rect()
speed=[1,1]
offset=1
fps=300
fclock=pygame.time.Clock()
bg=(130,216,207)#背景颜色
fullscreen=False
still=False
bgcolor=pygame.Color("black")
def RGBChannel(a):
return 0 if a<0 else(255 if a>255 else int(a))
#3.事件循环及对事件的响应
while True:
for event in pygame.event.get():
if event.type==pygame.QUIT:
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]))
if event.key==pygame.K_RIGHT:
speed[0]=speed[0]+1 if speed[0]>0 else speed[0]-1
if event.key==pygame.K_UP:
speed[1]=speed[1]+1 if speed[1]>0 else speed[1]-1
if event.key==pygame.K_DOWN:
speed[1]=speed[1] if speed[1]==0 else (abs(speed[1])-1)*int(speed[1]/abs(speed[1]))
if event.key==pygame.K_a:
speed[0]-=offset
if event.key==pygame.K_d:
speed[0]=offset
if event.key==pygame.K_w:
speed[1]-=offset
if event.key==pygame.K_s:
speed[1]=offset
if event.type==pygame.MOUSEBUTTONDOWN:
if event.button==1:
still=True
if event.type==pygame.MOUSEBUTTONUP:
still=False
if event.button==1:
ballrect=ballrect.move(event.pos[0]-ballrect.left,event.pos[1]-ballrect.top)
if event.type==pygame.MOUSEMOTION:
still=False
if event.buttons[0]==1:
ballrect=ballrect.move(event.pos[0]-ballrect.left,event.pos[1]-ballrect.top)
#无边框时,需要键入ESC键表示退出
elif event.type==pygame.KEYDOWN:
if event.key==pygame.K_ESCAPE:
pygame.quit()
sys.exit()
#设置全屏和非全屏的切换 F11 (笔记本电脑键盘F11不能用,用数字1代替)
if event.key==pygame.K_1:
fullscreen=not fullscreen
if fullscreen:
screen=pygame.display.set_mode(size,pygame.FULLSCREEN)
else:
screen=pygame.display.set_mode(size)
ballrect=ballrect.move(speed[0],speed[1])
if ballrect.left<0 or ballrect.right>width:
speed[0]=-speed[0]
if ballrect.top<0 or ballrect.bottom>height:
speed[1]=-speed[1]
vinfo=pygame.display.Info()
size=width,height=vinfo.current_w,vinfo.current_h #感知窗口大小的实时变化
bgcolor.r=RGBChannel(ballrect.left*255/width)
bgcolor.g=RGBChannel(ballrect.top*255/width)
bgcolor.b=RGBChannel(min(speed[0],speed[1])*255/max(speed[0],speed[1],1))
#4.刷新屏幕
screen.fill(bgcolor)#消除残影
screen.blit(ball,ballrect)
pygame.display.update() #属于while语句
fclock.tick(fps)