下面是一个简单的示例代码,演示了如何使用pygame包创建一个表面边缘碰撞的游戏。
import pygame
import sys
pygame.init()
# 设置窗口大小和标题
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("Surface Edge Collision")
# 加载图片
player_image = pygame.image.load("player.png")
player_rect = player_image.get_rect()
player_width = player_rect.width
player_height = player_rect.height
player_x = (screen_width - player_width) // 2
player_y = (screen_height - player_height) // 2
# 设置速度
player_speed = 5
while True:
# 处理退出事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# 获取键盘输入
keys = pygame.key.get_pressed()
# 移动玩家
if keys[pygame.K_UP]:
player_y -= player_speed
if keys[pygame.K_DOWN]:
player_y += player_speed
if keys[pygame.K_LEFT]:
player_x -= player_speed
if keys[pygame.K_RIGHT]:
player_x += player_speed
# 边缘碰撞检测
if player_x < 0:
player_x = 0
if player_x + player_width > screen_width:
player_x = screen_width - player_width
if player_y < 0:
player_y = 0
if player_y + player_height > screen_height:
player_y = screen_height - player_height
# 绘制画面
screen.fill((0, 0, 0))
screen.blit(player_image, (player_x, player_y))
pygame.display.flip()
在这个示例中,我们使用pygame包创建了一个窗口,并加载了一个玩家的图片。玩家可以通过键盘输入上下左右键来移动。边缘碰撞检测部分会检测玩家是否超出了窗口边界,如果超出了边界则将玩家位置限制在边界范围内。
你可以将示例代码保存为一个.py文件,然后在同级目录下放置一个名为"player.png"的图片文件,运行代码即可看到效果。
上一篇:表面磁性水平z轴旋转问题
下一篇:表面的渐变颜色