pygame实现弹球游戏
本文实例为大家分享了pygame实现弹球游戏的具体代码,供大家参考,具体内容如下
pygame弹球游戏
写的很简陋
pipinstallpygame安装pygame模块
代码,复制运行即可
importpygame
importrandom
pygame.init()
win=pygame.display.set_mode((600,600))#画布窗口的大小
pygame.display.set_caption("弹球游戏")#窗口标题
x,y=300,0#方块的起点
width,height=10,10#方块的宽,高
speed=1#速度
def_randomOK():
returnrandom.randint(0,1)
stop=False
_random=_randomOK()
str1="暂停中"
baffle=250
status=0
count=0
top=0
whileTrue:
#刷新频率,小球移动速度
pygame.time.Clock().tick(1000)
foreventinpygame.event.get():
#窗口x事件
ifevent.type==pygame.QUIT:
exit(0)
elifevent.type==pygame.KEYDOWN:
#回车事件
ifevent.key==13:
str1="暂停中"
stop=notstop
ifstatus==1:
x,y=300,0
keys=pygame.key.get_pressed()
ifstop:
pygame.display.set_caption(str1)#窗口标题
continue
ify>=590:
status=1
stop=notstop
str1="游戏结束,回车重新开始,反弹次数"+str(count)
count=0
pygame.display.set_caption("弹球游戏")#窗口标题
ify==0:
top=0
iftop==0:
if_random==0:#向下左弹
x-=speed
y+=speed
elif_random==1:
x+=speed
y+=speed
else:
if_random==0:#向上左弹
x-=speed
y-=speed
elif_random==1:#向上右弹
x+=speed
y-=speed
#方向箭头响应
ifkeys[pygame.K_LEFT]:
baffle-=speed
ifbaffle<0:
baffle=0
ifkeys[pygame.K_RIGHT]:
baffle+=speed
ifbaffle>500:
baffle=500
#碰撞逻辑
if500<=y<=520:
print(x,y)
print(baffle)
#y高度坐标200x宽度坐标200
#x坐标加300大于宽度初始坐标,小于宽度+300
ifbaffle<=x<=baffle+100:
count+=1
top=1
#防止跑出边界
ifx>win.get_size()[0]-width:
_random=_randomOK()
x=win.get_size()[0]-width
ifx<0:
_random=_randomOK()
x=0
ify>win.get_size()[1]-height:
_random=_randomOK()
y=win.get_size()[1]-height
ify<0:
_random=_randomOK()
y=0
#将每一帧的底色先填充成黑色
win.fill((64,158,255))
#画方块
pygame.draw.rect(win,(255,0,0),(x,y,width,height))
#挡板设置,
pygame.draw.rect(win,(255,255,255),(baffle,500,100,20))
#更新画布
pygame.display.update()
pygame.quit()
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。