python打乒乓球
时间: 2023-12-26 09:28:55 浏览: 172
以下是一个简单的Python打乒乓球游戏的示例代码:
```python
import pygame
from pygame.locals import *
# 初始化游戏
pygame.init()
# 设置窗口大小
screen_width = 640
screen_height = 480
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("乒乓球游戏")
# 设置颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
# 创建球拍类
class Paddle(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((100, 10))
self.image.fill(WHITE)
self.rect = self.image.get_rect()
self.rect.centerx = screen_width // 2
self.rect.bottom = screen_height - 20
def update(self):
# 控制球拍的移动
pos = pygame.mouse.get_pos()
self.rect.centerx = pos[0]
self.rect.clamp_ip(screen.get_rect())
# 创建球类
class Ball(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((10, 10))
self.image.fill(WHITE)
self.rect = self.image.get_rect()
self.rect.centerx = screen_width // 2
self.rect.centery = screen_height // 2
self.speed = [3, 3]
def update(self):
# 控制球的移动和碰撞检测
self.rect.x += self.speed[0]
self.rect.y += self.speed[1]
if self.rect.left <= 0 or self.rect.right >= screen_width:
self.speed[0] = -self.speed[0]
if self.rect.top <= 0:
self.speed[1] = -self.speed[1]
if self.rect.colliderect(paddle.rect):
self.speed[1] = -self.speed[1]
# 创建球拍和球的精灵组
all_sprites = pygame.sprite.Group()
paddle = Paddle()
ball = Ball()
all_sprites.add(paddle, ball)
# 游戏主循环
running = True
clock = pygame.time.Clock()
while running:
clock.tick(60)
# 处理事件
for event in pygame.event.get():
if event.type == QUIT:
running = False
# 更新精灵组
all_sprites.update()
# 绘制背景
screen.fill(BLACK)
# 绘制精灵组
all_sprites.draw(screen)
# 刷新屏幕
pygame.display.flip()
# 退出游戏
pygame.quit()
```
阅读全文