打乒乓小游戏代码可复制python
时间: 2023-07-31 14:11:21 浏览: 215
Python乒乓球小游戏源代码
5星 · 资源好评率100%
下面是一个简单的打乒乓球小游戏的Python代码:
```python
import pygame
# 初始化Pygame
pygame.init()
# 设置游戏窗口尺寸
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
# 设置游戏标题
pygame.display.set_caption("Ping Pong Game")
# 设置游戏颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
# 设置球和球拍的大小和速度
ball_size = 20
ball_x = screen_width // 2
ball_y = screen_height // 2
ball_speed_x = 5
ball_speed_y = 5
paddle_width = 100
paddle_height = 10
paddle_x = (screen_width - paddle_width) // 2
paddle_y = screen_height - paddle_height - 10
paddle_speed = 0
# 绘制球和球拍
def draw_ball(ball_x, ball_y):
pygame.draw.circle(screen, WHITE, (ball_x, ball_y), ball_size)
def draw_paddle(paddle_x, paddle_y):
pygame.draw.rect(screen, WHITE, (paddle_x, paddle_y, paddle_width, paddle_height))
# 游戏循环
running = True
while running:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
paddle_speed = -5
elif event.key == pygame.K_RIGHT:
paddle_speed = 5
elif event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT:
paddle_speed = 0
elif event.key == pygame.K_RIGHT:
paddle_speed = 0
# 移动球拍
paddle_x += paddle_speed
if paddle_x < 0:
paddle_x = 0
elif paddle_x > screen_width - paddle_width:
paddle_x = screen_width - paddle_width
# 移动球
ball_x += ball_speed_x
ball_y += ball_speed_y
if ball_x < ball_size or ball_x > screen_width - ball_size:
ball_speed_x = -ball_speed_x
elif ball_y < ball_size:
ball_speed_y = -ball_speed_y
elif ball_y > screen_height - ball_size - paddle_height and paddle_x <= ball_x <= paddle_x + paddle_width:
ball_speed_y = -ball_speed_y
elif ball_y > screen_height:
ball_x = screen_width // 2
ball_y = screen_height // 2
ball_speed_x = 5
ball_speed_y = 5
# 绘制游戏界面
screen.fill(BLACK)
draw_ball(ball_x, ball_y)
draw_paddle(paddle_x, paddle_y)
pygame.display.flip()
# 退出Pygame
pygame.quit()
```
你可以直接复制上述代码并运行,就可以玩这个简单的打乒乓球小游戏了。
阅读全文