前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >用python图形库实现的一个白球,简单记录一下(实现了简单的碰撞检测)

用python图形库实现的一个白球,简单记录一下(实现了简单的碰撞检测)

作者头像
命运之光
发布2024-03-20 14:15:44
920
发布2024-03-20 14:15:44
举报
前言

写大作业的时候创造出来的,留之无用,丢之可惜,就简单的放在这里,看看说不定什么时候就还能用的上,主要是这个球,想要扩展也不知道写些什么,害怕雷同,还是换一个算了。

代码如下
代码语言:javascript
复制
import pygame
import sys
import math

# 初始化 Pygame
pygame.init()

# 游戏窗口大小
WIDTH, HEIGHT = 800, 600
# 颜色定义
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
# 球的半径
BALL_RADIUS = 20
# 球的速度
BALL_SPEED = 5

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

# 创建球
class Ball:
    def __init__(self, x, y, color):
        self.x = x
        self.y = y
        self.color = color
        self.radius = BALL_RADIUS
        self.speed_x = 0
        self.speed_y = 0

    def draw(self):
        pygame.draw.circle(screen, self.color, (self.x, self.y), self.radius)

    def update(self):
        self.x += self.speed_x
        self.y += self.speed_y

        # 边界检测
        if self.x - self.radius < 0 or self.x + self.radius > WIDTH:
            self.speed_x *= -1
        if self.y - self.radius < 0 or self.y + self.radius > HEIGHT:
            self.speed_y *= -1

# 创建球
cue_ball = Ball(100, 300, WHITE)

# 游戏循环
running = True
while running:
    screen.fill(BLACK)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # 获取鼠标位置
    mouse_x, mouse_y = pygame.mouse.get_pos()

    # 计算球的速度(根据鼠标点击)
    if pygame.mouse.get_pressed()[0]:  # 0 代表左键
        cue_ball.speed_x = (mouse_x - cue_ball.x) / BALL_SPEED
        cue_ball.speed_y = (mouse_y - cue_ball.y) / BALL_SPEED

    # 更新球的位置
    cue_ball.update()
    # 绘制球
    cue_ball.draw()

    pygame.display.flip()

    # 控制帧率
    pygame.time.Clock().tick(60)

# 退出游戏
pygame.quit()
sys.exit()
实现效果

还是可以的,很好玩,真的,不然也不会记录一下。

有谁想要扩展,可以试着扩展一下,就这样吧,拜拜

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2024-03-19,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 前言
  • 代码如下
  • 实现效果
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档