用python代码做一个打球球小游戏
时间: 2023-09-05 12:11:28 浏览: 74
python小球游戏
好的,以下是用 Python 语言实现的打球球小游戏示例代码:
```python
import pygame
import random
# 初始化 Pygame
pygame.init()
# 游戏窗口大小
WINDOW_WIDTH = 800
WINDOW_HEIGHT = 600
# 创建游戏窗口
screen = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption("打球球小游戏")
# 设置游戏帧率
clock = pygame.time.Clock()
# 球的大小和速度
BALL_RADIUS = 20
BALL_SPEED = 5
# 球的初始位置和速度
ball_x = random.randint(BALL_RADIUS, WINDOW_WIDTH - BALL_RADIUS)
ball_y = random.randint(BALL_RADIUS, WINDOW_HEIGHT - BALL_RADIUS)
ball_speed_x = BALL_SPEED
ball_speed_y = BALL_SPEED
# 玩家的位置和大小
player_width = 100
player_height = 20
player_x = (WINDOW_WIDTH - player_width) // 2
player_y = WINDOW_HEIGHT - player_height
# 游戏分数
score = 0
# 游戏结束标志
game_over = False
# 加载字体
font = pygame.font.SysFont(None, 36)
# 游戏循环
while not game_over:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
player_x -= 10
elif event.key == pygame.K_RIGHT:
player_x += 10
# 移动球
ball_x += ball_speed_x
ball_y += ball_speed_y
# 球碰到左右边界反弹
if ball_x - BALL_RADIUS < 0 or ball_x + BALL_RADIUS > WINDOW_WIDTH:
ball_speed_x = -ball_speed_x
# 球碰到顶部反弹
if ball_y - BALL_RADIUS < 0:
ball_speed_y = -ball_speed_y
# 球碰到玩家反弹
if ball_y + BALL_RADIUS >= player_y and \
ball_x >= player_x and \
ball_x <= player_x + player_width:
ball_speed_y = -ball_speed_y
score += 10
# 球落下游戏结束
if ball_y + BALL_RADIUS > WINDOW_HEIGHT:
game_over = True
# 绘制游戏界面
screen.fill((255, 255, 255))
pygame.draw.circle(screen, (255, 0, 0), (ball_x, ball_y), BALL_RADIUS)
pygame.draw.rect(screen, (0, 0, 255), (player_x, player_y, player_width, player_height))
score_text = font.render("Score: " + str(score), True, (0, 0, 0))
screen.blit(score_text, (10, 10))
pygame.display.update()
# 控制游戏帧率
clock.tick(60)
# 游戏结束,退出 Pygame
pygame.quit()
```
你可以将这段代码保存到一个 Python 文件中并运行,就可以玩到这个打球球小游戏了。
阅读全文