Error in user YAML: (<unknown>): found a tab character that violate indentation while scanning a plain scalar at line 3 column 3
---
- oeasy Python 0774
- 这是 oeasy 系统化 Python 教程,从基础一步步讲,扎实、完整、不跳步。愿意花时间学,就能真正学会。
- 本教程同步发布在:
- 个人网站: `https://oeasy.org`
- 蓝桥云课: `https://www.lanqiao.cn/courses/3584`
- GitHub: `https://github.com/overmind1980/oeasy-python-tutorial`
- Gitee: `https://gitee.com/overmind1980/oeasypython`
---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()
- 本文来自 oeasy Python 系统教程。
- 想完整、扎实学 Python,
- 搜索 oeasy 即可。