pygame实现弹球游戏
本文实例为大家分享了pygame实现弹球游戏的具体代码,供大家参考,具体内容如下
pygame弹球游戏
写的很简陋
pip install pygame 安装pygame模块
代码,复制运行即可
import pygame import random 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(): return random.randint(0, 1) stop = False _random = _randomOK() str1 = "暂停中" baffle = 250 status = 0 count = 0 top = 0 while True: # 刷新频率, 小球移动速度 pygame.time.Clock().tick(1000) for event in pygame.event.get(): # 窗口x事件 if event.type == pygame.QUIT: exit(0) elif event.type == pygame.KEYDOWN: # 回车事件 if event.key == 13: str1 = "暂停中" stop = not stop if status == 1: x, y = 300, 0 keys = pygame.key.get_pressed() if stop: pygame.display.set_caption(str1) # 窗口标题 continue if y >= 590: status = 1 stop = not stop str1 = "游戏结束,回车重新开始,反弹次数" + str(count) count = 0 pygame.display.set_caption("弹球游戏") # 窗口标题 if y == 0: top = 0 if top == 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 # 方向箭头响应 if keys[pygame.K_LEFT]: baffle -= speed if baffle < 0: baffle = 0 if keys[pygame.K_RIGHT]: baffle += speed if baffle > 500: baffle = 500 # 碰撞逻辑 if 500 <= y <= 520: print(x, y) print(baffle) # y 高度坐标 200 x 宽度坐标 200 # x坐标加300 大于 宽度初始坐标, 小于 宽度+300 if baffle <= x <= baffle + 100: count += 1 top = 1 # 防止跑出边界 if x > win.get_size()[0] - width: _random = _randomOK() x = win.get_size()[0] - width if x < 0: _random = _randomOK() x = 0 if y > win.get_size()[1] - height: _random = _randomOK() y = win.get_size()[1] - height if y < 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()
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。
赞 (0)