Skip to content

Latest commit

 

History

History
62 lines (49 loc) · 1.42 KB

678-1011622-四处开的小汽车.sy.md

File metadata and controls

62 lines (49 loc) · 1.42 KB
import pygame
import os

pygame.init()

# 设置窗口的大小
screen = pygame.display.set_mode((800, 600))

# 加载汽车图片
car_image = pygame.image.load('car.png')
car_image = pygame.transform.scale(car_image, (50, 100)) # 可根据需要调整汽车大小
car_rect = car_image.get_rect()

# 设置汽车的初始位置
car_rect.midbottom = (400, 600)

# 设置汽车的朝向
direction = 0

# 设置游戏主循环
running = True
while running:
    # 处理事件
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # 获取键盘事件
    keys = pygame.key.get_pressed()
    if keys[pygame.K_UP]:
        car_rect.move_ip(0, -5)
        direction = 0
    if keys[pygame.K_DOWN]:
        car_rect.move_ip(0, 5)
        direction = 180
    if keys[pygame.K_LEFT]:
        car_rect.move_ip(-5, 0)
        direction = 90
    if keys[pygame.K_RIGHT]:
        car_rect.move_ip(5, 0)
        direction = -90

    # 将汽车的位置限制在屏幕内
    car_rect.clamp_ip(screen.get_rect())

    # 清屏
    screen.fill((255, 255, 255))
    # 旋转汽车图像以匹配其行驶方向
    rotated_car_image = pygame.transform.rotate(car_image, direction)
    rotated_car_rect = rotated_car_image.get_rect(center=car_rect.center)

    # 绘制汽车
    screen.blit(rotated_car_image, rotated_car_rect)

    # 更新屏幕
    pygame.display.flip()

# 退出pygame
pygame.quit()