python弹力球小游戏
时间: 2024-01-01 09:23:43 浏览: 177
Python乒乓球小游戏源代码
5星 · 资源好评率100%
以下是一个简单的Python弹力球小游戏的示例代码:
```python
import pygame
import random
# 初始化游戏
pygame.init()
# 设置游戏窗口大小
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("弹力球小游戏")
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
# 定义球的初始位置和速度
ball_radius = 10
ball_x = screen_width // 2
ball_y = screen_height // 2
ball_speed_x = random.choice([-2, 2])
ball_speed_y = random.choice([-2, 2])
# 定义挡板的初始位置和大小
paddle_width = 100
paddle_height = 10
paddle_x = (screen_width - paddle_width) // 2
paddle_y = screen_height - paddle_height - 10
paddle_speed = 5
# 定义分数
score = 0
# 游戏主循环
running = True
clock = pygame.time.Clock()
while running:
clock.tick(60)
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# 移动挡板
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
paddle_x -= paddle_speed
if keys[pygame.K_RIGHT]:
paddle_x += paddle_speed
# 移动球
ball_x += ball_speed_x
ball_y += ball_speed_y
# 球与边界的碰撞检测
if ball_x < ball_radius or ball_x > screen_width - ball_radius:
ball_speed_x = -ball_speed_x
if ball_y < ball_radius:
ball_speed_y = -ball_speed_y
# 球与挡板的碰撞检测
if ball_y > paddle_y - ball_radius and paddle_x - ball_radius < ball_x < paddle_x + paddle_width + ball_radius:
ball_speed_y = -ball_speed_y
score += 1
# 清空屏幕
screen.fill(BLACK)
# 绘制挡板
pygame.draw.rect(screen, WHITE, (paddle_x, paddle_y, paddle_width, paddle_height))
# 绘制球
pygame.draw.circle(screen, WHITE, (ball_x, ball_y), ball_radius)
# 绘制分数
font = pygame.font.Font(None, 36)
text = font.render("Score: " + str(score), True, WHITE)
screen.blit(text, (10, 10))
# 更新屏幕
pygame.display.flip()
# 退出游戏
pygame.quit()
```
阅读全文