帮我用Python写一个接球小游戏
时间: 2023-04-07 22:03:31 浏览: 177
利用python如何实现猫捉老鼠小游戏
5星 · 资源好评率100%
好的,我可以回答这个问题。以下是一个简单的Python接球小游戏的代码:
```python
import pygame
import random
# 初始化pygame
pygame.init()
# 设置窗口大小
screen_width = 500
screen_height = 500
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("接球小游戏")
# 设置颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
# 设置球和板子的大小和速度
ball_size = 25
ball_speed = 5
paddle_width = 75
paddle_height = 15
paddle_speed = 5
# 创建球和板子
ball = pygame.Rect(screen_width/2 - ball_size/2, 0, ball_size, ball_size)
paddle = pygame.Rect(screen_width/2 - paddle_width/2, screen_height - paddle_height, paddle_width, paddle_height)
# 设置分数
score = 0
font = pygame.font.Font(None, 30)
# 游戏循环
running = True
while running:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# 移动板子
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and paddle.left > 0:
paddle.left -= paddle_speed
if keys[pygame.K_RIGHT] and paddle.right < screen_width:
paddle.right += paddle_speed
# 移动球
ball.top += ball_speed
# 碰撞检测
if ball.top < 0:
ball_speed = -ball_speed
if ball.colliderect(paddle):
ball_speed = -ball_speed
score += 1
if ball.bottom > screen_height:
running = False
# 生成新球
if ball.top > screen_height/3:
if random.randint(0, 10) == 0:
ball = pygame.Rect(random.randint(0, screen_width-ball_size), 0, ball_size, ball_size)
ball_speed = 5
# 绘制界面
screen.fill(white)
pygame.draw.rect(screen, black, paddle)
pygame.draw.ellipse(screen, red, ball)
score_text = font.render("Score: " + str(score), True, black)
screen.blit(score_text, (10, 10))
pygame.display.flip()
# 退出游戏
pygame.quit()
```
希望这个代码能够帮助你实现一个简单的接球小游戏。
阅读全文