当前位置: 首页 > article >正文

python弹球小游戏

import pygame
import random

# 游戏窗口大小
WIDTH = 800
HEIGHT = 600

# 定义颜色
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)


# 球的类
class Ball:
    def __init__(self):
        self.radius = 10
        self.speed = [random.randint(2, 4), random.randint(2, 4)]
        self.color = RED
        self.rect = pygame.Rect(400, 300, self.radius * 2, self.radius * 2)

    def move(self):
        self.rect.move_ip(self.speed[0], self.speed[1])

        # 球碰到边界反弹
        if self.rect.left <= 0 or self.rect.right >= WIDTH:
            self.speed[0] = -self.speed[0]

        if self.rect.top <= 0 or self.rect.bottom >= HEIGHT:
            self.speed[1] = -self.speed[1]

    def draw(self, screen):
        pygame.draw.circle(screen, self.color, self.rect.center, self.radius)


# 初始化pygame
pygame.init()

# 创建游戏窗口
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("壁球小游戏")

# 创建球对象
ball = Ball()

# 游戏主循环
running = True
clock = pygame.time.Clock()

while running:
    # 处理退出事件
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # 移动球
    ball.move()

    # 绘制背景
    screen.fill(BLACK)

    # 绘制球
    ball.draw(screen)

    # 更新屏幕
    pygame.display.flip()

    # 控制游戏帧率
    clock.tick(60)

# 退出游戏
pygame.quit()

在这里插入图片描述


http://www.kler.cn/news/155061.html

相关文章:

  • Claude2 -sdk java (非官方提供)开源计划
  • Python简单模拟蓝牙车钥匙协议
  • Linux周期任务
  • 将数据导出为excel的js库有哪些
  • linux简述进程
  • 程序员学习方法
  • 字符函数 和 字符串函数
  • asp.net core webpi 结合jwt实现登录鉴权
  • 金额到底应该用什么类型存储?
  • 基于单片机的多功能视力保护器(论文+源码)
  • SmartSoftHelp8,服务器,目标端口安全扫描工具
  • 单页面应用
  • 阅读软件OmniReader Pro mac功能特色
  • PostgreSQL对比Mysql
  • OpenSSL 使用AES对文件加解密
  • SQL Server对象类型(8)——4.8.约束(Constraint)
  • 五子棋AI算法自动测试方法
  • 6.7 Windows驱动开发:内核枚举LoadImage映像回调
  • “SRP模型+”多技术融合在生态环境脆弱性评价模型构建、时空格局演变分析与RSEI 指数的生态质量评价及拓展
  • 计算机网络TCP篇②
  • 力扣题:字符的统计-12.2
  • C#-串口通信入门及进阶扩展
  • linux的ping命令
  • vue 生命周期
  • 461. 汉明距离
  • TCP三次握手与四次挥手
  • 爬虫-xpath篇
  • 计算机组成学习-计算机系统概述总结
  • DOM 事件的注册和移除
  • 深度学习好文记录,反复学习