pygame实现弹球游戏的方法

发布时间:2020-08-04 10:09:47 作者:小猪
来源:亿速云 阅读:176

这篇文章主要讲解了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()

看完上述内容,是不是对pygame实现弹球游戏的方法有进一步的了解,如果还想学习更多内容,欢迎关注亿速云行业资讯频道。

推荐阅读:
  1. 怎么在pygame中使用python制作一个挡板弹球游戏
  2. 怎么在python中使用pygame实现挡板弹球游戏

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

pygame gam

上一篇:Jupyter Notebook输出矢量图的方法

下一篇:Flutter如何实现虎牙/斗鱼弹幕功能

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》