Python编写一个stg
时间: 2023-05-23 15:02:03 浏览: 107
stg-pythonWebdriver
很高兴回答您的问题!以下是一个简单的 Python STG 游戏实现的示例代码:
```
import pygame
import random
# 初始化
pygame.init()
# 设置游戏界面宽、高
screen_width = 480
screen_height = 640
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("STG Game")
# 载入玩家图片
player_img = pygame.image.load("player.png")
player_size = player_img.get_rect().size
player_width = player_size[0]
player_height = player_size[1]
player_x_pos = (screen_width - player_width) / 2
player_y_pos = screen_height - player_height
# 载入敌人图片
enemy_img = pygame.image.load("enemy.png")
enemy_size = enemy_img.get_rect().size
enemy_width = enemy_size[0]
enemy_height = enemy_size[1]
enemy_x_pos = random.randint(0, screen_width - enemy_width)
enemy_y_pos = 0
enemy_speed = 10
# 设置时钟
clock = pygame.time.Clock()
# 游戏循环
running = True
while running:
# 设置刷新率
dt = clock.tick(60)
# 事件循环
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# 移动玩家
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
player_x_pos -= 5
elif keys[pygame.K_RIGHT]:
player_x_pos += 5
elif keys[pygame.K_UP]:
player_y_pos -= 5
elif keys[pygame.K_DOWN]:
player_y_pos += 5
# 移动敌人
enemy_y_pos += enemy_speed
# 碰撞检测
if player_x_pos + player_width > enemy_x_pos and \
player_x_pos < enemy_x_pos + enemy_width and \
player_y_pos + player_height > enemy_y_pos and \
player_y_pos < enemy_y_pos + enemy_height:
print("Game Over!")
running = False
# 绘制游戏界面
screen.blit(player_img, (player_x_pos, player_y_pos))
screen.blit(enemy_img, (enemy_x_pos, enemy_y_pos))
pygame.display.update()
# 退出游戏
pygame.quit()
```
只要运行这段代码,您就可以在窗口中看到一个玩家和一个从顶部下落的敌人。您可以使用箭头键来控制玩家的移动。当玩家和敌人碰撞时,游戏将结束。
祝您玩得愉快!
阅读全文