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

前言

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

代码如下

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()

实现效果

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

 

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

猜你喜欢

转载自blog.csdn.net/VLOKL/article/details/135139843