import sys
import pygame
pygame.init()
# 初始
# 窗口大小
screen_image = pygame.display.set_mode((800, 600))
screen_rect = screen_image.get_rect()
# 窗口标题
pygame.display.set_caption('游戏窗口标题')
# 元素
# 读取图像 图像不可中文
ship_image = pygame.image.load("2.png")
ship_rect = ship_image.get_rect()
# 图像 中间底部 = 窗口 中间底部
ship_rect.midbottom = screen_rect.midbottom
# ship_rect.bottom = screen_rect.bottom # 底部默认初始 左边
# 自定义颜色
bg_color1 = (0, 128, 128)
bg_color2 = (60, 60, 60)
bg_color3 = (255, 0, 0)
moving_left = False
moving_right = False
while True:
# 捕获 键盘鼠标操作 pygame.event.get()
for event in pygame.event.get():
# 点击❌号关闭,退出游戏
if event.type == pygame.QUIT:
sys.exit()
# 监控 键盘 按下
elif event.type == pygame.KEYDOWN:
# 键盘 左
if event.key == pygame.K_LEFT:
moving_left = True
# 键盘 右
if event.key == pygame.K_RIGHT:
moving_right = True
# # 键盘 上
# if event.key == pygame.K_UP:
# ship_rect.y -= 10
# # 键盘 下
# if event.key == pygame.K_DOWN:
# ship_rect.y += 10
# 监控 键盘 松开
elif event.type == pygame.KEYUP:
# 键盘 左
if event.key == pygame.K_LEFT:
moving_left = False
# 键盘 右
if event.key == pygame.K_RIGHT:
moving_right = False
if moving_left and ship_rect.left > 0:
ship_rect.x -= 1
if moving_right and ship_rect.right < screen_rect.right:
ship_rect.x += 1
# 绘制
# 绘制游戏窗口背景(颜色三通道)
screen_image.fill(bg_color1)
# 在游戏窗口 绘制 加载的图像
# 窗口 绘制图像(图, 图的坐标)
screen_image.blit(ship_image, ship_rect)
# 刷新屏幕
pygame.display.flip()
11-10
1514
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountBlack.png)
10-23
1406
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountBlack.png)
08-27
6559
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountBlack.png)
05-11
3020
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountBlack.png)
11-10
283
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountBlack.png)
07-10