写一个pygame车辆驾驶小游戏
时间: 2023-09-21 10:03:19 浏览: 101
好的,下面是一个简单的pygame车辆驾驶小游戏的代码示例:
```python
import pygame
import random
# 初始化pygame
pygame.init()
# 设置窗口大小
window_width = 800
window_height = 600
window = pygame.display.set_mode((window_width, window_height))
pygame.display.set_caption("Car Driving Game")
# 加载图片
car_image = pygame.image.load("car.png").convert_alpha()
# 车辆类
class Car:
def __init__(self):
self.x = 350
self.y = 500
self.speed = 0
def move_left(self):
self.speed = -5
def move_right(self):
self.speed = 5
def stop(self):
self.speed = 0
def update(self):
self.x += self.speed
if self.x < 0:
self.x = 0
if self.x > 700:
self.x = 700
def draw(self):
window.blit(car_image, (self.x, self.y))
# 障碍物类
class Obstacle:
def __init__(self):
self.x = random.randint(0, 700)
self.y = -100
self.speed = random.randint(3, 8)
def update(self):
self.y += self.speed
def draw(self):
pygame.draw.rect(window, (255, 0, 0), (self.x, self.y, 50, 100))
# 创建车辆
car = Car()
# 创建障碍物列表
obstacles = []
# 游戏循环
running = True
score = 0
clock = pygame.time.Clock()
while running:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
car.move_left()
if event.key == pygame.K_RIGHT:
car.move_right()
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
car.stop()
# 更新车辆和障碍物
car.update()
for obstacle in obstacles:
obstacle.update()
# 添加新障碍物
if random.randint(0, 100) < 5:
obstacles.append(Obstacle())
# 绘制背景
window.fill((255, 255, 255))
# 绘制车辆和障碍物
car.draw()
for obstacle in obstacles:
obstacle.draw()
# 检测碰撞
for obstacle in obstacles:
if obstacle.y > 600:
obstacles.remove(obstacle)
score += 1
if obstacle.y + 100 > car.y and obstacle.y < car.y + 100 and obstacle.x + 50 > car.x and obstacle.x < car.x + 100:
running = False
# 显示分数
font = pygame.font.SysFont(None, 30)
text = font.render("Score: " + str(score), True, (0, 0, 0))
window.blit(text, (10, 10))
# 更新屏幕
pygame.display.update()
# 控制游戏帧率
clock.tick(60)
# 退出游戏
pygame.quit()
```
在这个游戏中,玩家需要控制一辆车躲避从上方飞来的障碍物,并尽可能地获得高分。玩家可以使用左右箭头键来控制车辆的移动,当车辆与障碍物相撞时游戏结束,玩家的得分将会显示在窗口的左上角。
阅读全文