Python写一个双人赛车小游戏
时间: 2024-02-16 11:52:28 浏览: 102
好的,以下是一个简单的双人赛车小游戏代码:
```python
import pygame, sys
from pygame.locals import *
# 初始化 Pygame
pygame.init()
# 设置窗口大小和标题
WINDOW_WIDTH = 800
WINDOW_HEIGHT = 600
DISPLAYSURF = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption('双人赛车')
# 设置颜色
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
# 加载图片
player1_car = pygame.image.load('car1.png')
player2_car = pygame.image.load('car2.png')
# 设置初始位置和速度
player1_x = 350
player1_y = 500
player1_speed = 0
player2_x = 450
player2_y = 500
player2_speed = 0
# 设置游戏循环
clock = pygame.time.Clock()
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == KEYDOWN:
# 玩家1的控制键
if event.key == K_LEFT:
player1_speed = -5
elif event.key == K_RIGHT:
player1_speed = 5
# 玩家2的控制键
elif event.key == K_a:
player2_speed = -5
elif event.key == K_d:
player2_speed = 5
elif event.type == KEYUP:
# 玩家1的控制键
if event.key == K_LEFT:
player1_speed = 0
elif event.key == K_RIGHT:
player1_speed = 0
# 玩家2的控制键
elif event.key == K_a:
player2_speed = 0
elif event.key == K_d:
player2_speed = 0
# 更新玩家位置
player1_x += player1_speed
player2_x += player2_speed
# 设置边界
if player1_x < 0:
player1_x = 0
elif player1_x > WINDOW_WIDTH - player1_car.get_width():
player1_x = WINDOW_WIDTH - player1_car.get_width()
if player2_x < 0:
player2_x = 0
elif player2_x > WINDOW_WIDTH - player2_car.get_width():
player2_x = WINDOW_WIDTH - player2_car.get_width()
# 绘制背景
DISPLAYSURF.fill(WHITE)
pygame.draw.line(DISPLAYSURF, BLACK, (0, 450), (WINDOW_WIDTH, 450), 5)
# 绘制玩家1的车
DISPLAYSURF.blit(player1_car, (player1_x, player1_y))
# 绘制玩家2的车
DISPLAYSURF.blit(player2_car, (player2_x, player2_y))
# 碰撞检测
if player1_y < player2_y + player2_car.get_height():
if (player1_x + player1_car.get_width() > player2_x) and (player1_x < player2_x + player2_car.get_width()):
pygame.draw.rect(DISPLAYSURF, RED, (player1_x, player1_y, player1_car.get_width(), player1_car.get_height()))
pygame.draw.rect(DISPLAYSURF, RED, (player2_x, player2_y, player2_car.get_width(), player2_car.get_height()))
pygame.display.update()
pygame.time.wait(1000)
player1_x = 350
player1_y = 500
player1_speed = 0
player2_x = 450
player2_y = 500
player2_speed = 0
# 更新屏幕
pygame.display.update()
# 设置帧率
clock.tick(60)
```
这个游戏中,玩家1使用左右箭头键控制赛车,玩家2使用 A 和 D 键控制赛车。当两辆车相撞时,会出现红色矩形,并且在1秒后重新开始游戏。
阅读全文