pygame实现弹球游戏

脚本专栏 发布日期:2024/10/22 浏览次数:1

正在浏览: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()

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

一文看懂荣耀MagicBook Pro 16
荣耀猎人回归!七大亮点看懂不只是轻薄本,更是游戏本的MagicBook Pro 16.
人们对于笔记本电脑有一个固有印象:要么轻薄但性能一般,要么性能强劲但笨重臃肿。然而,今年荣耀新推出的MagicBook Pro 16刷新了人们的认知——发布会上,荣耀宣布猎人游戏本正式回归,称其继承了荣耀 HUNTER 基因,并自信地为其打出“轻薄本,更是游戏本”的口号。
众所周知,寻求轻薄本的用户普遍更看重便携性、外观造型、静谧性和打字办公等用机体验,而寻求游戏本的用户则普遍更看重硬件配置、性能释放等硬核指标。把两个看似难以相干的产品融合到一起,我们不禁对它产生了强烈的好奇:作为代表荣耀猎人游戏本的跨界新物种,它究竟做了哪些平衡以兼顾不同人群的各类需求呢?