pygame汽车游戏
时间: 2024-01-13 17:19:23 浏览: 74
以下是一个使用pygame实现的简单汽车游戏的示例:
```python
import pygame
import random
# 初始化pygame
pygame.init()
# 设置游戏窗口大小
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("Car Game")
# 加载汽车图片
car_image = pygame.image.load("car.png")
car_width = 50
car_height = 100
# 加载其他汽车图片
other_car_image = pygame.image.load("other_car.png")
other_car_width = 50
other_car_height = 100
# 设置汽车初始位置
car_x = screen_width // 2 - car_width // 2
car_y = screen_height - car_height - 10
# 设置其他汽车初始位置和速度
other_car_x = random.randint(0, screen_width - other_car_width)
other_car_y = -other_car_height
other_car_speed = 5
# 设置游戏结束标志
game_over = False
# 游戏主循环
while not game_over:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
# 获取键盘输入
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
car_x -= 5
if keys[pygame.K_RIGHT]:
car_x += 5
# 更新汽车位置
car_rect = pygame.Rect(car_x, car_y, car_width, car_height)
other_car_rect = pygame.Rect(other_car_x, other_car_y, other_car_width, other_car_height)
if car_rect.colliderect(other_car_rect):
game_over = True
else:
other_car_y += other_car_speed
if other_car_y > screen_height:
other_car_x = random.randint(0, screen_width - other_car_width)
other_car_y = -other_car_height
# 绘制游戏界面
screen.fill((255, 255, 255))
screen.blit(car_image, (car_x, car_y))
screen.blit(other_car_image, (other_car_x, other_car_y))
pygame.display.flip()
# 退出游戏
pygame.quit()
```
这个游戏使用pygame库创建了一个窗口,并在窗口中显示一辆汽车和其他汽车。玩家可以通过键盘输入控制汽车的左右移动,避免与其他汽车相撞。当汽车与其他汽车相撞时,游戏结束。
阅读全文