import pygame import random import sys # 初始化pygame pygame.init() WIDTH, HEIGHT = 800, 600 screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("简易射击小游戏") # 颜色定义 WHITE = (255, 255, 255) BLUE = (0, 100, 255) RED = (255, 0, 0) BLACK = (0, 0, 0) # 玩家设置 player_size = 40 player_x = WIDTH // 2 player_y = HEIGHT // 2 player_speed = 5 # 子弹列表、敌人列表 bullets = [] enemies = [] bullet_speed = 10 score = 0 clock = pygame.time.Clock() font = pygame.font.SysFont(None, 40) # 生成敌人函数 def create_enemy(): ex = random.randint(0, WIDTH - 30) ey = random.randint(0, HEIGHT - 30) enemies.append([ex, ey, 30]) # 游戏主循环 running = True while running: screen.fill(WHITE) mouse_x, mouse_y = pygame.mouse.get_pos() keys = pygame.key.get_pressed() # 事件监听 for event in pygame.event.get(): if event.type == pygame.QUIT: running = False # 鼠标点击发射子弹 if event.type == pygame.MOUSEBUTTONDOWN: bullets.append([player_x + player_size//2, player_y + player_size//2, mouse_x, mouse_y]) # WASD移动玩家 if keys[pygame.K_W] and player_y > 0: player_y -= player_speed if keys[pygame.K_S] and player_y < HEIGHT - player_size: player_y += player_speed if keys[pygame.K_A] and player_x > 0: player_x -= player_speed if keys[pygame.K_D] and player_x < WIDTH - player_size: player_x += player_speed # 随机生成敌人 if random.randint(1, 60) == 1: create_enemy() # 更新子弹位置 for b in bullets[:]: bx, by, tx, ty = b dx = tx - bx dy = ty - by dist = (dx**2 + dy**2)**0.5 if dist != 0: bx += dx / dist * bullet_speed by += dy / dist * bullet_speed b[0], b[1] = bx, by # 超出屏幕删除子弹 if bx < 0 or bx > WIDTH or by < 0 or by > HEIGHT: bullets.remove(b) # 子弹碰撞敌人 for b in bullets[:]: bx, by, _, _ = b for e in enemies[:]: ex, ey, esize = e if ex < bx < ex + esize and ey < by < ey + esize: enemies.remove(e) bullets.remove(b) score += 10 break # 绘制玩家(蓝色方块) pygame.draw.rect(screen, BLUE, (player_x, player_y, player_size, player_size)) # 绘制敌人(红色方块) for e in enemies: pygame.draw.rect(screen, RED, (e[0], e[1], e[2], e[2])) # 绘制子弹(小黑点) for b in bullets: pygame.draw.circle(screen, BLACK, (int(b[0]), int(b[1])), 5) # 显示分数 score_text = font.render(f"分数:{score}", True, BLACK) screen.blit(score_text, (10, 10)) pygame.display.flip() clock.tick(60) pygame.quit() sys.exit()
html2.link
举报