import pygame import sys # 初始化 pygame.init() SCREEN_WIDTH = 800 SCREEN_HEIGHT = 600 GRID_SIZE = 40 GRID_COLS = SCREEN_WIDTH // GRID_SIZE GRID_ROWS = SCREEN_HEIGHT // GRID_SIZE # 颜色 WHITE = (255, 255, 255) BLACK = (0, 0, 0) RED = (255, 0, 0) BLUE = (0, 0, 255) GRAY = (128, 128, 128) GREEN = (0, 255, 0) screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) pygame.display.set_caption("战争沙盘 - 4v4吃子版") clock = pygame.time.Clock() font = pygame.font.SysFont(None, 48) small_font = pygame.font.SysFont(None, 32) # 单位类 class Unit: def __init__(self, grid_x, grid_y, team): self.x = grid_x self.y = grid_y self.team = team # 0红 1蓝 self.selected = False def draw(self): cx = self.x * GRID_SIZE + GRID_SIZE // 2 cy = self.y * GRID_SIZE + GRID_SIZE // 2 color = RED if self.team == 0 else BLUE pygame.draw.circle(screen, color, (cx, cy), 12) if self.selected: pygame.draw.rect(screen, GREEN, (self.x * GRID_SIZE, self.y * GRID_SIZE, GRID_SIZE, GRID_SIZE), 2) # 生成双方各4个单位 red_units = [Unit(7, 2 + i, 0) for i in range(11)] red_units += [Unit(6, 2 + i, 0) for i in range(11)] red_units += [Unit(5, 2 + i, 0) for i in range(11)] red_units += [Unit(4, 2 + i, 0) for i in range(11)] red_units += [Unit(3, 2 + i, 0) for i in range(11)] red_units += [Unit(2, 2 + i, 0) for i in range(11)] blue_units = [Unit(12, 7 + i, 1) for i in range(1)] current_turn = 0 # 0红 1蓝 selected = None game_over = False def draw_grid(): for x in range(0, SCREEN_WIDTH, GRID_SIZE): pygame.draw.line(screen, GRAY, (x, 0), (x, SCREEN_HEIGHT), 1) for y in range(0, SCREEN_HEIGHT, GRID_SIZE): pygame.draw.line(screen, GRAY, (0, y), (SCREEN_WIDTH, y), 1) def get_grid(pos): x, y = pos return x // GRID_SIZE, y // GRID_SIZE # 主循环 while True: screen.fill(WHITE) draw_grid() # 事件 for e in pygame.event.get(): if e.type == pygame.QUIT: pygame.quit() sys.exit() if not game_over and e.type == pygame.MOUSEBUTTONDOWN and e.button == 1: gx, gy = get_grid(e.pos) # 1. 选择己方单位 if selected is None: if current_turn == 0: for u in red_units: if u.x == gx and u.y == gy: selected = u u.selected = True else: for u in blue_units: if u.x == gx and u.y == gy: selected = u u.selected = True # 2. 移动单位 else: # 移动 selected.x = gx selected.y = gy selected.selected = False # 判断吃子 if selected.team == 0: # 红吃蓝 for b in blue_units[:]: if b.x == gx and b.y == gy: blue_units.remove(b) else: # 蓝吃红 for r in red_units[:]: if r.x == gx and r.y == gy: red_units.remove(r) # 切换回合 selected = None current_turn = 1 - current_turn # 绘制单位 for u in red_units + blue_units: u.draw() # 胜利判断 if len(red_units) == 0: game_over = True tip = "蓝方胜利!" elif len(blue_units) == 0: game_over = True tip = "红方胜利!" # 文字 if game_over: text = font.render(tip, True, BLACK) screen.blit(text, (SCREEN_WIDTH//2 - 100, SCREEN_HEIGHT//2)) else: turn_text = small_font.render(f"当前回合:{'红方' if current_turn==0 else '蓝方'}", True, BLACK) screen.blit(turn_text, (10, 10)) pygame.display.flip() clock.tick(60)
Note.ms
/chirenyouxi3245