游戏:元梦之星游戏开发代码(谢苏)

在这里插入图片描述
在这里插入图片描述
《元梦之星》是一款轻松社交派对游戏,玩家们可以化身星宝,体验纯粹的游玩乐趣,收获简单的快乐。无论i人e人,都能轻松找到属于自己的社交方式。 《元梦之星》的快乐,可以是闯关夺冠时的激动,谁是狼人推理的巧妙,峡谷3V3打赢团战的爽感。也可以是星梦广场开火车的闹腾,农场生活的悠闲,钓到大鱼的惊喜,星世界与星家园带来的感动,还有全世界的星朋友,陪你一起去胡闹。下面用python写代码。

一.蜡笔小新皮肤获取全流程
在这里插入图片描述

在这里插入图片描述

进入祈愿系统

登录游戏后点击主界面顶部菜单栏的【祈愿】按钮

在祈愿页面左侧选择【蜡笔小新联动】专题页

小新的饼干屋机制

该活动采用保底机制:累计祈愿6次必得蜡笔小新皮肤

每次祈愿消耗1个幸运币,单次十连祈愿可享受9折优惠(仅需9个幸运币)

幸运币获取途径

免费获取:

完成每日任务(每日最多可获得2枚)

参与周末限定活动(额外奖励3-5枚)

新手七日签到(第7天赠送5枚)

付费兑换:

商城-星钻兑换:10星钻=1幸运币

首充双倍优惠(首次充值可获得双倍星钻)

import pygame
import random
import sys
from pygame.locals import*

#初始化pygame
pygame.init()
pygame.mixer.init()H

#屏幕设置
SCREEN_WIDTH = 1024
SCREEN_HEIGHT = 768
screen = pygame.dislay.set_model((SCREEN_WIDTH,SCREEN_HEIGHT))
pygame.display.set_caption("元梦之星 - 蜡笔小新皮肤获取模拟器")

#颜色定义
WHITE =255,255,255)
BLACK = (0,0,0)
PINK =255,182,193)
GOLD =255215,0)
BLUE =30,144,255#加载字体
font_large = pygame.font.SysFont('simhei',48)
font_medium = pygame.font.SysFont('simhei',36)
font_small = pygame.font.SysFont('simhei',24)

#游戏数据
class GameData:
  def_init_(self):
  self.lucky_coins = #初始幸运币
  self.star_diamonds = 0 #星钻
  self.wish_count = 0 #已祈愿次数
  self.has_skin = False # 是否获得皮肤
  self.daily_tasks = False # 每日任务完成状态
  self.animation_playing = False
  self.animation_frame = 0
  self.result_message = ""
  
  def add_coins(self,amount):
    self.lucky_coins += amount
  
  def wish(self):
    if self.lucky_coins >= 1 and not self.has_skin:
       self.lucky_coins -= 1
       self.wish_count += 1
     
     #保底机制:第6次必得
     if self.wish_count >= 6:
        self.has_skin = True
        self.result_message="恭喜获得蜡笔小新皮肤!"
        return"skin"
      else:
        rewards = ["星钻x10", "装饰碎片x5", "表情包", "金币x100"]
        self.result_message = f"获得:{random.choice(rewards)}(进度:{self.wish_count}/6)"return"item"

#创建按钮类
class Button:
  def_init_(self,x,y,width,height,text,color):
      self.rect = pygame.Rect(x,y,width,height)
      self.text = text
      self.color = color
      self.hover_color = (min(color[0]+30,255),min(color[1]+30,255),min(color[2]+30,255))
  
  def draw(self,surface):
     mouse_pos = pygame.mouse.get_pos()
     current_color = self.hover_ color if
 self.rect.colliderpoint(mouse_pos)else else self.color
   
     pygame.draw.rect(surface,current_color,self.rect,border_radius=10) 
pygame.draw.rect(surface,BLACK,self.rect,2,boder_radius =10)

text_surf = font_medium.render(self.text,True,BLACK)
text_rect = text_surf.get_rect(center=self.rect.center)
surface.blit(text_surf,text_rect)

def is_clicked(self,pos,event):
  if event.type == MOUSEBUTTIONDOWN and
event.button == 1:
  return self.rect.collidepoint(pos)
 return False

#主游戏类
class WishSystem:
   def_init_(self):
      self.data = GameData()
      self.buttons = [
         Button(350,400,300,60,"祈愿一次(1幸运币)",144,238,144)),
         Button(350,500,300,60,"十连祈愿(9幸运币)",255,215,0)),
         Button(700,650,200,50,"完成每日任务",(70,130,180)),
         Button(100,650,200,50,"星钻兑换",220,20,60))]
         self.shinchan_img = None # 这里应该加载图片,用矩形代替
         self.shinchan_rect = pygame.Rect(400,140,200,300)
      
      def draw_main_menu(self):
        #背景
       screen.fill(WHITE)
        
       #标题
       title = font_large.render("蜡笔小新皮肤祈愿",True,BLACK)
       screen.blit(title,(SCREEN_WIDTH//2 - title.get_width()//2,50))
     
      #绘制小新图片
      pygame.draw.rect(screen,BLUE,self.shinchan_rect)
      if self.data.has_skin:
        text = font_smll.render("已获得皮肤",True,BLACK)
      else:
        text = font_small.render(f"祈愿进度:{self.data.wish_count}/6"True,BLACK}
        screen.blit(text,(self.shinchan_rect.centerx - text.get_width()//2, 
                         self.shinchan_rect.bottom + 10))
     
        
        # 绘制资源信息
        coin_text = font_medium.render(f"幸运币: {self.data.lucky_coins}", True, GOLD)
        diamond_text = font_medium.render(f"星钻: {self.data.star_diamonds}", True, BLUE)
        
        screen.blit(coin_text, (50, 100))
        screen.blit(diamond_text, (50, 150))
        
        # 绘制按钮
        for button in self.buttons:
            button.draw(screen)
            
            # 禁用已获得皮肤后的祈愿按钮
            if (button.text.startswith("祈愿") and self.data.has_skin) or \
               (button.text == "十连祈愿" and self.data.lucky_coins < 9):
                overlay = pygame.Surface((button.rect.width, button.rect.height), pygame.SRCALPHA)
                overlay.fill((200, 200, 200, 128))
                screen.blit(overlay, button.rect)
        
        # 绘制结果消息
        if self.data.result_message:
            text = font_medium.render(self.data.result_message, True, BLACK)
            screen.blit(text, (SCREEN_WIDTH//2 - text.get_width()//2, 350))
        
        # 绘制操作说明
        tips = [
            "保底机制:6次祈愿必得皮肤",
            "幸运币可通过任务或星钻兑换获取",
            "10星钻=1幸运币"
        ]
        for i, tip in enumerate(tips):
            text = font_small.render(tip, True, BLACK)
            screen.blit(text, (SCREEN_WIDTH - 300, 100 + i * 40))
        
        pygame.display.flip()
    
    def handle_events(self):
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
                
            # 按钮点击检测
            mouse_pos = pygame.mouse.get_pos()
            
            # 祈愿一次
            if self.buttons[0].is_clicked(mouse_pos, event) and not self.data.has_skin:
                if self.data.lucky_coins >= 1:
                    result = self.data.wish()
                    # 这里可以添加动画效果
                else:
                    self.data.result_message = "幸运币不足!"
            
            # 十连祈愿
            elif self.buttons[1].is_clicked(mouse_pos, event) and not self.data.has_skin:
                if self.data.lucky_coins >= 9:
                    for _ in range(10):
                        if not self.data.has_skin:
                            result = self.data.wish()
                    self.data.result_message = f"十连结束!进度:{self.data.wish_count}/6"
                else:
                    self.data.result_message = "幸运币不足9个!"
            
            # 完成每日任务
            elif self.buttons[2].is_clicked(mouse_pos, event):
                if not self.data.daily_tasks:
                    self.data.add_coins(2)
                    self.data.daily_tasks = True
                    self.data.result_message = "完成每日任务,获得2幸运币!"
                else:
                    self.data.result_message = "今日任务已完成"
            
            # 星钻兑换
            elif self.buttons[3].is_clicked(mouse_pos, event):
                if self.data.star_diamonds >= 10:
                    self.data.star_diamonds -= 10
                    self.data.add_coins(1)
                    self.data.result_message = "兑换成功:10星钻→1幸运币"
                else:
                    self.data.result_message = "星钻不足(需10星钻)"
    
    def run(self):
        clock = pygame.time.Clock()
        
        # 模拟初始赠送星钻
        self.data.star_diamonds = 30
        
        while True:
            self.handle_events()
            self.draw_main_menu()
            clock.tick(60)

# 运行游戏
if __name__ == "__main__":
    game = WishSystem()
    game.run()
      

           
        
  





小新的饼干屋:
在这里插入图片描述
在这里插入图片描述

饼干屋特色玩法
互动彩蛋

获得皮肤后,家园场景会解锁特殊互动:

点击小新会触发"动感超人"舞蹈

与小白宠物同屏会出现追逐动画

专属技能特效

使用皮肤时:

胜利动作变为"屁股摇摇舞"

失败时触发"妈妈我错了"哭泣表情

隐藏成就

连续使用小新皮肤游戏10场可解锁【春日部防卫队】称号

在饼干屋完成5次完美烹饪获得【特级厨师】勋章

class YuanMengStarSkinSystem:
    def __init__(self):
        self.skin_activated = False
        self.games_played = 0
        self.perfect_cooking = 0
        self.unlocked_titles = []
        self.unlocked_medals = []

    def activate_skin(self, skin_name):
        if skin_name == "蜡笔小新":
            self.skin_activated = True
            print("蜡笔小新皮肤已激活!家园场景解锁特殊互动彩蛋!")
            self.unlock_home_interactions()
        else:
            self.skin_activated = False

    def unlock_home_interactions(self):
        print(">>> 家园彩蛋解锁:点击小新会触发'动感超人'舞蹈")
        print(">>> 家园彩蛋解锁:与小白宠物同屏会出现追逐动画")

    def trigger_victory(self):
        if self.skin_activated:
            print("[特效] 小新跳起了'屁股摇摇舞'!")
        else:
            print("标准胜利动作")

    def trigger_defeat(self):
        if self.skin_activated:
            print("[特效] 小新哭着脸说'妈妈我错了'")
        else:
            print("标准失败动作")

    def play_game(self):
        if self.skin_activated:
            self.games_played += 1
            self.check_achievements()
    
    def perfect_cook(self):
        if self.skin_activated:
            self.perfect_cooking += 1
            self.check_achievements()
    
    def check_achievements(self):
        # 检查春日部防卫队称号
        if self.games_played >= 10 and "春日部防卫队" not in self.unlocked_titles:
            self.unlocked_titles.append("春日部防卫队")
            print("成就解锁!获得称号【春日部防卫队】")
        
        # 检查特级厨师勋章
        if self.perfect_cooking >= 5 and "特级厨师" not in self.unlocked_medals:
            self.unlocked_medals.append("特级厨师")
            print("成就解锁!获得勋章【特级厨师】")

    def display_status(self):
        print("\n当前状态:")
        print(f"使用小新皮肤: {'是' if self.skin_activated else '否'}")
        print(f"已玩游戏场次: {self.games_played}/10")
        print(f"完美烹饪次数: {self.perfect_cooking}/5")
        print(f"已解锁称号: {', '.join(self.unlocked_titles) if self.unlocked_titles else '无'}")
        print(f"已解锁勋章: {', '.join(self.unlocked_medals) if self.unlocked_medals else '无'}")


# 测试代码
if __name__ == "__main__":
    system = YuanMengStarSkinSystem()
    
    # 激活皮肤
    system.activate_skin("蜡笔小新")
    system.display_status()
    
    # 触发互动
    print("\n--- 家园互动测试 ---")
    print("玩家点击了小新角色...")
    print(">>> 触发: 动感超人舞蹈")
    print("小白宠物进入场景...")
    print(">>> 触发: 追逐动画")
    
    # 游戏对战测试
    print("\n--- 对战测试 ---")
    for i in range(3):
        system.play_game()
    system.trigger_victory()
    system.trigger_defeat()
    
    # 烹饪测试
    print("\n--- 饼干屋烹饪测试 ---")
    for i in range(6):
        system.perfect_cook()
    
    # 继续游戏
    print("\n--- 继续游戏 ---")
    for i in range(7):
        system.play_game()
    
    # 显示最终状态
    system.display_status()

二:场景地图

该作地图主要为大厅,玩家通过点击大厅界面中的图标进行场景切换,进入不同的功能菜单。具体如下:

1.大厅
玩家日常待机的地方,能在其中查看邮件、和其他待机玩家进行互动等。
开始快速开始一场游戏。
在这里插入图片描述

import random
import time

class Player:
  def_init_(self,name):
   self.name = name
   self.status = "待机中"
   self.position = (random.randint(0,100),(random.randint(0,100))

def move(self):
  self.position = (self.position[0] + random.randint(-5,5),
  print.position[1] + random.randint(-5,5))
  print(f"{self.name}移动到了位置{self.position}")

def interact(self,other_plater):
   print(f"{self.name}正在与{other_palyer.name}互动")
   time.sleep(1)
   print(f"{self.name}正在与{other_player.name}互动完成"}
    
def check_mail(self):
   print(f"{self.name}正在查看邮件...")
   time.sleep(0.5)
   mails = ["系统通知","好友申请","活动奖励"]
   print(f"收到邮件:{random.choice(mails)}")

def ready_for_game(self):
   self.status = "准备游戏中"
   print(f"{self.name}已准备开始游戏")

class GameLobby:
  def_init_(self):
    self.players = []
    self.max_palyer = 50

def add_player(self,player):
   if len(self.players) < self.max_players:
      self.players.append(player)
      print(f"{player.name}进入了元梦之星大厅")
      return True
   else:
      print("大厅已满,无法进入")
      return False

  def remove_player(self,player):
     if palyer in self.players: 
       self.palyers.remove(player)
       print(f"{player.name}离开了大厅")

 def statr_game(self,players):
    print("\n游戏即将开始...")
    for p in players:
       p.status = "游戏中"
       time.sleep(3)
       winner = random.choice(palyers)
       print(f"游戏开始!"{winner.name}获得了胜利!")
       for p in players:
          p.status = "待机中"
   
   def quick_start(self,palyer):
       ready_players = [p for p in self.players if p.status=="准备游戏中"]
       if len(ready_players) >= 3:#假设最少需要4人开始游戏
          players_to_statrt = ready_player[:3]+ [player]
          self.start_game(players[:3] + [player]
          self.start_game(palyers_to_start)
      else:
         print("等待更多玩家准备...")
         player.ready_for_game()

#模拟大厅运行
    def simulate_lobby():
      lobby = GameLobby()
   
   #创建一些国家
   players = [Player(f"玩家{i+1}")for i in range(10)]
    for p in players:
        lobby.add_player(p)
   
   #模拟玩家行为
     for _ in range(5):
       time.sleep(1)
       p = random.choice(players)
       action = random.randint(0,3)
    
    if action == 0:
       p.move()
    elif action == 1:
     other = random.([op for op in players if op != p])
     p.interact(other)
     elif action == 2:
      p.check_mail()
     elif action ==3:
       print(f"\n{p.name}点击了'快速开始'按钮")
       lobby.quick_start(p)

if_name_=="_main_":
  print("欢迎来到了元梦之星大厅!")
  simulate_lobby()        
                  
                  
    
          
        
     

   


  

2.星世界
由星选好图、星图广场、星海巡游、造梦空间组成,能在其中体验其他玩家创建的地图进行游戏,也能自行创建游戏地图。

在这里插入图片描述

import random
from typing import List,Dict,Optional

class Player
  def_init_(self,name:str):
    self.name = name
    self.level = 1
    self.experience = 0
 
 def gain_experience(self,amount:int):
     self.experience += amount
     if self.experience >= 100:
        self.level += 1
        self.experience -= 100
        print(f"{self.name}升级到{self.level}级!")

class GameMap: 
    def_init_(self,name:str,creator:str,map_type:str,difficulty:int = 1):
    self.name = name
    self.creator = creator
    self.map_type = map_type # 地图类型,如竞速,解谜,战斗等 
    self.difficulty = difficulty
    self.play_count = 0
    self.rating  = 0.0
    self.ratings =[]
  
  def play(self)
     self.play_count += 1
     print(f"正在游玩地图:{self.name}(作者:{self.creator})")
     # 模拟游戏过程
     result = random.choice(["胜利","失败"])
     print(f"游戏结果:{result}")
     return result
   
  def rate(self,score:int):
    if 1 <= score <= 5:
      self.ratings.append(score)
      self.rating = sum(self.ratings)/len(self.ratings)
      print(f"已为地图{self.name}评分:{score}星")
    else: 
       print("评分应在1-5星之间")

class StarWorld:
   def _init_(self):
     #初始化四个主要组成部分
     self.star_selected_maps = StarSelectedMaps() # 星选好图
     self.star_map_plaza = StarMapPlaza()        #星图广场
     self.star_sea_cruise = StarSeaCruise()     # 星海巡游
     self.dream_workshop = DreamWorkshop()      #造梦空间
      
     self.players = {}        #玩家数据库
     self.current_player  = None

 def  register_player(self,name:str):
     if name not in self.players:
        self.players[name] = Player(name)
        print(f"玩家{name}注册成功!")
        return True
   else: 
     print("该名称已被使用,请尝试其他名称")
     return False
     def login(self, name: str):
        if name in self.players:
            self.current_player = self.players[name]
            print(f"欢迎回来, {name}!")
            return True
        else:
            print("未找到该玩家,请先注册")
            return False

class StarSelectedMaps:
    """星选好图 - 精选玩家创作的地图"""
    def __init__(self):
        self.featured_maps = [
            GameMap("极速狂飙", "SpeedMaster", "竞速", 3),
            GameMap("迷宫探险", "PuzzleLover", "解谜", 2),
            GameMap("星际大战", "SpaceFighter", "战斗", 4)
        ]
    
    def show_featured_maps(self):
        print("\n=== 星选好图 ===")
        for i, map in enumerate(self.featured_maps, 1):
            print(f"{i}. {map.name} - 类型: {map.map_type} 难度: {'★' * map.difficulty} 评分: {map.rating:.1f}")

    def play_map(self, index: int):
        if 0 <= index < len(self.featured_maps):
            return self.featured_maps[index].play()
        else:
            print("无效的地图编号")
            return None

class StarMapPlaza:
    """星图广场 - 浏览和搜索所有玩家创作的地图"""
    def __init__(self):
        self.all_maps = [
            GameMap("欢乐跳跳", "JumpKing", "平台跳跃", 2),
            GameMap("密室逃脱", "EscapePro", "解谜", 3),
            GameMap("赛车冠军", "RacerX", "竞速", 4),
            GameMap("怪物猎人", "MonsterHunter", "战斗", 5),
            GameMap("水上乐园", "WaterFun", "休闲", 1)
        ]
        self.search_results = []
    
    def search_maps(self, keyword: str = "", map_type: str = ""):
        self.search_results = [
            map for map in self.all_maps 
            if (keyword.lower() in map.name.lower() or keyword.lower() in map.creator.lower()) and
               (map_type == "" or map.map_type == map_type)
        ]
        
        print("\n=== 搜索结果 ===")
        if not self.search_results:
            print("没有找到匹配的地图")
        else:
            for i, map in enumerate(self.search_results, 1):
                print(f"{i}. {map.name} - 作者: {map.creator} 类型: {map.map_type} 难度: {'★' * map.difficulty}")
    
    def play_map(self, index: int):
        if 0 <= index < len(self.search_results):
            return self.search_results[index].play()
        else:
            print("无效的地图编号")
            return None

class StarSeaCruise:
    """星海巡游 - 随机体验玩家创作的地图"""
    def __init__(self):
        self.random_maps = [
            GameMap("幸运轮盘", "LuckyPlayer", "休闲", 1),
            GameMap("未知领域", "Explorer", "冒险", 3),
            GameMap("惊喜派对", "PartyGoer", "社交", 2)
        ]
    
    def cruise(self):
        print("\n=== 星海巡游 ===")
        print("准备开始随机地图冒险...")
        selected_map = random.choice(self.random_maps)
        result = selected_map.play()
        
        # 随机获得经验值
        exp_gain = random.randint(10, 30)
        print(f"获得 {exp_gain} 点经验值!")
        return exp_gain, result

class DreamWorkshop:
    """造梦空间 - 创建自己的游戏地图"""
    def __init__(self):
        self.my_creations = []
    
    def create_map(self, name: str, map_type: str, difficulty: int):
        if not name or not map_type:
            print("地图名称和类型不能为空")
            return None
        
        if difficulty < 1 or difficulty > 5:
            print("难度必须在1-5之间")
            return None
        
        new_map = GameMap(name, "我", map_type, difficulty)
        self.my_creations.append(new_map)
        print(f"成功创建地图: {name} (类型: {map_type}, 难度: {difficulty}星)")
        return new_map
    
    def show_my_creations(self):
        print("\n=== 我的创作 ===")
        if not self.my_creations:
            print("你还没有创建任何地图")
        else:
            for i, map in enumerate(self.my_creations, 1):
                print(f"{i}. {map.name} - 类型: {map.map_type} 难度: {'★' * map.difficulty} 游玩次数: {map.play_count}")

# 示例使用
if __name__ == "__main__":
    star_world = StarWorld()
    
    # 注册并登录玩家
    star_world.register_player("DreamPlayer")
    star_world.login("DreamPlayer")
    
    # 体验星选好图
    print("\n体验星选好图:")
    star_world.star_selected_maps.show_featured_maps()
    star_world.star_selected_maps.play_map(0)
    
    # 在星图广场搜索地图
    print("\n在星图广场搜索地图:")
    star_world.star_map_plaza.search_maps("赛车", "竞速")
    star_world.star_map_plaza.play_map(0)
    
    # 星海巡游
    print("\n体验星海巡游:")
    exp, result = star_world.star_sea_cruise.cruise()
    star_world.current_player.gain_experience(exp)
    
    # 在造梦空间创建地图
    print("\n在造梦空间创建地图:")
    star_world.dream_workshop.create_map("我的第一个地图", "解谜", 2)
    star_world.dream_workshop.show_my_creations() 
           
          
  
                  

3.热购、祈愿、商城
消耗游戏币,购买道具、装扮。
在这里插入图片描述

在这里插入图片描述

import random
from enum import Enum

class CurrencyType(Enum):
    STAR_COIN = "星币"  # 普通游戏币
    DIAMOND = "钻石"    # 高级货币
    COUPON = "优惠券"   # 活动货币

class Item:
    def __init__(self, item_id, name, item_type, price, currency=CurrencyType.STAR_COIN):
        self.id = item_id
        self.name = name
        self.type = item_type  # "装扮"、"道具"、"礼包"等
        self.price = price
        self.currency = currency

class WishPool:
    def __init__(self, pool_name, items, probabilities):
        self.pool_name = pool_name
        self.items = items  # Item对象列表
        self.probabilities = probabilities  # 对应概率列表
        
    def wish(self, times=1):
        results = random.choices(self.items, weights=self.probabilities, k=times)
        return results

class Player:
    def __init__(self, name):
        self.name = name
        self.wallet = {
            CurrencyType.STAR_COIN: 10000,  # 初始星币
            CurrencyType.DIAMOND: 500,      # 初始钻石
            CurrencyType.COUPON: 0          # 初始优惠券
        }
        self.inventory = []
        self.equipped = {}  # 当前穿戴的装扮
    
    def add_currency(self, currency_type, amount):
        self.wallet[currency_type] += amount
    
    def can_afford(self, item):
        return self.wallet[item.currency] >= item.price
    
    def purchase(self, item):
        if not self.can_afford(item):
            return False
        
        self.wallet[item.currency] -= item.price
        self.inventory.append(item)
        return True
    
    def wish(self, wish_pool, times=1):
        cost_per_wish = 160  # 每次祈愿消耗160钻石
        total_cost = cost_per_wish * times
        
        if self.wallet[CurrencyType.DIAMOND] < total_cost:
            return None
        
        self.wallet[CurrencyType.DIAMOND] -= total_cost
        return wish_pool.wish(times)
    
    def equip(self, item):
        if item in self.inventory and item.type == "装扮":
            self.equipped[item.type] = item
            return True
        return False

class Shop:
    def __init__(self):
        self.hot_items = []  # 热购商品
        self.regular_items = []  # 常驻商品
    
    def refresh_hot_items(self, new_items):
        self.hot_items = new_items
    
    def display_items(self, category="all"):
        items = []
        if category == "hot" or category == "all":
            print("\n=== 热购商品 ===")
            for idx, item in enumerate(self.hot_items, 1):
                print(f"{idx}. {item.name} [{item.type}] 价格: {item.price} {item.currency.value}")
            items.extend(self.hot_items)
        
        if category == "regular" or category == "all":
            print("\n=== 常驻商品 ===")
            for idx, item in enumerate(self.regular_items, 1):
                print(f"{idx+len(self.hot_items)}. {item.name} [{item.type}] 价格: {item.price} {item.currency.value}")
            items.extend(self.regular_items)
        
        return items

# 初始化游戏物品
def initialize_items():
    # 装扮物品
    outfit1 = Item(101, "蜡笔小新套装", "装扮", 2880, CurrencyType.STAR_COIN)
    outfit2 = Item(102, "动感超人战衣", "装扮", 4500, CurrencyType.DIAMOND)
    # 道具
    prop1 = Item(201, "星梦礼盒", "道具", 1200, CurrencyType.STAR_COIN)
    prop2 = Item(202, "豪华礼包", "道具", 800, CurrencyType.DIAMOND)
    # 祈愿池物品
    wish_item1 = Item(301, "限定星空装扮", "装扮", 0, CurrencyType.DIAMOND)
    wish_item2 = Item(302, "稀有光效翅膀", "装扮", 0, CurrencyType.DIAMOND)
    wish_item3 = Item(303, "普通表情包", "道具", 0, CurrencyType.DIAMOND)
    
    return [outfit1, outfit2, prop1, prop2], [wish_item1, wish_item2, wish_item3]

# 主游戏循环
def main():
    # 初始化系统
    shop_items, wish_items = initialize_items()
    shop = Shop()
    shop.hot_items = [shop_items[0], shop_items[3]]  # 蜡笔小新套装和豪华礼包
    shop.regular_items = [shop_items[1], shop_items[2]]  # 其他商品
    
    wish_pool = WishPool(
        pool_name="星空祈愿",
        items=wish_items,
        probabilities=[0.01, 0.09, 0.9]  # 1%, 9%, 90%
    )
    
    player = Player("元梦玩家")
    
    while True:
        print("\n===== 元梦之星商城系统 =====")
        print(f"玩家: {player.name}")
        print(f"余额: 星币 {player.wallet[CurrencyType.STAR_COIN]} | "
              f"钻石 {player.wallet[CurrencyType.DIAMOND]} | "
              f"优惠券 {player.wallet[CurrencyType.COUPON]}")
        print("\n1. 浏览商城\n2. 热购商品\n3. 祈愿池\n4. 查看背包\n5. 退出")
        
        choice = input("请选择操作: ")
        
        if choice == "1":
            items = shop.display_items()
            item_choice = input("请输入要购买的商品编号(0返回): ")
            if item_choice == "0":
                continue
            try:
                selected_item = items[int(item_choice)-1]
                if player.purchase(selected_item):
                    print(f"成功购买 {selected_item.name}!")
                else:
                    print("余额不足!")
            except (IndexError, ValueError):
                print("无效选择!")
        
        elif choice == "2":
            items = shop.display_items("hot")
            item_choice = input("请输入要购买的热购商品编号(0返回): ")
            if item_choice == "0":
                continue
            try:
                selected_item = shop.hot_items[int(item_choice)-1]
                if player.purchase(selected_item):
                    print(f"成功购买 {selected_item.name}!")
                else:
                    print("余额不足!")
            except (IndexError, ValueError):
                print("无效选择!")
        
        elif choice == "3":
            print("\n=== 星空祈愿池 ===")
            print("每次祈愿消耗160钻石")
            print("概率公示:")
            print("- 限定星空装扮 (1%)")
            print("- 稀有光效翅膀 (9%)")
            print("- 普通表情包 (90%)")
            
            wish_choice = input("\n1. 单次祈愿\n2. 十连祈愿\n3. 返回\n请选择: ")
            if wish_choice == "1":
                results = player.wish(wish_pool)
                if results:
                    print("\n祈愿结果:")
                    for item in results:
                        player.inventory.append(item)
                        print(f"获得: {item.name}")
                else:
                    print("钻石不足!")
            elif wish_choice == "2":
                results = player.wish(wish_pool, 10)
                if results:
                    print("\n十连祈愿结果:")
                    for item in results:
                        player.inventory.append(item)
                        print(f"获得: {item.name}")
                else:
                    print("钻石不足!需要1600钻石!")
        
        elif choice == "4":
            print("\n=== 我的背包 ===")
            if not player.inventory:
                print("背包空空如也~")
            else:
                for idx, item in enumerate(player.inventory, 1):
                    print(f"{idx}. {item.name} [{item.type}]")
            
            equip_choice = input("\n输入装备编号进行穿戴(0返回): ")
            if equip_choice != "0":
                try:
                    item = player.inventory[int(equip_choice)-1]
                    if player.equip(item):
                        print(f"已装备 {item.name}!")
                    else:
                        print("无法装备此物品!")
                except (IndexError, ValueError):
                    print("无效选择!")
        
        elif choice == "5":
            print("感谢游玩元梦之星!")
            break
        
        else:
            print("无效输入,请重新选择!")

if __name__ == "__main__":
    main()

功能说明:
货币系统:

星币(普通货币)

钻石(高级货币)

优惠券(活动货币)

商城系统:

热购商品(定期刷新)

常驻商品

商品分类(装扮、道具等)

祈愿系统:

概率公示(SSR/SR/R不同概率)

单抽和十连功能

每次祈愿消耗160钻石

玩家系统:

货币余额管理

物品购买与装备

背包管理

交互界面:

简洁的菜单导航

购买确认

装备穿戴

4.星家园
从竹林庭院、童话小镇、梦幻奇缘三种风格中选择一个,创建家园,对家园进行装扮。
在这里插入图片描述
4.星家园
从竹林庭院、童话小镇、梦幻奇缘三种风格中选择一个,创建家园,对家园进行装扮。

import random
from enum import Enum

class HomeStyle(Enum):
    BAMBOO_GARDEN = "竹林庭院"
    FAIRY_TOWN = "童话小镇"
    DREAM_ADVENTURE = "梦幻奇缘"

class Furniture:
    def __init__(self, fid, name, style, price, interact_func=None):
        self.id = fid
        self.name = name
        self.style = style  # 适配的家园风格
        self.price = price
        self.interact_func = interact_func  # 交互功能
    
    def interact(self):
        if self.interact_func:
            return self.interact_func()
        return f"{self.name} 没有特殊交互"

class PlayerHome:
    def __init__(self, style):
        self.style = style
        self.furnitures = []
        self.theme_music = "默认背景音乐"
        self.wallpaper = "默认墙纸"
        self.floor = "默认地板"
        self.level = 1
        self.exp = 0
    
    def add_furniture(self, furniture):
        if furniture.style == self.style or furniture.style == "通用":
            self.furnitures.append(furniture)
            self.add_exp(10)
            return True
        print(f"错误:{furniture.name} 不适合 {self.style.value} 风格!")
        return False
    
    def add_exp(self, amount):
        self.exp += amount
        if self.exp >= self.level * 100:
            self.level_up()
    
    def level_up(self):
        self.level += 1
        self.exp = 0
        print(f"家园升级到 {self.level} 级!解锁了新装饰区域!")
    
    def customize(self, element, new_style):
        setattr(self, element, new_style)
        self.add_exp(5)
    
    def show_home(self):
        print(f"\n=== 我的{self.style.value} ===")
        print(f"等级: {self.level} (经验: {self.exp}/{self.level*100})")
        print(f"背景音乐: {self.theme_music}")
        print(f"墙纸: {self.wallpaper}")
        print(f"地板: {self.floor}")
        print("\n家具列表:")
        for idx, item in enumerate(self.furnitures, 1):
            print(f"{idx}. {item.name}")
    
    def interact_with_furniture(self, index):
        if 0 <= index < len(self.furnitures):
            print(self.furnitures[index].interact())
        else:
            print("无效的家具编号!")

# 家具交互函数
def swing_chair():
    return "摇椅轻轻摇晃,发出吱呀声..."

def bubble_machine():
    return "泡泡机喷出五彩泡泡!"

def bamboo_fountain():
    return "竹筒流水发出清脆的叮咚声"

def fairy_light():
    return "精灵灯闪烁着温暖的光芒"

# 初始化家具库
def initialize_furnitures():
    return [
        Furniture(101, "古风摇椅", HomeStyle.BAMBOO_GARDEN, 500, swing_chair),
        Furniture(102, "竹筒流水", HomeStyle.BAMBOO_GARDEN, 800, bamboo_fountain),
        Furniture(103, "石灯笼", HomeStyle.BAMBOO_GARDEN, 600),
        
        Furniture(201, "精灵泡泡机", HomeStyle.FAIRY_TOWN, 700, bubble_machine),
        Furniture(202, "糖果屋", HomeStyle.FAIRY_TOWN, 1200),
        Furniture(203, "精灵灯", HomeStyle.FAIRY_TOWN, 900, fairy_light),
        
        Furniture(301, "星空吊床", HomeStyle.DREAM_ADVENTURE, 1000),
        Furniture(302, "幻彩旋转木马", HomeStyle.DREAM_ADVENTURE, 1500),
        Furniture(303, "云朵沙发", HomeStyle.DREAM_ADVENTURE, 800),
        
        Furniture(401, "通用地毯", "通用", 300),
        Furniture(402, "小夜灯", "通用", 200)
    ]

# 主游戏循环
def main():
    # 初始化家具库
    all_furnitures = initialize_furnitures()
    
    # 玩家创建家园
    print("===== 元梦之星家园系统 =====")
    print("请选择你的家园风格:")
    for idx, style in enumerate(HomeStyle, 1):
        print(f"{idx}. {style.value}")
    
    style_choice = input("请输入选择(1-3): ")
    try:
        home_style = list(HomeStyle)[int(style_choice)-1]
    except (IndexError, ValueError):
        print("无效选择,默认创建竹林庭院")
        home_style = HomeStyle.BAMBOO_GARDEN
    
    player_home = PlayerHome(home_style)
    print(f"\n恭喜!你的{home_style.value}已创建!")
    
    # 初始赠送家具
    starter_furniture = random.choice([f for f in all_furnitures if f.style == home_style or f.style == "通用"])
    player_home.add_furniture(starter_furniture)
    print(f"获得初始家具: {starter_furniture.name}")
    
    # 商城库存
    shop_stock = [f for f in all_furnitures if f.style == home_style or f.style == "通用"]
    
    # 自定义选项
    style_options = {
        "music": {
            HomeStyle.BAMBOO_GARDEN: ["竹林细语", "古筝韵律", "溪水潺潺"],
            HomeStyle.FAIRY_TOWN: ["童话八音盒", "精灵之歌", "欢乐小镇"],
            HomeStyle.DREAM_ADVENTURE: ["星空幻想", "梦境漫步", "云端旋律"]
        },
        "wallpaper": {
            HomeStyle.BAMBOO_GARDEN: ["墨竹图", "山水画", "素雅宣纸"],
            HomeStyle.FAIRY_TOWN: ["糖果条纹", "蘑菇小屋", "彩虹云朵"],
            HomeStyle.DREAM_ADVENTURE: ["星空图", "极光幻影", "棉花云海"]
        },
        "floor": {
            HomeStyle.BAMBOO_GARDEN: ["青石板", "木地板", "鹅卵石"],
            HomeStyle.FAIRY_TOWN: ["彩虹地毯", "糖果地板", "星光瓷砖"],
            HomeStyle.DREAM_ADVENTURE: ["星空地毯", "云朵地板", "幻彩玻璃"]
        }
    }
    
    while True:
        print("\n===== 家园管理 =====")
        player_home.show_home()
        print("\n1. 购买家具\n2. 更换主题\n3. 与家具互动\n4. 退出")
        
        choice = input("请选择操作: ")
        
        if choice == "1":
            print("\n=== 家具商城 ===")
            for idx, item in enumerate(shop_stock, 1):
                print(f"{idx}. {item.name} - {item.price}星币")
            
            buy_choice = input("请输入要购买的家具编号(0返回): ")
            if buy_choice == "0":
                continue
            try:
                selected_item = shop_stock[int(buy_choice)-1]
                if player_home.add_furniture(selected_item):
                    print(f"{selected_item.name} 已添加到你的家园!")
            except (IndexError, ValueError):
                print("无效选择!")
        
        elif choice == "2":
            print("\n=== 主题定制 ===")
            print("1. 更换背景音乐")
            print("2. 更换墙纸")
            print("3. 更换地板")
            
            sub_choice = input("请选择定制项目: ")
            if sub_choice == "1":
                print("\n可选音乐:")
                for idx, music in enumerate(style_options["music"][home_style], 1):
                    print(f"{idx}. {music}")
                music_choice = input("请选择: ")
                try:
                    new_music = style_options["music"][home_style][int(music_choice)-1]
                    player_home.customize("theme_music", new_music)
                    print(f"背景音乐已更换为 {new_music}")
                except (IndexError, ValueError):
                    print("无效选择!")
            
            elif sub_choice == "2":
                print("\n可选墙纸:")
                for idx, wp in enumerate(style_options["wallpaper"][home_style], 1):
                    print(f"{idx}. {wp}")
                wp_choice = input("请选择: ")
                try:
                    new_wp = style_options["wallpaper"][home_style][int(wp_choice)-1]
                    player_home.customize("wallpaper", new_wp)
                    print(f"墙纸已更换为 {new_wp}")
                except (IndexError, ValueError):
                    print("无效选择!")
            
            elif sub_choice == "3":
                print("\n可选地板:")
                for idx, floor in enumerate(style_options["floor"][home_style], 1):
                    print(f"{idx}. {floor}")
                floor_choice = input("请选择: ")
                try:
                    new_floor = style_options["floor"][home_style][int(floor_choice)-1]
                    player_home.customize("floor", new_floor)
                    print(f"地板已更换为 {new_floor}")
                except (IndexError, ValueError):
                    print("无效选择!")
        
        elif choice == "3":
            if not player_home.furnitures:
                print("你的家园还没有家具,快去购买一些吧!")
                continue
            
            print("\n选择要交互的家具:")
            for idx, item in enumerate(player_home.furnitures, 1):
                print(f"{idx}. {item.name}")
            
            interact_choice = input("请输入家具编号(0返回): ")
            if interact_choice == "0":
                continue
            try:
                player_home.interact_with_furniture(int(interact_choice)-1)
            except (IndexError, ValueError):
                print("无效选择!")
        
        elif choice == "4":
            print("退出家园系统")
            break
        
        else:
            print("无效输入,请重新选择!")

if __name__ == "__main__":
    main()

系统功能说明:
三种家园风格选择:

竹林庭院(古风主题)

童话小镇(梦幻童话主题)

梦幻奇缘(星空幻想主题)

家具系统:

风格专属家具(每种风格有独特家具)

通用家具(适合所有风格)

家具交互功能(部分家具可互动)

家园装扮功能:

更换背景音乐(风格专属音乐)

更换墙纸(风格专属墙纸)

更换地板(风格专属地板)

成长系统:

家园等级(通过布置家具获得经验)

等级提升解锁新区域

交互体验:

与家具互动触发特殊效果

随机获得初始家具

三.特色系统

游戏模式
该作游戏模式由经典模式和娱乐模式两大类型组成,玩家可以选择其中一种进行体验。具体如下:

在这里插入图片描述
1.排位赛
参加排位赛,根据每场的结果计算排位分。
单人排位:得分来自于每一轮个人是否晋级、个人的名次,第一轮未能晋级会扣分。
团队排位:得分来自于每一轮个人的名次、团队是否晋级、团队的名次,第一轮未能晋级的队伍和表现不好的个人会扣分。
排位段位:排位赛一共有9个段位,青铜小萌星、白银祈愿星、黄金幸运星、铂金典藏星、钻石永恒星、至尊梦想星、元梦启明星、元梦领航星、元梦超新星,当段位到达元梦领航星后,将以排位分数进行结算,全服前300名的段位会更新为元梦超新星。
首次晋级奖励:每日前3次在首轮晋级可获得额外分数奖励。

from enum import Enum
import random
from collections import defaultdict

class RankTier(Enum):
    BRONZE = ("青铜小萌星", 0, 100)
    SILVER = ("白银祈愿星", 101, 200)
    GOLD = ("黄金幸运星", 201, 300)
    PLATINUM = ("铂金典藏星", 301, 450)
    DIAMOND = ("钻石永恒星", 451, 600)
    MASTER = ("至尊梦想星", 601, 800)
    STAR = ("元梦启明星", 801, 1000)
    LEADER = ("元梦领航星", 1001, float('inf'))
    SUPERSTAR = ("元梦超新星", None, None)  # 特殊段位
    
    def __init__(self, name, min_score, max_score):
        self.chinese_name = name
        self.min_score = min_score
        self.max_score = max_score

class MatchType(Enum):
    SOLO = "单人排位"
    TEAM = "团队排位"

class Player:
    def __init__(self, name):
        self.name = name
        self.rank_score = 0
        self.tier = RankTier.BRONZE
        self.daily_first_wins = 3  # 每日首次晋级奖励次数
        self.match_history = []
    
    def update_rank(self, score_change):
        self.rank_score += score_change
        
        # 更新段位 (元梦领航星以上特殊处理)
        if self.tier != RankTier.SUPERSTAR:
            for tier in RankTier:
                if tier.min_score is not None and tier.max_score is not None:
                    if tier.min_score <= self.rank_score <= tier.max_score:
                        self.tier = tier
                        break
        
        # 确保分数不低于0
        self.rank_score = max(0, self.rank_score)
    
    def add_match_record(self, match_type, result, score_change):
        self.match_history.append({
            "type": match_type,
            "result": result,
            "score_change": score_change,
            "timestamp": datetime.now()
        })
    
    def get_rank_info(self):
        if self.tier == RankTier.SUPERSTAR:
            return f"{self.tier.chinese_name} (全服前300名)"
        return f"{self.tier.chinese_name} ({self.rank_score}分)"

class RankSystem:
    def __init__(self):
        self.leaderboard = []  # 全服排行榜(元梦领航星以上)
        self.global_rank_threshold = 300  # 超新星名额
    
    def calculate_solo_score(self, player, round_result, final_rank=None):
        """
        单人排位赛得分计算
        :param round_result: "晋级" 或 "淘汰"
        :param final_rank: 最终名次(如果晋级到决赛)
        """
        score_change = 0
        
        # 第一轮结果
        if round_result == "晋级":
            score_change += 20
            # 每日首次晋级奖励
            if player.daily_first_wins > 0:
                score_change += 10
                player.daily_first_wins -= 1
        else:
            score_change -= 15
        
        # 决赛名次奖励
        if final_rank is not None:
            if final_rank == 1:
                score_change += 50
            elif 2 <= final_rank <= 3:
                score_change += 30
            elif 4 <= final_rank <= 6:
                score_change += 15
            else:
                score_change += 5
        
        player.update_rank(score_change)
        player.add_match_record(MatchType.SOLO, 
                              f"晋级到第{final_rank}名" if final_rank else round_result, 
                              score_change)
        return score_change
    
    def calculate_team_score(self, player, team_result, individual_rank, team_rank=None):
        """
        团队排位赛得分计算
        :param team_result: "晋级" 或 "淘汰"
        :param individual_rank: 个人在团队中的表现排名(1-4)
        :param team_rank: 团队最终名次(如果晋级到决赛)
        """
        score_change = 0
        
        # 第一轮团队结果
        if team_result == "晋级":
            score_change += 15
            # 每日首次晋级奖励
            if player.daily_first_wins > 0:
                score_change += 10
                player.daily_first_wins -= 1
        else:
            score_change -= 10
        
        # 个人表现
        if individual_rank == 1:
            score_change += 20
        elif individual_rank == 2:
            score_change += 10
        elif individual_rank == 3:
            score_change += 5
        else:
            score_change -= 5
        
        # 决赛团队名次
        if team_rank is not None:
            if team_rank == 1:
                score_change += 60
            elif 2 <= team_rank <= 3:
                score_change += 40
            elif 4 <= team_rank <= 6:
                score_change += 20
        
        player.update_rank(score_change)
        player.add_match_record(MatchType.TEAM, 
                              f"团队第{team_rank}名(个人第{individual_rank})" if team_rank else team_result, 
                              score_change)
        return score_change
    
    def update_global_rank(self, players):
        """更新全服排行榜(元梦领航星以上玩家)"""
        leader_candidates = [p for p in players if p.tier == RankTier.LEADER or p.tier == RankTier.SUPERSTAR]
        # 按分数降序排序
        sorted_players = sorted(leader_candidates, key=lambda x: x.rank_score, reverse=True)
        
        # 更新超新星段位
        for i, player in enumerate(sorted_players, 1):
            if i <= self.global_rank_threshold:
                player.tier = RankTier.SUPERSTAR
            elif player.tier == RankTier.SUPERSTAR:  # 掉出前300
                player.tier = RankTier.LEADER
        
        self.leaderboard = sorted_players[:self.global_rank_threshold]
    
    def get_global_top(self, n=10):
        """获取全服前n名玩家"""
        return self.leaderboard[:n]

# 模拟比赛帮助函数
def simulate_solo_match(player, rank_system):
    print(f"\n{player.name} 参加单人排位赛...")
    # 模拟第一轮(60%晋级率)
    if random.random() < 0.6:
        print("第一轮晋级成功!")
        # 模拟决赛名次(8人)
        final_rank = random.randint(1, 8)
        print(f"最终获得第{final_rank}名!")
        score_change = rank_system.calculate_solo_score(player, "晋级", final_rank)
    else:
        print("第一轮被淘汰...")
        score_change = rank_system.calculate_solo_score(player, "淘汰")
    
    print(f"排位分变化: {'+' if score_change >=0 else ''}{score_change}")
    print(f"当前段位: {player.get_rank_info()}")

def simulate_team_match(player, rank_system):
    print(f"\n{player.name} 参加团队排位赛...")
    # 模拟第一轮(50%晋级率)
    if random.random() < 0.5:
        print("团队第一轮晋级成功!")
        # 模拟个人表现(4人团队中排名)
        individual_rank = random.randint(1, 4)
        # 模拟决赛团队名次(6队)
        team_rank = random.randint(1, 6)
        print(f"团队最终获得第{team_rank}名,个人表现第{individual_rank}!")
        score_change = rank_system.calculate_team_score(player, "晋级", individual_rank, team_rank)
    else:
        # 模拟个人表现(即使团队淘汰也有个人表现)
        individual_rank = random.randint(1, 4)
        print(f"团队第一轮被淘汰...个人表现第{individual_rank}")
        score_change = rank_system.calculate_team_score(player, "淘汰", individual_rank)
    
    print(f"排位分变化: {'+' if score_change >=0 else ''}{score_change}")
    print(f"当前段位: {player.get_rank_info()}")

# 主程序
if __name__ == "__main__":
    from datetime import datetime, timedelta
    
    rank_system = RankSystem()
    player = Player("元梦玩家")
    
    # 模拟重置每日奖励
    def reset_daily_rewards():
        player.daily_first_wins = 3
        print("\n每日奖励已重置!")
    
    # 设置模拟时间(每小时重置一次)
    last_reset_time = datetime.now()
    
    while True:
        print("\n===== 元梦之星排位赛 =====")
        print(f"玩家: {player.name}")
        print(f"当前段位: {player.get_rank_info()}")
        print(f"今日剩余首次晋级奖励: {player.daily_first_wins}次")
        print("\n1. 参加单人排位\n2. 参加团队排位\n3. 查看比赛记录\n4. 查看全服排行榜\n5. 退出")
        
        # 检查是否需要重置每日奖励
        if datetime.now() - last_reset_time >= timedelta(hours=24):
            reset_daily_rewards()
            last_reset_time = datetime.now()
        
        choice = input("请选择操作: ")
        
        if choice == "1":
            simulate_solo_match(player, rank_system)
        elif choice == "2":
            simulate_team_match(player, rank_system)
        elif choice == "3":
            print("\n=== 近期比赛记录 ===")
            for record in player.match_history[-5:][::-1]:  # 显示最近5场
                print(f"{record['timestamp'].strftime('%m-%d %H:%M')} {record['type'].value}: "
                      f"{record['result']} ({record['score_change']:+}分)")
        elif choice == "4":
            rank_system.update_global_rank([player])  # 模拟更新排行榜
            top_players = rank_system.get_global_top(5)
            print("\n=== 全服排行榜 ===")
            if top_players:
                for i, p in enumerate(top_players, 1):
                    print(f"{i}. {p.name} - {p.get_rank_info()}")
            else:
                print("暂无数据")
        elif choice == "5":
            print("退出排位赛系统")
            break
        else:
            print("无效输入,请重新选择!")

2.休闲赛
单人、双人、四人:根据玩家选择改变,或单人、或组队,进行总共4轮连续的比赛。第1轮比赛为竞速赛,成功冲线的玩家可以晋级到下一轮。第2、3轮可能会有竞速赛、生存赛或积分赛,获胜的玩家可以晋纹到下一轮。第4轮比赛为生存赛,在生存赛中坚持到最后的玩家将成为本场比赛的冠军。

import random
from enum import Enum
from typing import List, Dict

class GameMode(Enum):
    SOLO = "单人"
    DUO = "双人"
    SQUAD = "四人"

class RoundType(Enum):
    RACE = "竞速赛"
    SURVIVAL = "生存赛"
    SCORE = "积分赛"

class Player:
    def __init__(self, name: str):
        self.name = name
        self.advanced = False
        self.score = 0
        self.team = None  # 用于双人和四人模式

class MatchResult:
    def __init__(self, round_num: int, round_type: RoundType, winners: List[Player]):
        self.round_num = round_num
        self.round_type = round_type
        self.winners = winners

class CasualMatch:
    def __init__(self, mode: GameMode, players: List[Player]):
        self.mode = mode
        self.players = players
        self.current_round = 1
        self.total_rounds = 4
        self.results = []
        self.setup_teams()
    
    def setup_teams(self):
        """根据模式分配队伍"""
        if self.mode == GameMode.SOLO:
            for p in self.players:
                p.team = None
        else:
            team_size = 2 if self.mode == GameMode.DUO else 4
            shuffled = random.sample(self.players, len(self.players))
            
            for i in range(0, len(shuffled), team_size):
                team_id = i // team_size + 1
                for j in range(i, min(i+team_size, len(shuffled))):
                    shuffled[j].team = team_id
    
    def get_round_type(self, round_num: int) -> RoundType:
        """确定每轮比赛类型"""
        if round_num == 1:
            return RoundType.RACE  # 第一轮总是竞速赛
        elif round_num == 4:
            return RoundType.SURVIVAL  # 最后一轮总是生存赛
        else:
            return random.choice([RoundType.RACE, RoundType.SCORE, RoundType.SURVIVAL])
    
    def play_round(self, round_type: RoundType) -> MatchResult:
        """进行一轮比赛"""
        participants = [p for p in self.players if p.advanced or self.current_round == 1]
        
        print(f"\n=== 第{self.current_round}{round_type.value} ===")
        
        if round_type == RoundType.RACE:
            winners = self.play_race(participants)
        elif round_type == RoundType.SURVIVAL:
            winners = self.play_survival(participants)
        else:
            winners = self.play_score(participants)
        
        # 更新晋级状态
        for p in participants:
            p.advanced = p in winners
        
        result = MatchResult(self.current_round, round_type, winners)
        self.results.append(result)
        self.current_round += 1
        return result
    
    def play_race(self, participants: List[Player]) -> List[Player]:
        """竞速赛逻辑 - 前50%晋级"""
        num_winners = max(1, len(participants) // 2)
        
        # 模拟比赛结果 - 按随机顺序"冲线"
        shuffled = random.sample(participants, len(participants))
        winners = shuffled[:num_winners]
        
        # 显示结果
        if self.mode == GameMode.SOLO:
            print("竞速赛结果:")
            for i, p in enumerate(shuffled, 1):
                print(f"{i}. {p.name}")
        else:
            print("队伍竞速赛结果:")
            teams = set(p.team for p in shuffled)
            team_ranking = sorted(teams, key=lambda x: shuffled.index(next(p for p in shuffled if p.team == x)))
            
            for i, team in enumerate(team_ranking, 1):
                team_members = [p.name for p in shuffled if p.team == team]
                print(f"{i}. 队伍{team}: {'、'.join(team_members)}")
        
        print(f"晋级玩家: {', '.join(p.name for p in winners)}")
        return winners
    
    def play_survival(self, participants: List[Player]) -> List[Player]:
        """生存赛逻辑 - 最后存活的1人或1队获胜"""
        # 模拟淘汰过程
        remaining = participants.copy()
        
        print("生存赛开始!淘汰顺序:")
        while len(remaining) > 1:
            # 随机淘汰一个玩家或一队
            if self.mode == GameMode.SOLO:
                eliminated = random.choice(remaining)
                remaining.remove(eliminated)
                print(f"- {eliminated.name} 被淘汰")
            else:
                # 淘汰整队
                teams = list(set(p.team for p in remaining))
                eliminated_team = random.choice(teams)
                eliminated = [p for p in remaining if p.team == eliminated_team]
                remaining = [p for p in remaining if p.team != eliminated_team]
                print(f"- 队伍{eliminated_team} ({'、'.join(p.name for p in eliminated)}) 被淘汰")
        
        print(f"冠军: {remaining[0].name}" if self.mode == GameMode.SOLO else 
              f"冠军队伍: 队伍{remaining[0].team} ({'、'.join(p.name for p in remaining)})")
        return remaining
    
    def play_score(self, participants: List[Player]) -> List[Player]:
        """积分赛逻辑 - 积分最高的1人或1队获胜"""
        # 分配随机积分
        for p in participants:
            p.score = random.randint(1, 100)
        
        if self.mode == GameMode.SOLO:
            print("积分赛结果:")
            sorted_players = sorted(participants, key=lambda x: x.score, reverse=True)
            for i, p in enumerate(sorted_players, 1):
                print(f"{i}. {p.name}: {p.score}分")
            return [sorted_players[0]]
        else:
            # 计算队伍总分
            team_scores = {}
            for p in participants:
                if p.team not in team_scores:
                    team_scores[p.team] = 0
                team_scores[p.team] += p.score
            
            print("队伍积分赛结果:")
            sorted_teams = sorted(team_scores.items(), key=lambda x: x[1], reverse=True)
            for i, (team, score) in enumerate(sorted_teams, 1):
                members = [p.name for p in participants if p.team == team]
                print(f"{i}. 队伍{team}: {score}分 ({'、'.join(members)})")
            
            winning_team = sorted_teams[0][0]
            return [p for p in participants if p.team == winning_team]
    
    def play_match(self):
        """进行完整比赛(4轮)"""
        print(f"\n===== 开始{self.mode.value}休闲赛 =====")
        print(f"参赛玩家: {', '.join(p.name for p in self.players)}")
        
        if self.mode != GameMode.SOLO:
            team_info = defaultdict(list)
            for p in self.players:
                team_info[p.team].append(p.name)
            print("\n队伍分配:")
            for team, members in team_info.items():
                print(f"队伍{team}: {'、'.join(members)}")
        
        while self.current_round <= self.total_rounds:
            round_type = self.get_round_type(self.current_round)
            result = self.play_round(round_type)
            
            # 检查是否还有玩家继续比赛
            if len(result.winners) == 0:
                print("没有玩家晋级,比赛结束!")
                break
        
        # 比赛结束奖励
        final_winners = self.results[-1].winners
        print("\n=== 比赛结束 ===")
        if self.mode == GameMode.SOLO:
            print(f"冠军: {final_winners[0].name}")
        else:
            team = final_winners[0].team
            members = [p.name for p in final_winners]
            print(f"冠军队伍: 队伍{team} ({'、'.join(members)})")

# 测试代码
if __name__ == "__main__":
    # 创建玩家
    player_names = ["小明", "小红", "小刚", "小丽", "小强", "小美", "小华", "小静"]
    players = [Player(name) for name in player_names]
    
    while True:
        print("\n===== 元梦之星休闲赛 =====")
        print("1. 单人模式 (8人)")
        print("2. 双人模式 (8人 -> 4队)")
        print("3. 四人模式 (8人 -> 2队)")
        print("4. 退出")
        
        choice = input("请选择游戏模式: ")
        
        if choice == "1":
            match = CasualMatch(GameMode.SOLO, random.sample(players, 8))
            match.play_match()
        elif choice == "2":
            match = CasualMatch(GameMode.DUO, random.sample(players, 8))
            match.play_match()
        elif choice == "3":
            match = CasualMatch(GameMode.SQUAD, random.sample(players, 8))
            match.play_match()
        elif choice == "4":
            print("退出休闲赛系统")
            break
        else:
            print("无效输入,请重新选择!")

3.躲猫猫
躲猫猫由12名玩家共同参与,每局游戏随机分配4名搜捕者和8名伪装者。
伪装者:可使用伪装技能变身为场景中的各种物品,同时也可以使用隐形技能躲避抓捕。玩家为伪装者,游戏结束时,伪装者未全部被淘汰,则伪装者全部获胜。
搜捕者:可使用攻击技能淘汰伪装者,也可使用扫描技能检测附近的伪装者。玩家为搜捕者,游戏结束前淘汰所有伪装者,便可获得胜利。

在这里插入图片描述
在这里插入图片描述

import random
import time

class Player:
    def __init__(self, player_id, is_hunter=False):
        self.player_id = player_id
        self.is_hunter = is_hunter
        self.is_eliminated = False
        self.is_hidden = False if is_hunter else True  # 伪装者初始隐藏
        self.disguised_as = None  # 伪装成的物品
    
    def disguise(self, items):
        """伪装成场景中的物品"""
        if not self.is_hunter and not self.is_eliminated:
            self.disguised_as = random.choice(items)
            return self.disguised_as
        return None
    
    def hide(self):
        """使用隐形技能"""
        if not self.is_hunter and not self.is_eliminated:
            self.is_hidden = True
            return True
        return False
    
    def reveal(self):
        """取消隐形"""
        self.is_hidden = False
    
    def get_status(self):
        status = "猎人" if self.is_hunter else "伪装者"
        if self.is_eliminated:
            return f"玩家{self.player_id}({status}): 已淘汰"
        hidden_str = "隐形中" if self.is_hidden else "可见"
        disguise_str = f"(伪装为{self.disguised_as})" if self.disguised_as else ""
        return f"玩家{self.player_id}({status}): {hidden_str}{disguise_str}"

class HideAndSeekGame:
    def __init__(self, num_players=12):
        self.num_players = num_players
        self.hunters = []
        self.disguises = ["椅子", "桌子", "花瓶", "灯", "画", "书架", "垃圾桶", "雕像", "窗帘", "钟表"]
        self.game_over = False
        self.winner = None
        
        # 初始化玩家
        for i in range(self.num_players):
            is_hunter = i < 4  # 前4个是猎人
            self.hunters.append(Player(i+1, is_hunter) if is_hunter else Player(i+1))
        
        # 分配伪装物品给伪装者
        available_disguises = self.disguises.copy()
        for player in self.hunters[4:]:  # 实际上前4个是猎人,这里应该是8个伪装者
            # 修正:前4个是猎人,所以伪装者是索引4-11
            if player.player_id > 4:
                disguise = random.choice(available_disguises)
                available_disguises.remove(disguise)
                player.disguise([disguise])  # 这里简化了,直接传入单个物品
    
    def start_game(self):
        print("游戏开始!")
        print("4名猎人 vs 8名伪装者")
        print("猎人需要找出并淘汰所有伪装者")
        print("伪装者需要隐藏直到游戏结束\n")
        
        # 初始状态
        self.show_status()
        
        # 游戏回合
        round_num = 1
        while not self.game_over:
            print(f"\n=== 第{round_num}回合 ===")
            
            # 猎人行动
            self.hunter_turn(round_num)
            
            # 检查游戏是否结束
            if all(player.is_eliminated for player in self.hunters if not player.is_hunter) or \
               all(player.is_eliminated for player in self.hunters if player.is_hunter):
                break
            
            # 伪装者行动
            self.disguiser_turn()
            
            # 检查游戏是否结束
            self.check_game_over()
            
            if not self.game_over:
                round_num += 1
                time.sleep(1)  # 模拟回合间隔
    
    def hunter_turn(self, round_num):
        print("\n猎人回合:")
        for hunter in [p for p in self.hunters if p.is_hunter]:
            if hunter.is_eliminated:
                continue
                
            print(f"猎人{hunter.player_id}行动:")
            
            # 扫描技能 - 随机检测3个玩家
            targets = [p for p in self.hunters if not p.is_hunter and not p.is_eliminated and not p.is_hidden]
            if not targets:
                # 如果没有可见的伪装者,随机选择3个
                targets = random.sample([p for p in self.hunters if not p.is_hunter and not p.is_eliminated], 
                                       min(3, len([p for p in self.hunters if not p.is_hunter and not p.is_eliminated])))
            
            # 如果没有可检测的目标,猎人尝试攻击随机伪装者
            if not targets:
                targets = [p for p in self.hunters if not p.is_hunter and not p.is_eliminated]
                if targets:
                    target = random.choice(targets)
                    print(f"  猎人{hunter.player_id}尝试攻击玩家{target.player_id}")
                    if random.random() > 0.5:  # 50%成功率
                        target.is_eliminated = True
                        print(f"  玩家{target.player_id}被淘汰!")
                    else:
                        print(f"  攻击失败!")
            else:
                # 检测技能
                for target in random.sample(targets, min(3, len(targets))):
                    print(f"  猎人{hunter.player_id}扫描玩家{target.player_id}")
                    if target.disguised_as:
                        print(f"  扫描发现玩家{target.player_id}伪装为{target.disguised_as}!")
                        # 可以选择直接攻击或继续观察
                        if random.random() > 0.3:  # 70%概率直接攻击
                            print(f"  猎人{hunter.player_id}攻击玩家{target.player_id}")
                            if random.random() > 0.4:  # 60%成功率
                                target.is_eliminated = True
                                print(f"  玩家{target.player_id}被淘汰!")
                            else:
                                print(f"  攻击失败!")
                    else:
                        print(f"  扫描未发现异常")
            
            # 每回合最多攻击一次
            if random.random() > 0.7 and any(not p.is_hunter and not p.is_eliminated for p in self.hunters):
                # 攻击行动
                targets = [p for p in self.hunters if not p.is_hunter and not p.is_eliminated]
                if targets:
                    target = random.choice(targets)
                    print(f"  猎人{hunter.player_id}直接攻击玩家{target.player_id}")
                    if random.random() > 0.4:  # 60%成功率
                        target.is_eliminated = True
                        print(f"  玩家{target.player_id}被淘汰!")
                    else:
                        print(f"  攻击失败!")
    
    def disguiser_turn(self):
        print("\n伪装者回合:")
        for disguiser in [p for p in self.hunters if not p.is_hunter and not p.is_eliminated]:
            print(f"伪装者{disguiser.player_id}行动:")
            
            # 60%概率使用隐形,40%概率保持当前状态
            if random.random() > 0.4 and not disguiser.is_hidden:
                if disguiser.hide():
                    print("  使用隐形技能")
            elif disguiser.is_hidden and random.random() > 0.7:
                disguiser.reveal()
                print("  取消隐形")
            
            # 30%概率更换伪装物品
            if not disguiser.is_hidden and random.random() > 0.7:
                available_disguises = [d for d in self.disguises if d != disguiser.disguised_as]
                if available_disguises:
                    new_disguise = random.choice(available_disguises)
                    disguiser.disguised_as = new_disguise
                    print(f"  更换伪装为{new_disguise}")
    
    def check_game_over(self):
        # 检查伪装者是否全部被淘汰
        remaining_disguisers = [p for p in self.hunters if not p.is_hunter and not p.is_eliminated]
        if len(remaining_disguisers) == 0:
            self.game_over = True
            self.winner = "猎人"
            print("\n游戏结束! 猎人获胜!")
        
        # 检查猎人是否全部被淘汰(虽然规则说猎人全部被淘汰伪装者获胜,但初始只有4个猎人)
        remaining_hunters = [p for p in self.hunters if p.is_hunter and not p.is_eliminated]
        if len(remaining_hunters) == 0:
            self.game_over = True
            self.winner = "伪装者"
            print("\n游戏结束! 伪装者获胜!")
    
    def show_status(self):
        print("\n当前游戏状态:")
        print("猎人:")
        for hunter in [p for p in self.hunters if p.is_hunter]:
            print(hunter.get_status())
        
        print("\n伪装者:")
        for disguiser in [p for p in self.hunters if not p.is_hunter]:
            print(disguiser.get_status())

# 运行游戏
if __name__ == "__main__":
    game = HideAndSeekGame()
    game.show_status()
    game.start_game()

躲猫猫庭院版:
在这里插入图片描述
在这里插入图片描述

4.武器大师
混战:武器大师混战由6名玩家共同参与,独立阵营,各自为战。
团竞:武器大师团竞由10名玩家共同参与,分成红蓝两个阵营,每个阵营由5名玩家组成。
在这里插入图片描述
在这里插入图片描述

混战模式:

import random
import time

class WeaponMasterPlayer:
    def __init__(self, player_id):
        self.player_id = player_id
        self.health = 100
        self.is_alive = True
        self.weapons = ["剑", "刀", "枪", "弓", "斧", "锤"]
        self.current_weapon = random.choice(self.weapons)
        self.position = (random.randint(0, 10), random.randint(0, 10))
        self.kills = 0
    
    def move(self):
        """随机移动"""
        if not self.is_alive:
            return
        x, y = self.position
        dx, dy = random.choice([(0,1), (0,-1), (1,0), (-1,0), (1,1), (-1,-1)])
        new_x, new_y = x + dx, y + dy
        # 确保不超出边界
        self.position = (max(0, min(10, new_x)), max(0, min(10, new_y)))
    
    def attack(self, other_players):
        """攻击其他玩家"""
        if not self.is_alive:
            return None
        
        # 找出活着的玩家
        alive_players = [p for p in other_players if p.is_alive and p != self]
        if not alive_players:
            return None
            
        # 随机选择一个目标
        target = random.choice(alive_players)
        
        # 计算距离
        distance = abs(self.position[0] - target.position[0]) + abs(self.position[1] - target.position[1])
        
        # 根据武器和距离计算伤害
        base_damage = {
            "剑": 15,
            "刀": 12,
            "枪": 18,
            "弓": 10 if distance > 3 else 25,  # 弓箭远距离伤害高
            "斧": 20,
            "锤": 25
        }.get(self.current_weapon, 10)
        
        # 距离衰减
        if distance > 2:
            damage = max(5, base_damage - (distance - 2) * 3)
        else:
            damage = base_damage
        
        # 攻击
        target.take_damage(damage, self.player_id)
        return {
            "attacker": self.player_id,
            "target": target.player_id,
            "damage": damage,
            "weapon": self.current_weapon,
            "distance": distance
        }
    
    def take_damage(self, damage, attacker_id):
        """受到伤害"""
        if not self.is_alive:
            return
        self.health -= damage
        if self.health <= 0:
            self.is_alive = False
            print(f"玩家{self.player_id}被玩家{attacker_id}击败!")
    
    def change_weapon(self):
        """更换武器"""
        if not self.is_alive:
            return
        old_weapon = self.current_weapon
        new_weapon = random.choice([w for w in self.weapons if w != old_weapon])
        self.current_weapon = new_weapon
        print(f"玩家{self.player_id}{old_weapon}切换到{new_weapon}")
    
    def get_status(self):
        """获取状态信息"""
        return {
            "id": self.player_id,
            "health": self.health,
            "alive": self.is_alive,
            "weapon": self.current_weapon,
            "position": self.position,
            "kills": self.kills
        }

class WeaponMasterBattleRoyale:
    def __init__(self, num_players=6):
        if num_players != 6:
            print("警告: 混战模式设计为6名玩家,当前设置为", num_players)
        self.players = [WeaponMasterPlayer(i+1) for i in range(num_players)]
        self.game_over = False
        self.round_num = 0
    
    def start_game(self):
        print("=== 武器大师混战模式开始 ===")
        print("6名玩家各自为战,最后存活的玩家获胜!")
        print("游戏规则:")
        print("- 每回合可以移动、攻击或更换武器")
        print("- 击败其他玩家获得胜利")
        print(f"初始玩家数量: {len(self.players)}\n")
        
        while not self.game_over:
            self.round_num += 1
            print(f"\n=== 第{self.round_num}回合 ===")
            
            # 玩家行动
            for player in self.players:
                if player.is_alive:
                    action = random.choice(["move", "attack", "change_weapon"])
                    if action == "move":
                        player.move()
                        print(f"玩家{player.player_id}移动到位置{player.position}")
                    elif action == "attack":
                        result = player.attack(self.players)
                        if result:
                            print(f"玩家{result['attacker']}使用{result['weapon']}在距离{result['distance']}处攻击玩家{result['target']}, 造成{result['damage']}点伤害")
                    elif action == "change_weapon":
                        player.change_weapon()
            
            # 检查游戏结束条件
            alive_players = [p for p in self.players if p.is_alive]
            if len(alive_players) <= 1:
                self.game_over = True
                winner = alive_players[0] if alive_players else None
                print("\n游戏结束!")
                if winner:
                    print(f"玩家{winner.player_id}获胜! 击杀数: {winner.kills}")
                else:
                    print("所有玩家都被击败了!")
            
            # 显示当前状态
            self.show_status()
            
            time.sleep(1)  # 暂停一秒
    
    def show_status(self):
        """显示当前游戏状态"""
        alive_players = [p for p in self.players if p.is_alive]
        dead_players = [p for p in self.players if not p.is_alive]
        
        print("\n当前状态:")
        print("存活玩家:")
        for player in alive_players:
            status = player.get_status()
            print(f"玩家{status['id']}: 生命值{status['health']}, 武器{status['weapon']}, 位置{status['position']}, 击杀数{status['kills']}")
        
        if dead_players:
            print("\n已淘汰玩家:")
            for player in dead_players:
                status = player.get_status()
                print(f"玩家{status['id']}: 已淘汰")

# 运行混战模式
if __name__ == "__main__":
    game = WeaponMasterBattleRoyale(6)
    game.start_game()

团竞模式:

import random
import time

class WeaponMasterTeamPlayer:
    def __init__(self, player_id, team):
        self.player_id = player_id
        self.team = team  # "red" 或 "blue"
        self.health = 100
        self.is_alive = True
        self.weapons = ["剑", "刀", "枪", "弓", "斧", "锤"]
        self.current_weapon = random.choice(self.weapons)
        self.position = (random.randint(0, 9), random.randint(0, 9))
        self.kills = 0
    
    def move(self):
        """随机移动"""
        if not self.is_alive:
            return
        x, y = self.position
        dx, dy = random.choice([(0,1), (0,-1), (1,0), (-1,0), (1,1), (-1,-1)])
        new_x, new_y = x + dx, y + dy
        
        # 确保不超出边界
        new_x = max(0, min(9, new_x))
        new_y = max(0, min(9, new_y))
        
        # 确保不会移动到己方基地(角落)
        if (self.team == "red" and (new_x < 2 and new_y < 2)) or \
           (self.team == "blue" and (new_x > 7 and new_y > 7)):
            return
            
        self.position = (new_x, new_y)
    
    def attack(self, other_players):
        """攻击其他玩家"""
        if not self.is_alive:
            return None
        
        # 找出敌方玩家
        enemies = [p for p in other_players if p.is_alive and p.team != self.team]
        if not enemies:
            return None
            
        # 随机选择一个目标
        target = random.choice(enemies)
        
        # 计算距离
        distance = abs(self.position[0] - target.position[0]) + abs(self.position[1] - target.position[1])
        
        # 根据武器和距离计算伤害
        base_damage = {
            "剑": 15,
            "刀": 12,
            "枪": 18,
            "弓": 10 if distance > 3 else 25,  # 弓箭远距离伤害高
            "斧": 20,
            "锤": 25
        }.get(self.current_weapon, 10)
        
        # 距离衰减
        if distance > 2:
            damage = max(5, base_damage - (distance - 2) * 3)
        else:
            damage = base_damage
        
        # 攻击
        target.take_damage(damage, self.player_id)
        return {
            "attacker": self.player_id,
            "attacker_team": self.team,
            "target": target.player_id,
            "target_team": target.team,
            "damage": damage,
            "weapon": self.current_weapon,
            "distance": distance
        }
    
    def take_damage(self, damage, attacker_id):
        """受到伤害"""
        if not self.is_alive:
            return
        self.health -= damage
        if self.health <= 0:
            self.is_alive = False
            print(f"玩家{self.player_id}({self.team})被玩家{attacker_id}({'red' if attacker_id in [p.player_id for p in self.get_red_players()] else 'blue'})击败!")
    
    def change_weapon(self):
        """更换武器"""
        if not self.is_alive:
            return
        old_weapon = self.current_weapon
        new_weapon = random.choice([w for w in self.weapons if w != old_weapon])
        self.current_weapon = new_weapon
        print(f"玩家{self.player_id}({self.team})从{old_weapon}切换到{new_weapon}")
    
    def get_status(self):
        """获取状态信息"""
        return {
            "id": self.player_id,
            "team": self.team,
            "health": self.health,
            "alive": self.is_alive,
            "weapon": self.current_weapon,
            "position": self.position,
            "kills": self.kills
        }
    
    @staticmethod
    def get_red_players(players):
        return [p for p in players if p.team == "red"]
    
    @staticmethod
    def get_blue_players(players):
        return [p for p in players if p.team == "blue"]

class WeaponMasterTeamBattle:
    def __init__(self, num_players=10):
        if num_players != 10:
            print("警告: 团竞模式设计为10名玩家,当前设置为", num_players)
        # 5名红队,5名蓝队
        self.players = [WeaponMasterTeamPlayer(i+1, "red") for i in range(5)] + \
                       [WeaponMasterTeamPlayer(i+6, "blue") for i in range(5)]
        self.game_over = False
        self.round_num = 0
    
    def start_game(self):
        print("=== 武器大师团竞模式开始 ===")
        print("10名玩家分成两队(红队和蓝队),每队5人")
        print("游戏规则:")
        print("- 每回合可以移动、攻击或更换武器")
        print("- 击败敌方玩家获得胜利")
        print("- 先消灭对方所有队员的队伍获胜!")
        print(f"初始队伍: 红队5人, 蓝队5人\n")
        
        while not self.game_over:
            self.round_num += 1
            print(f"\n=== 第{self.round_num}回合 ===")
            
            # 玩家行动
            for player in self.players:
                if player.is_alive:
                    action = random.choice(["move", "attack", "change_weapon"])
                    if action == "move":
                        player.move()
                        print(f"玩家{player.player_id}({player.team})移动到位置{player.position}")
                    elif action == "attack":
                        result = player.attack(self.players)
                        if result:
                            print(f"玩家{result['attacker']}({result['attacker_team']})使用{result['weapon']}在距离{result['distance']}处攻击玩家{result['target']}({result['target_team']}), 造成{result['damage']}点伤害")
                    elif action == "change_weapon":
                        player.change_weapon()
            
            # 检查游戏结束条件
            red_players = WeaponMasterTeamPlayer.get_red_players(self.players)
            blue_players = WeaponMasterTeamPlayer.get_blue_players(self.players)
            
            alive_red = [p for p in red_players if p.is_alive]
            alive_blue = [p for p in blue_players if p.is_alive]
            
            if len(alive_red) == 0:
                self.game_over = True
                print("\n游戏结束! 蓝队获胜!")
            elif len(alive_blue) == 0:
                self.game_over = True
                print("\n游戏结束! 红队获胜!")
            
            # 显示当前状态
            self.show_status()
            
            time.sleep(1)  # 暂停一秒
    
    def show_status(self):
        """显示当前游戏状态"""
        red_players = WeaponMasterTeamPlayer.get_red_players(self.players)
        blue_players = WeaponMasterTeamPlayer.get_blue_players(self.players)
        
        alive_red = [p for p in red_players if p.is_alive]
        alive_blue = [p for p in blue_players if p.is_alive]
        dead_red = [p for p in red_players if not p.is_alive]
        dead_blue = [p for p in blue_players if not p.is_alive]
        
        print("\n当前状态:")
        print(f"红队({len(alive_red)}/{len(red_players)}):")
        for player in alive_red:
            status = player.get_status()
            print(f"玩家{status['id']}: 生命值{status['health']}, 武器{status['weapon']}, 位置{status['position']}, 击杀数{status['kills']}")
        
        if dead_red:
            print("\n红队已淘汰玩家:")
            for player in dead_red:
                status = player.get_status()
                print(f"玩家{status['id']}: 已淘汰")
        
        print(f"\n蓝队({len(alive_blue)}/{len(blue_players)}):")
        for player in alive_blue:
            status = player.get_status()
            print(f"玩家{status['id']}: 生命值{status['health']}, 武器{status['weapon']}, 位置{status['position']}, 击杀数{status['kills']}")
        
        if dead_blue:
            print("\n蓝队已淘汰玩家:")
            for player in dead_blue:
                status = player.get_status()
                print(f"玩家{status['id']}: 已淘汰")

# 运行团竞模式
if __name__ == "__main__":
    game = WeaponMasterTeamBattle(10)
    game.start_game()

5.谁是狼人
谁是狼人由8名玩家或10名玩家共同参与。
8人模式:每局游戏会随机分配2名狼人和6名平民。
10人模式:每局游戏会随机分配2名狼人、2名中立和6名平民。
部分玩家会拥有特殊的职业身份。平民玩家需要寻找线索揪出狼人,狼人玩家需要伪装自己并伺机淘汰平民,而中玩家则需要巧妙的达成胜利条件。

在这里插入图片描述

在这里插入图片描述

import random
import time
from enum import Enum

class Role(Enum):
    VILLAGER = "平民"
    WEREWOLF = "狼人"
    NEUTRAL = "中立"  # 中立角色(如赏金猎人、捣蛋鬼等)
    DETECTIVE = "侦探"  # 特殊职业(可选)
    HUNTER = "猎人"     # 特殊职业(可选)

class WhoIsWerewolfGame:
    def __init__(self, num_players=8, game_mode="standard"):
        """
        初始化游戏
        :param num_players: 玩家数量(8或10)
        :param game_mode: 游戏模式("standard"标准模式或"custom"自定义模式)
        """
        if num_players not in [8, 10]:
            raise ValueError("玩家数量必须是8或10")
            
        self.num_players = num_players
        self.game_mode = game_mode
        self.players = []
        self.dead_players = []
        self.game_over = False
        self.winner = None
        self.night_phase = True
        self.day_count = 0
        
        # 定义角色分配
        if num_players == 8:
            self.role_distribution = {
                Role.WEREWOLF: 2,
                Role.VILLAGER: 6
            }
        else:  # 10人模式
            self.role_distribution = {
                Role.WEREWOLF: 2,
                Role.NEUTRAL: 2,
                Role.VILLAGER: 6
            }
        
        # 如果是自定义模式,可以在这里调整角色分布
        if game_mode == "custom":
            # 示例: 10人模式自定义角色分布
            # self.role_distribution = {
            #     Role.WEREWOLF: 3,
            #     Role.NEUTRAL: 1,
            #     Role.VILLAGER: 6
            # }
            pass
        
        self.initialize_game()
    
    def initialize_game(self):
        """初始化游戏,分配角色"""
        # 创建玩家
        for i in range(1, self.num_players + 1):
            self.players.append({
                "id": i,
                "role": None,
                "alive": True,
                "vote_target": None,
                "action_target": None,
                "special_action_used": False
            })
        
        # 分配角色
        roles = []
        for role, count in self.role_distribution.items():
            roles.extend([role] * count)
        
        # 如果有特殊职业需求,可以在这里添加
        if self.num_players == 10 and self.game_mode == "standard":
            # 在10人标准模式中,中立角色可以具体化为赏金猎人(1)和捣蛋鬼(1)
            roles.remove(Role.NEUTRAL)
            roles.append(Role.HUNTER)  # 赏金猎人
            roles.append(Role.DETECTIVE)  # 侦探
            random.shuffle(roles)
        
        random.shuffle(roles)
        
        # 分配角色给玩家
        for i, player in enumerate(self.players):
            if i < len(roles):
                player["role"] = roles[i]
            else:
                player["role"] = Role.VILLAGER
        
        # 打印初始角色分配(仅用于调试)
        print("初始角色分配(仅用于调试):")
        for player in self.players:
            print(f"玩家{player['id']}: {player['role'].value if player['role'] else '未知'}")
        print("\n" + "="*50 + "\n")
    
    def start_game(self):
        """开始游戏"""
        print(f"=== 元梦之星'谁是狼人' - {self.num_players}人模式 ===")
        print(f"游戏开始! 玩家数量: {self.num_players}")
        
        if self.num_players == 8:
            print("角色分布: 2狼人, 6平民")
        else:
            print("角色分布: 2狼人, 2中立, 6平民")
        
        self.night_phase = True
        self.day_count = 0
        
        while not self.game_over:
            self.day_count += 1
            if self.night_phase:
                print(f"\n=== 第{self.day_count}天夜晚 ===")
                self.night_phase_actions()
            else:
                print(f"\n=== 第{self.day_count}天白天 ===")
                self.day_phase_actions()
            
            self.check_game_over()
            
            if not self.game_over:
                self.night_phase = not self.night_phase
    
    def night_phase_actions(self):
        """夜晚阶段行动"""
        print("夜晚降临,玩家们开始行动...")
        
        # 狼人行动
        werewolves = [p for p in self.players if p["alive"] and p["role"] == Role.WEREWOLF]
        if werewolves:
            print(f"狼人(玩家{', 玩家'.join(str(w['id']) for w in werewolves)})睁开了眼睛...")
            
            # 狼人选择目标
            targets = [p for p in self.players if p["alive"] and p["id"] not in [w["id"] for w in werewolves]]
            if targets:
                for werewolf in werewolves:
                    # 简化版: 狼人随机选择一个目标
                    target = random.choice(targets)
                    werewolf["action_target"] = target["id"]
                    print(f"狼人玩家{werewolf['id']}选择了玩家{target['id']}作为目标")
                
                # 执行狼人杀害
                for werewolf in werewolves:
                    target_id = werewolf["action_target"]
                    target_player = next(p for p in self.players if p["id"] == target_id)
                    
                    # 检查是否有猎人保护(简化版不实现保护机制)
                    if random.random() > 0.3:  # 70%成功率
                        target_player["alive"] = False
                        print(f"狼人玩家{werewolf['id']}成功杀害了玩家{target_id}")
                    else:
                        print(f"狼人玩家{werewolf['id']}的杀害行动失败了!")
            
            # 重置狼人行动目标
            for werewolf in werewolves:
                werewolf["action_target"] = None
        
        # 中立角色行动(赏金猎人/捣蛋鬼)
        neutrals = [p for p in self.players if p["alive"] and p["role"] in [Role.HUNTER, Role.DETECTIVE]]
        for neutral in neutrals:
            if neutral["role"] == Role.HUNTER:  # 赏金猎人
                print(f"赏金猎人玩家{neutral['id']}在夜间观察...")
                # 简化版: 赏金猎人不做行动,只在被杀时触发技能
            elif neutral["role"] == Role.DETECTIVE:  # 侦探
                print(f"侦探玩家{neutral['id']}开始调查...")
                # 侦探调查一名玩家
                alive_players = [p for p in self.players if p["alive"] and p["id"] != neutral["id"]]
                if alive_players:
                    target = random.choice(alive_players)
                    # 简化版: 50%概率正确识别
                    is_werewolf = (target["role"] == Role.WEREWOLF)
                    correct = random.random() > 0.5  # 50%准确率
                    result = "狼人" if (correct and is_werewolf) or (not correct and not is_werewolf) else "平民"
                    print(f"侦探玩家{neutral['id']}调查玩家{target['id']}, 认为是{result}(实际: {target['role'].value})")
                    # 记录调查结果(实际游戏中可以用于策略)
        
        # 特殊角色行动(如捣蛋鬼)
        # 简化版不实现所有特殊角色
        
        # 重置所有行动目标
        for player in self.players:
            player["action_target"] = None
    
    def day_phase_actions(self):
        """白天阶段行动"""
        print("\n黎明到来,玩家们开始讨论...")
        
        # 显示存活玩家
        alive_players = [p for p in self.players if p["alive"]]
        print("\n当前存活玩家:")
        for player in alive_players:
            role = player["role"].value if player["role"] else "未知"
            status = "存活"
            print(f"玩家{player['id']}: {role}, {status}")
        
        # 投票阶段
        print("\n开始投票!")
        votes = {p["id"]: [] for p in alive_players}  # 记录每个玩家获得的票数
        
        # 每个玩家投票(简化版: 随机投票)
        for voter in alive_players:
            # 获取可选的投票目标(排除自己)
            targets = [p["id"] for p in alive_players if p["id"] != voter["id"]]
            if targets:
                # 随机选择一个目标投票
                target = random.choice(targets)
                voter["vote_target"] = target
                votes[target].append(voter["id"])
                print(f"玩家{voter['id']}投票给玩家{target}")
            else:
                voter["vote_target"] = None
        
        # 统计票数
        vote_results = []
        for player_id, voters in votes.items():
            if voters:
                vote_results.append({
                    "player_id": player_id,
                    "votes": len(voters),
                    "voters": voters
                })
        
        # 按票数排序
        vote_results.sort(key=lambda x: x["votes"], reverse=True)
        
        # 执行处决(如果有玩家获得票数)
        if vote_results and vote_results[0]["votes"] > 0:
            # 可能有多个玩家票数相同且最高
            max_votes = vote_results[0]["votes"]
            eliminated_candidates = [vr["player_id"] for vr in vote_results if vr["votes"] == max_votes]
            
            # 如果有多个候选人,随机选择一个处决
            if len(eliminated_candidates) > 1:
                eliminated_player_id = random.choice(eliminated_candidates)
            else:
                eliminated_player_id = eliminated_candidates[0]
            
            # 找到被处决的玩家
            eliminated_player = next(p for p in self.players if p["id"] == eliminated_player_id)
            eliminated_player["alive"] = False
            self.dead_players.append(eliminated_player)
            
            print(f"\n玩家{eliminated_player_id}被投票出局! ({max_votes}票)")
            
            # 如果是狼人被处决,显示身份
            if eliminated_player["role"] == Role.WEREWOLF:
                print(f"处决的是狼人! 平民获得优势!")
            elif eliminated_player["role"] in [Role.HUNTER, Role.DETECTIVE]:
                print(f"处决的是{eliminated_player['role'].value}! 失去重要角色!")
            else:
                print("处决的是平民...")
        else:
            print("\n没有玩家被处决!")
        
        # 重置投票目标
        for player in self.players:
            player["vote_target"] = None
        
        # 夜晚降临
        self.night_phase = True
    
    def check_game_over(self):
        """检查游戏是否结束"""
        alive_players = [p for p in self.players if p["alive"]]
        alive_werewolves = [p for p in alive_players if p["role"] == Role.WEREWOLF]
        alive_neutrals = [p for p in alive_players if p["role"] in [Role.HUNTER, Role.DETECTIVE]]
        alive_villagers = [p for p in alive_players if p["role"] == Role.VILLAGER]
        
        # 狼人胜利条件: 所有平民和中立角色被消灭
        if not alive_villagers and (not alive_neutrals or len(alive_neutrals) < 2):  # 至少需要保留一个中立角色用于判断
            self.game_over = True
            self.winner = "狼人"
            print("\n游戏结束! 狼人获胜!")
            return
        
        # 平民胜利条件: 所有狼人被消灭
        if not alive_werewolves:
            self.game_over = True
            self.winner = "平民"
            print("\n游戏结束! 平民获胜!")
            return
        
        # 中立角色特殊胜利(如赏金猎人杀死狼人)
        if alive_neutrals:
            for player in alive_neutrals:
                if player["role"] == Role.HUNTER and player["special_action_used"] == "kill_werewolf":
                    # 假设赏金猎人在被杀时杀了狼人
                    self.game_over = True
                    self.winner = "中立(赏金猎人)"
                    print("\n游戏结束! 赏金猎人获胜!")
                    return
        
        # 如果游戏未结束,继续下一轮
        if self.day_count >= 10:  # 防止无限循环
            self.game_over = True
            # 根据存活角色决定胜负
            alive_players = [p for p in self.players if p["alive"]]
            alive_werewolves = [p for p in alive_players if p["role"] == Role.WEREWOLF]
            if len(alive_werewolves) > len(alive_players) / 2:
                self.winner = "狼人"
            else:
                self.winner = "平民"
            print("\n游戏达到最大回合数,结束!")
            if self.winner == "狼人":
                print("狼人获胜!")
            else:
                print("平民获胜!")

# 运行游戏
if __name__ == "__main__":
    print("=== 元梦之星'谁是狼人'游戏 ===")
    mode = input("选择模式(8人/10人): ").strip()
    num_players = 8 if mode == "8人" else 10
    
    game = WhoIsWerewolfGame(num_players=num_players)
    game.start_game()

游戏功能说明
​​两种游戏模式​​:
8人模式: 2狼人, 6平民
10人模式: 2狼人, 2中立(赏金猎人+侦探), 6平民
​​角色系统​​:
平民: 需要找出并投票淘汰狼人
狼人: 夜晚杀害平民,伪装成平民
赏金猎人(中立): 被杀时可以杀死一名玩家
侦探(中立): 可以调查玩家身份
​​游戏流程​​:
夜晚阶段: 狼人行动、特殊角色行动
白天阶段: 讨论、投票处决一名玩家
循环直到游戏结束条件满足
​​胜利条件​​:
狼人胜利: 所有平民和中立角色被消灭
平民胜利: 所有狼人被消灭
特殊胜利: 如赏金猎人成功杀死狼人

谁是狼人:

在这里插入图片描述
在这里插入图片描述

6.突围梦幻岛
单人、双人、四人:突围梦幻岛由32名玩家共同参与,进行总共7-10分钟的友谊赛。玩家可通过在场景内搜索道具、武器、投掷物、补给来与其他玩家或团队进行比拼。比赛中在固定时间会刷出强力的特殊武器,拥有特殊道具可具有较强的对抗能力。即使被击倒,在一定时间内还有返场机会,重回对局进行比赛,比拼到最后的玩家或团队获得最终胜利。

在这里插入图片描述

import random
import time
from enum import Enum
from collections import defaultdict

class GameMode(Enum):
    SINGLE = "单人"
    DOUBLE = "双人"
    FOUR = "四人"

class Player:
    def __init__(self, player_id, team_id=None):
        self.player_id = player_id
        self.team_id = team_id  # 对于单人模式为None,双人/四人模式为队伍ID
        self.health = 100
        self.is_alive = True
        self.is_downed = False
        self.down_time = 0
        self.respawn_time = 0
        self.weapons = []  # 当前持有的武器
        self.inventory = []  # 道具和补给
        self.score = 0
        self.kills = 0
        self.deaths = 0
        self.special_equipped = None  # 当前装备的特殊武器
        
    def take_damage(self, damage):
        """受到伤害"""
        if not self.is_alive:
            return False
            
        if self.is_downed:
            return False  # 倒地状态不能被攻击
            
        self.health -= damage
        if self.health <= 0:
            self.health = 0
            self.is_alive = False
            self.is_downed = True
            self.down_time = time.time()
            print(f"玩家{self.player_id}({self.get_team_name()})被击倒! 剩余复活时间: {self.get_down_time_left():.1f}秒")
            return True
        return False
        
    def get_down_time_left(self):
        """获取剩余复活时间"""
        if not self.is_downed:
            return 0
        return max(0, 5 - (time.time() - self.down_time))  # 倒地5秒后复活
        
    def respawn(self):
        """复活"""
        if self.is_downed and time.time() - self.down_time >= 5:
            self.is_alive = True
            self.is_downed = False
            self.health = 50  # 复活后血量减半
            self.respawn_time = time.time()
            print(f"玩家{self.player_id}({self.get_team_name()})已复活! 当前血量: {self.health}")
            return True
        return False
        
    def equip_special(self, special_weapon):
        """装备特殊武器"""
        if special_weapon in self.inventory:
            self.special_equipped = special_weapon
            self.inventory.remove(special_weapon)
            print(f"玩家{self.player_id}装备了特殊武器: {special_weapon}")
            return True
        return False
        
    def use_special(self, target=None):
        """使用特殊武器"""
        if not self.special_equipped:
            return False
            
        success = False
        if self.special_equipped == "火箭筒":
            # 火箭筒造成高额伤害
            damage = 80
            if target and target.is_alive and not target.is_downed:
                success = True
                target.take_damage(damage)
                print(f"玩家{self.player_id}使用火箭筒对玩家{target.player_id}造成{damage}点伤害!")
        elif self.special_equipped == "医疗包":
            # 医疗包恢复生命值
            heal = 40
            if self.health + heal > 100:
                self.health = 100
            else:
                self.health += heal
            success = True
            print(f"玩家{self.player_id}使用医疗包恢复{heal}点生命值! 当前血量: {self.health}")
        elif self.special_equipped == "穿甲弹":
            # 穿甲弹增加下一次攻击伤害
            self.inventory.append("穿甲效果")  # 标记下一次攻击有穿甲效果
            success = True
            print(f"玩家{self.player_id}装备了穿甲弹!")
            
        if success:
            self.special_equipped = None  # 使用后特殊武器消失
        return success
        
    def add_item(self, item):
        """添加物品到背包"""
        if item in ["火箭筒", "医疗包", "穿甲弹"]:  # 特殊武器
            if item not in self.inventory and item not in [w for w in self.weapons if isinstance(w, str) and w.endswith("火箭筒")]:
                self.inventory.append(item)
        else:  # 普通武器或道具
            self.inventory.append(item)
            
    def search_loot(self, loot_pool):
        """搜索战利品"""
        if not self.is_alive:
            return None
            
        found_items = random.sample(loot_pool, min(2, len(loot_pool)))  # 最多找到2个物品
        for item in found_items:
            loot_pool.remove(item)
            self.add_item(item)
            print(f"玩家{self.player_id}({self.get_team_name()})找到了物品: {item}")
            
        return found_items
        
    def attack(self, target):
        """攻击目标"""
        if not self.is_alive or self.is_downed:
            return False
            
        if target.is_downed:
            return False
            
        # 计算伤害
        damage = random.randint(10, 30)
        
        # 检查是否有穿甲效果
        if "穿甲效果" in self.inventory:
            damage = int(damage * 1.5)
            print(f"穿甲效果触发! 伤害提升至{damage}")
            self.inventory.remove("穿甲效果")
            
        # 检查是否有火箭筒
        if self.special_equipped == "火箭筒":
            damage = 80
            self.use_special(target)
            return True
            
        # 普通攻击
        if target.take_damage(damage):
            self.kills += 1
            target.deaths += 1
            print(f"玩家{self.player_id}({self.get_team_name()})攻击玩家{target.player_id}({target.get_team_name()})造成{damage}点伤害!")
            return True
        else:
            print(f"玩家{self.player_id}({self.get_team_name()})攻击玩家{target.player_id}({target.get_team_name()})但未击倒!")
            return False
            
    def get_team_name(self):
        """获取队伍名称"""
        if self.team_id is None:
            return "单人"
        elif self.team_id == 1:
            return "红队"
        elif self.team_id == 2:
            return "蓝队"
        elif self.team_id == 3:
            return "绿队"
        elif self.team_id == 4:
            return "黄队"
        return "未知队伍"
        
    def get_status(self):
        """获取玩家状态"""
        status = {
            "id": self.player_id,
            "team": self.get_team_name(),
            "health": self.health,
            "alive": self.is_alive,
            "downed": self.is_downed,
            "score": self.score,
            "kills": self.kills,
            "deaths": self.deaths,
            "special": self.special_equipped,
            "inventory": self.inventory
        }
        return status
        
    def __str__(self):
        return f"玩家{self.player_id}({self.get_team_name()}) - 血量:{self.health}{'(倒地)' if self.is_downed else ''}"

class BattleRoyaleGame:
    def __init__(self, game_mode=GameMode.SINGLE):
        """
        初始化游戏
        :param game_mode: 游戏模式(SINGLE, DOUBLE, FOUR)
        """
        self.game_mode = game_mode
        self.players = []
        self.loot_pool = self.initialize_loot_pool()
        self.game_over = False
        self.round_time = 7 * 60  # 7分钟,单位秒
        self.start_time = None
        self.special_weapon_spawn_time = 0
        self.special_weapon_active = False
        self.special_weapon_type = None
        
        # 根据游戏模式创建玩家
        self.initialize_players()
        
    def initialize_loot_pool(self):
        """初始化战利品池"""
        weapons = [
            "手枪", "步枪", "霰弹枪", "冲锋枪", "狙击枪",
            "火箭筒", "榴弹发射器", "机枪", "弓箭", "双刀"
        ]
        
        specials = ["火箭筒", "医疗包", "穿甲弹", "隐身药剂", "加速药剂"]
        
        throwables = ["手榴弹", "烟雾弹", "闪光弹"]
        
        consumables = ["急救包", "能量饮料", "护甲", "止痛药"]
        
        # 基础武器(数量较多)
        loot_pool = weapons * 15
        
        # 特殊武器(数量较少)
        loot_pool.extend(specials * 5)
        
        # 投掷物
        loot_pool.extend(throwables * 20)
        
        # 消耗品
        loot_pool.extend(consumables * 30)
        
        # 随机打乱
        random.shuffle(loot_pool)
        
        return loot_pool
        
    def initialize_players(self):
        """初始化玩家"""
        player_ids = list(range(1, 33))  # 32名玩家
        
        if self.game_mode == GameMode.SINGLE:
            # 单人模式: 32名单人玩家
            for i, player_id in enumerate(player_ids):
                self.players.append(Player(player_id))
                
        elif self.game_mode == GameMode.DOUBLE:
            # 双人模式: 16支队伍,每队2人
            for i in range(1, 17):
                team_id = 1 if i <= 8 else 2  # 前8队红队,后8队蓝队
                if i > 8:
                    team_id = 2 if i <= 12 else 3  # 调整为4个队伍
                if i > 12:
                    team_id = 3 if i <= 14 else 4
                if i > 14:
                    team_id = 4
                    
                # 每队2人
                self.players.append(Player(player_ids[2*i-2], team_id))
                self.players.append(Player(player_ids[2*i-1], team_id))
                
        elif self.game_mode == GameMode.FOUR:
            # 四人模式: 8支队伍,每队4人
            for i in range(1, 9):
                team_id = i
                # 每队4人
                start_idx = (i-1)*4 + 1
                for j in range(4):
                    player_id = 4*(i-1) + j + 1
                    self.players.append(Player(player_id, team_id))
        
        # 确保玩家数量正确
        if self.game_mode == GameMode.SINGLE:
            assert len(self.players) == 32
        elif self.game_mode == GameMode.DOUBLE:
            assert len(self.players) == 32  # 16队x2人
        elif self.game_mode == GameMode.FOUR:
            assert len(self.players) == 32  # 8队x4人
            
    def start_game(self):
        """开始游戏"""
        print(f"=== 元梦之星'突围梦幻岛' - {self.game_mode.value}模式 ===")
        if self.game_mode == GameMode.SINGLE:
            print("32名玩家参与的单人竞技!")
        elif self.game_mode == GameMode.DOUBLE:
            print("16支队伍(每队2人)的双人竞技!")
        elif self.game_mode == GameMode.FOUR:
            print("8支队伍(每队4人)的四人竞技!")
            
        print(f"游戏时长: {7}分钟")
        print("目标: 成为最后存活的玩家或队伍!")
        
        self.start_time = time.time()
        self.spawn_special_weapon()  # 初始生成特殊武器
        
        # 游戏主循环
        while not self.game_over:
            current_time = time.time()
            elapsed_time = current_time - self.start_time
            
            # 检查游戏时间
            if elapsed_time >= self.round_time:
                self.end_game_by_time()
                break
                
            # 检查特殊武器刷新
            if not self.special_weapon_active and elapsed_time - self.special_weapon_spawn_time > 90:  # 90秒刷新一次
                self.spawn_special_weapon()
                
            # 玩家行动(简化版,随机行动)
            self.player_actions(elapsed_time)
            
            # 检查复活倒地玩家
            self.check_respawn()
            
            # 检查游戏结束条件
            self.check_game_over()
            
            # 每秒循环一次
            time.sleep(1)
            
        # 游戏结束,显示结果
        self.show_results()
        
    def spawn_special_weapon(self):
        """生成特殊武器"""
        if len(self.loot_pool) == 0:
            return
            
        # 特殊武器列表
        special_weapons = ["火箭筒", "医疗包", "穿甲弹"]
        
        # 随机选择一个特殊武器
        weapon = random.choice(special_weapons)
        
        # 从战利品池中随机选择一个位置(或直接生成在随机位置)
        if self.loot_pool and random.random() > 0.3:  # 70%概率从现有战利品中替换
            index = random.randint(0, len(self.loot_pool)-1)
            old_item = self.loot_pool[index]
            self.loot_pool[index] = weapon
            print(f"特殊武器{weapon}在战利品刷新点生成! (替换了{old_item})")
        else:  # 30%概率直接在随机位置生成
            self.special_weapon_type = weapon
            self.special_weapon_active = True
            self.special_weapon_spawn_time = time.time()
            print(f"特殊武器{weapon}在地图随机位置生成! 持续时间: 60秒")
            
        # 设置下次刷新时间
        self.special_weapon_spawn_time = time.time()
        
    def player_actions(self, elapsed_time):
        """模拟玩家行动"""
        # 根据游戏模式分组玩家
        if self.game_mode == GameMode.SINGLE:
            players_by_team = {None: self.players}
        elif self.game_mode == GameMode.DOUBLE:
            players_by_team = defaultdict(list)
            for player in self.players:
                players_by_team[player.team_id].append(player)
        elif self.game_mode == GameMode.FOUR:
            players_by_team = defaultdict(list)
            for player in self.players:
                players_by_team[player.team_id].append(player)
                
        # 每个玩家随机行动
        for team_id, players in players_by_team.items():
            for player in players:
                if not player.is_alive:
                    continue
                    
                # 随机决定行动
                action = random.choice(["搜索", "攻击", "移动", "使用物品"])
                
                if action == "搜索":
                    # 搜索附近的战利品
                    if self.loot_pool and random.random() > 0.7:  # 30%概率找到战利品
                        found_items = player.search_loot(self.loot_pool)
                        if found_items:
                            # 检查是否找到特殊武器
                            for item in found_items:
                                if item == self.special_weapon_type and self.special_weapon_active:
                                    player.equip_special(item) if item in ["火箭筒", "医疗包", "穿甲弹"] else None
                                    self.special_weapon_active = False
                                    print(f"玩家{player.player_id}找到了地图上的特殊武器{item}!")
                                    
                elif action == "攻击":
                    # 寻找附近敌人攻击
                    alive_players = [p for p in self.players if p.is_alive and p != player]
                    if alive_players:
                        target = random.choice(alive_players)
                        player.attack(target)
                        
                elif action == "移动":
                    # 移动到随机位置(简化处理)
                    pass
                    
                elif action == "使用物品":
                    # 使用背包中的物品
                    if player.inventory:
                        item = random.choice(player.inventory)
                        if item in ["火箭筒", "医疗包", "穿甲弹"] and not player.special_equipped:
                            player.equip_special(item)
                        elif item == "医疗包" and player.health < 100:
                            player.use_special()
                        elif item == "穿甲弹":
                            player.use_special()
                        elif item in ["急救包", "能量饮料", "护甲", "止痛药"]:
                            # 使用消耗品恢复状态
                            player.inventory.remove(item)
                            heal_amount = 20 if item == "急救包" else (10 if item == "能量饮料" else (15 if item == "护甲" else 5))
                            if item == "急救包":
                                player.health = min(100, player.health + heal_amount)
                            print(f"玩家{player.player_id}使用了{item}, 恢复了{heal_amount}点状态")
                            
    def check_respawn(self):
        """检查倒地玩家复活"""
        for player in self.players:
            if player.is_downed and time.time() - player.down_time >= 5:  # 5秒后复活
                player.respawn()
                
    def check_game_over(self):
        """检查游戏是否结束"""
        if self.game_mode == GameMode.SINGLE:
            # 单人模式: 检查是否只剩一名玩家
            alive_players = [p for p in self.players if p.is_alive]
            if len(alive_players) <= 1:
                self.game_over = True
                self.winner = alive_players[0].player_id if alive_players else None
                
        elif self.game_mode == GameMode.DOUBLE:
            # 双人模式: 检查是否只剩一支队伍
            teams_alive = set()
            for player in self.players:
                if player.is_alive:
                    teams_alive.add(player.team_id)
                    
            if len(teams_alive) <= 1:
                self.game_over = True
                winning_teams = [team for team in teams_alive]
                self.winners = [p for p in self.players if p.team_id in winning_teams]
                
        elif self.game_mode == GameMode.FOUR:
            # 四人模式: 检查是否只剩一支队伍
            teams_alive = set()
            for player in self.players:
                if player.is_alive:
                    teams_alive.add(player.team_id)
                    
            if len(teams_alive) <= 1:
                self.game_over = True
                winning_teams = [team for team in teams_alive]
                self.winners = [p for p in self.players if p.team_id in winning_teams]
                
    def end_game_by_time(self):
        """时间到结束游戏"""
        print("\n=== 游戏时间到! ===")
        
        if self.game_mode == GameMode.SINGLE:
            alive_players = [p for p in self.players if p.is_alive]
            if alive_players:
                # 按击杀数排名
                alive_players.sort(key=lambda p: p.kills, reverse=True)
                top_players = alive_players[:3]  # 前三名
                print("最终排名:")
                for i, player in enumerate(top_players, 1):
                    print(f"{i}. 玩家{player.player_id} - 击杀数: {player.kills}")
                self.winners = top_players
                self.winner = top_players[0].player_id
            else:
                self.winners = []
                self.winner = None
                
        elif self.game_mode == GameMode.DOUBLE:
            # 统计每队存活人数和击杀数
            team_stats = defaultdict(lambda: {"alive": 0, "kills": 0})
            for player in self.players:
                if player.team_id is not None:
                    team_stats[player.team_id]["alive"] += 1 if player.is_alive else 0
                    team_stats[player.team_id]["kills"] += player.kills
                    
            # 计算每队总分(存活人数*10 + 击杀数)
            team_scores = {team: (stats["alive"]*10 + stats["kills"]) 
                          for team, stats in team_stats.items()}
                          
            # 按分数排序
            sorted_teams = sorted(team_scores.items(), key=lambda x: x[1], reverse=True)
            
            # 找出最高分队伍
            if sorted_teams:
                top_team_score = sorted_teams[0][1]
                winning_teams = [team for team, score in sorted_teams if score == top_team_score]
                
                # 获取获胜队伍的所有玩家
                self.winners = [p for p in self.players if p.team_id in winning_teams and p.is_alive]
                if not self.winners:
                    # 如果获胜队伍无人存活,按击杀数排序
                    alive_players = [p for p in self.players if p.is_alive and p.team_id in winning_teams]
                    alive_players.sort(key=lambda p: p.kills, reverse=True)
                    self.winners = alive_players[:len(winning_teams)*4]  # 每队最多4人
                    
                self.winner = self.winners[0].player_id if self.winners else None
                
        elif self.game_mode == GameMode.FOUR:
            # 统计每队存活人数和击杀数
            team_stats = defaultdict(lambda: {"alive": 0, "kills": 0})
            for player in self.players:
                if player.team_id is not None:
                    team_stats[player.team_id]["alive"] += 1 if player.is_alive else 0
                    team_stats[player.team_id]["kills"] += player.kills
                    
            # 计算每队总分(存活人数*10 + 击杀数)
            team_scores = {team: (stats["alive"]*10 + stats["kills"]) 
                          for team, stats in team_stats.items()}
                          
            # 按分数排序
            sorted_teams = sorted(team_scores.items(), key=lambda x: x[1], reverse=True)
            
            # 找出最高分队伍
            if sorted_teams:
                top_team_score = sorted_teams[0][1]
                winning_teams = [team for team, score in sorted_teams if score == top_team_score]
                
                # 获取获胜队伍的所有玩家
                self.winners = [p for p in self.players if p.team_id in winning_teams and p.is_alive]
                if not self.winners:
                    # 如果获胜队伍无人存活,按击杀数排序
                    alive_players = [p for p in self.players if p.is_alive and p.team_id in winning_teams]
                    alive_players.sort(key=lambda p: p.kills, reverse=True)
                    self.winners = alive_players[:len(winning_teams)*4]  # 每队最多4人
                    
                self.winner = self.winners[0].player_id if self.winners else None
                
    def show_results(self):
        """显示游戏结果"""
        print("\n=== 游戏结束! ===")
        
        if self.game_mode == GameMode.SINGLE:
            if self.winners:
                print("最终排名:")
                for i, player in enumerate(self.winners, 1):
                    print(f"{i}. 玩家{player.player_id} - 击杀数: {player.kills}")
                print(f"获胜者: 玩家{self.winner}")
            else:
                print("所有玩家都被淘汰了!")
                
        elif self.game_mode == GameMode.DOUBLE:
            if self.winners:
                winning_teams = set(p.team_id for p in self.winners)
                print(f"获胜队伍: {', '.join([f'队伍{team}' for team in winning_teams])}")
                print("获胜玩家:")
                for player in self.winners:
                    print(f"玩家{player.player_id}(队伍{player.team_id}) - 击杀数: {player.kills}")
            else:
                print("所有队伍都被淘汰了!")
                
        elif self.game_mode == GameMode.FOUR:
            if self.winners:
                winning_teams = set(p.team_id for p in self.winners)
                print(f"获胜队伍: {', '.join([f'队伍{team}' for team in winning_teams])}")
                print("获胜玩家:")
                for player in self.winners:
                    print(f"玩家{player.player_id}(队伍{player.team_id}) - 击杀数: {player.kills}")
            else:
                print("所有队伍都被淘汰了!")

# 运行游戏
if __name__ == "__main__":
    print("=== 元梦之星'突围梦幻岛' ===")
    print("选择游戏模式:")
    print("1. 单人模式 (32名玩家)")
    print("2. 双人模式 (16支队伍,每队2人)")
    print("3. 四人模式 (8支队伍,每队4人)")
    
    mode_choice = input("请输入模式编号(1-3): ")
    
    if mode_choice == "1":
        game = BattleRoyaleGame(GameMode.SINGLE)
    elif mode_choice == "2":
        game = BattleRoyaleGame(GameMode.DOUBLE)
    elif mode_choice == "3":
        game = BattleRoyaleGame(GameMode.FOUR)
    else:
        print("无效选择,默认使用单人模式")
        game = BattleRoyaleGame(GameMode.SINGLE)
        
    game.start_game()

突围梦幻岛:
在这里插入图片描述
在这里插入图片描述

四.元梦之星武器:

1.步枪是元梦之星突围梦幻岛中的主力武器。它使用重型子弹,弹夹容量为40发。虽然射速不如冲锋枪快,但威力较大,且在中远距离的精度和威力和步枪相比有较大优势。建议使用三连发点射来提高命中率。

在这里插入图片描述

import random
import time
from enum import Enum

class FireMode(Enum):
    SINGLE = "单发"
    BURST = "三连发"
    AUTO = "全自动"

class Rifle:
    def __init__(self):
        self.ammo = 40  # 弹夹容量40发
        self.max_ammo = 40
        self.damage_per_shot = 25  # 单发伤害
        self.burst_damage = 65  # 三连发总伤害
        self.accuracy = 0.75  # 基础命中率75%
        self.range = 50  # 中远距离优势
        self.current_fire_mode = FireMode.BURST  # 默认三连发
        self.reload_time = 2.0  # 换弹时间2秒
        self.is_reloading = False
        
    def shoot(self, distance, target_evasion=0.2):
        """
        射击
        :param distance: 目标距离(0-100)
        :param target_evasion: 目标闪避率(0-1)
        :return: 是否命中,造成的伤害
        """
        if self.is_reloading or self.ammo <= 0:
            return False, 0
            
        # 根据距离调整命中率
        distance_penalty = max(0, (distance - self.range) / 50)  # 超出射程范围每单位降低10%命中率
        adjusted_accuracy = self.accuracy * (1 - distance_penalty) if distance <= self.range else 0.3
        
        # 根据射击模式选择伤害
        if self.current_fire_mode == FireMode.SINGLE:
            damage = self.damage_per_shot
            shots = 1
        elif self.current_fire_mode == FireMode.BURST:
            damage = self.burst_damage
            shots = 3
        else:  # AUTO
            damage = self.damage_per_shot * 2  # 全自动单发伤害略低
            shots = 2
            
        # 检查是否命中
        hit = random.random() < adjusted_accuracy * (1 - target_evasion)
        
        total_damage = 0
        if hit:
            total_damage = damage if self.current_fire_mode != FireMode.BURST else self.burst_damage
            # 三连发模式下,每发子弹有独立命中判定(但只计算一次总伤害)
            if self.current_fire_mode == FireMode.BURST:
                actual_hits = 0
                for _ in range(3):
                    if random.random() < adjusted_accuracy * (1 - target_evasion):
                        actual_hits += 1
                # 三连发至少命中1发
                if actual_hits == 0:
                    total_damage = self.damage_per_shot  # 至少造成单发伤害
                else:
                    total_damage = self.burst_damage
        else:
            total_damage = 0
            
        # 消耗弹药
        if self.current_fire_mode == FireMode.SINGLE:
            ammo_cost = 1
        elif self.current_fire_mode == FireMode.BURST:
            ammo_cost = 3  # 三连发消耗3发
        else:
            ammo_cost = 2
            
        self.ammo -= ammo_cost
        if self.ammo < 0:
            self.ammo = 0
            
        return hit, total_damage
        
    def reload(self):
        """换弹"""
        if self.is_reloading or self.ammo == self.max_ammo:
            return False
            
        print("正在换弹...")
        time.sleep(self.reload_time)
        self.ammo = self.max_ammo
        self.is_reloading = False
        print(f"换弹完成! 弹夹剩余: {self.ammo}")
        return True
        
    def change_fire_mode(self, mode):
        """切换射击模式"""
        if mode in FireMode:
            self.current_fire_mode = mode
            print(f"切换为{mode.value}模式")
            return True
        return False
        
    def get_status(self):
        """获取步枪状态"""
        return {
            "ammo": self.ammo,
            "max_ammo": self.max_ammo,
            "damage": self.damage_per_shot,
            "burst_damage": self.burst_damage,
            "accuracy": self.accuracy,
            "range": self.range,
            "fire_mode": self.current_fire_mode.value,
            "reloading": self.is_reloading
        }

class RifleTacticsSimulator:
    def __init__(self):
        self.rifle = Rifle()
        self.target_health = 100
        self.distance = 30  # 默认距离30米
        self.target_evasion = 0.2  # 目标基础闪避率20%
        
    def simulate_combat(self):
        """模拟战斗场景"""
        print("\n=== 元梦之星步枪战术模拟 ===")
        print("你装备了一把突击步枪,正在与敌人交战!")
        print(f"当前距离: {self.distance}米 | 目标血量: {self.target_health}")
        print(f"步枪状态: {self.rifle.get_status()}")
        
        # 战术选择
        while self.target_health > 0 and self.rifle.ammo > 0:
            print("\n选择你的行动:")
            print("1. 使用三连发点射(BURST)")
            print("2. 使用单发射击(SINGLE)")
            print("3. 切换为全自动射击(AUTO)")
            print("4. 调整射击距离")
            print("5. 换弹")
            print("6. 退出战斗")
            
            choice = input("请输入选项(1-6): ")
            
            if choice == "1":
                self.burst_shot()
            elif choice == "2":
                self.single_shot()
            elif choice == "3":
                self.auto_fire()
            elif choice == "4":
                self.adjust_distance()
            elif choice == "5":
                self.reload_rifle()
            elif choice == "6":
                print("退出战斗!")
                break
            else:
                print("无效选择,请重新输入!")
                
            # 目标反击
            if self.target_health > 0 and self.rifle.ammo > 0:
                self.enemy_counterattack()
                
        # 战斗结果
        if self.target_health <= 0:
            print("\n=== 战斗胜利! ===")
            print(f"你成功击杀了敌人! 剩余弹药: {self.rifle.ammo}")
        elif self.rifle.ammo <= 0:
            print("\n=== 弹药耗尽! ===")
            print(f"敌人剩余血量: {self.target_health}")
            
    def burst_shot(self):
        """三连发点射"""
        print("\n使用三连发点射!")
        total_damage = 0
        hits = 0
        
        for _ in range(3):
            hit, damage = self.rifle.shoot(self.distance, self.target_evasion)
            if hit:
                hits += 1
                total_damage += damage
                print(f"命中! 造成{damage}点伤害")
                if self.target_health <= 0:
                    break
            else:
                print("未命中!")
                
        if hits > 0:
            print(f"三连发总计造成{total_damage}点伤害")
        else:
            print("三连发全部未命中!")
            
        self.check_target_status(total_damage)
            
    def single_shot(self):
        """单发射击"""
        print("\n使用单发射击!")
        hit, damage = self.rifle.shoot(self.distance, self.target_evasion)
        if hit:
            print(f"命中! 造成{damage}点伤害")
            self.check_target_status(damage)
        else:
            print("未命中!")
            
    def auto_fire(self):
        """全自动射击(模拟2发)"""
        print("\n切换为全自动射击模式!")
        total_damage = 0
        
        for _ in range(2):
            hit, damage = self.rifle.shoot(self.distance, self.target_evasion)
            if hit:
                print(f"命中! 造成{damage}点伤害")
                total_damage += damage
                if self.target_health <= 0:
                    break
            else:
                print("未命中!")
                
        if total_damage > 0:
            print(f"全自动射击总计造成{total_damage}点伤害")
        else:
            print("全自动射击全部未命中!")
            
        self.check_target_status(total_damage)
        
    def adjust_distance(self):
        """调整射击距离"""
        print("\n当前距离:", self.distance, "米")
        print("1. 接近目标(减少10米)")
        print("2. 拉开距离(增加10米)")
        print("3. 保持当前距离")
        
        choice = input("请选择: ")
        if choice == "1" and self.distance > 10:
            self.distance -= 10
            print(f"接近目标! 当前距离: {self.distance}米")
        elif choice == "2" and self.distance < 80:
            self.distance += 10
            print(f"拉开距离! 当前距离: {self.distance}米")
        elif choice == "3":
            print(f"保持当前距离: {self.distance}米")
        else:
            print("无效选择或距离已达极限!")
            
    def reload_rifle(self):
        """换弹"""
        if self.rifle.ammo < self.rifle.max_ammo:
            print(f"弹药不足! 当前弹药: {self.rifle.ammo}/{self.rifle.max_ammo}")
            choice = input("是否换弹? (y/n): ")
            if choice.lower() == 'y':
                self.rifle.reload()
        else:
            print("弹夹已满!")
            
    def enemy_counterattack(self):
        """敌人反击"""
        print("\n敌人开始反击!")
        # 敌人随机选择攻击方式
        attack_type = random.choice(["单发", "连射"])
        
        if attack_type == "单发":
            hit_chance = 0.6  # 敌人单发命中率60%
            damage = random.randint(15, 25)
            if random.random() < hit_chance:
                self.target_health -= damage
                print(f"敌人命中! 造成{damage}点伤害")
            else:
                print("敌人未命中!")
        else:
            # 连射3次,每次有50%概率命中
            total_damage = 0
            hits = 0
            for _ in range(3):
                if random.random() < 0.5:  # 50%命中率
                    hit_damage = random.randint(10, 20)
                    total_damage += hit_damage
                    hits += 1
                    print(f"敌人命中! 造成{hit_damage}点伤害")
                else:
                    print("敌人未命中!")
                    
            if hits > 0:
                print(f"敌人连射总计造成{total_damage}点伤害")
            else:
                print("敌人连射全部未命中!")
                
        if self.target_health < 0:
            self.target_health = 0
        print(f"敌人剩余血量: {self.target_health}")
            
    def check_target_status(self, damage):
        """检查目标状态"""
        self.target_health -= damage
        if self.target_health < 0:
            self.target_health = 0
            
        print(f"敌人剩余血量: {self.target_health}")
        if self.target_health <= 0:
            print("敌人被击倒!")
            
    def show_rifle_tips(self):
        """显示步枪使用技巧"""
        print("\n=== 步枪使用技巧 ===")
        print("1. 中远距离作战时,优先使用三连发点射(BURST)模式")
        print("2. 距离超过50米时,命中率会显著下降,考虑调整距离或使用单发")
        print("3. 全自动模式(AUTO)适合近距离扫射,但弹药消耗快")
        print("4. 保持移动,避免被敌人瞄准")
        print("5. 注意敌人闪避,高闪避目标可能需要多次命中才能击倒")
        print("6. 弹药不足时及时换弹,避免战斗中被击中")

# 运行模拟器
if __name__ == "__main__":
    simulator = RifleTacticsSimulator()
    simulator.show_rifle_tips()
    simulator.simulate_combat()

2.篮球枪:
在这里插入图片描述

import random
import time
import math

class Player:
    def __init__(self, player_id, position=(0, 0), team=None):
        self.player_id = player_id
        self.position = position  # (x, y)坐标
        self.velocity = (0, 0)    # 当前速度向量
        self.is_jumping = False   # 是否处于跳跃状态
        self.is_dribbling = False # 是否正在运球
        self.has_ball = False     # 是否持有篮球
        self.team = team          # 所属队伍
        self.score = 0            # 得分
        self.direction = (1, 0)   # 移动方向(默认向右)
        self.basket_position = (50, 90)  # 篮筐位置(默认在地图右侧)
        self.basket_radius = 3    # 篮筐半径
        self.ball_in_hand = False # 是否手持篮球
        self.shooting_cooldown = 0 # 射击冷却时间
        
    def move(self, direction=None):
        """移动玩家"""
        if direction:
            self.direction = direction
            
        if self.shooting_cooldown > 0:
            self.shooting_cooldown -= 1
            return False
            
        new_x = self.position[0] + self.direction[0] * (5 if not self.is_dribbling else 3)
        new_y = self.position[1] + self.direction[1] * (5 if not self.is_dribbling else 3)
        
        # 边界检查
        if 0 <= new_x <= 100 and 0 <= new_y <= 100:
            self.position = (new_x, new_y)
            return True
        else:
            print(f"玩家{self.player_id}尝试移动到地图外!")
            return False
            
    def shoot(self):
        """投篮"""
        if not self.has_ball or self.shooting_cooldown > 0:
            return False
            
        # 计算与篮筐的距离和角度
        distance = math.sqrt((self.position[0] - self.basket_position[0])**2 + 
                            (self.position[1] - self.basket_position[1])**2)
        
        # 篮球枪特殊效果: 增加投篮距离和精度
        accuracy_modifier = 1.2  # 篮球枪提高20%命中率
        power_modifier = 1.1   # 篮球枪增加10%射程
        
        adjusted_distance = distance / power_modifier
        
        # 判断是否在有效射程内(原距离70,现在可到77)
        if adjusted_distance > 77:
            print(f"玩家{self.player_id}投篮太远了!")
            return False
            
        # 计算投篮成功率(距离越远越低)
        base_accuracy = 0.7 - min(0.4, adjusted_distance/100)  # 最近距离70%成功率,最远30%
        accuracy = base_accuracy * accuracy_modifier
        
        # 投篮!
        if random.random() < accuracy:
            self.has_ball = False
            self.score += 1
            print(f"玩家{self.player_id}投篮命中! 得分+1")
            return True
        else:
            print(f"玩家{self.player_id}投篮不中!")
            return False
            
    def pickup_ball(self, ball_position):
        """捡起篮球"""
        if self.has_ball:
            return False
            
        distance = math.sqrt((self.position[0] - ball_position[0])**2 + 
                            (self.position[1] - ball_position[1])**2)
                            
        if distance < 2:  # 近距离才能捡球
            self.has_ball = True
            self.ball_in_hand = True
            print(f"玩家{self.player_id}捡起了篮球!")
            return True
        return False
        
    def dribble(self):
        """运球"""
        if not self.has_ball:
            return False
            
        self.is_dribbling = True
        print(f"玩家{self.player_id}开始运球")
        return True
        
    def pass_ball(self, target_player):
        """传球"""
        if not self.has_ball or not target_player:
            return False
            
        distance = math.sqrt((self.position[0] - target_player.position[0])**2 + 
                            (self.position[1] - target_player.position[1])**2)
                            
        # 篮球枪传球更精准
        accuracy = 0.9  # 90%准确率
        
        if random.random() < accuracy and distance < 30:  # 30米内有效传球
            self.has_ball = False
            target_player.pickup_ball(target_player.position)  # 简化处理,球传到目标位置
            print(f"玩家{self.player_id}传球给玩家{target_player.player_id}!")
            return True
        else:
            print(f"玩家{self.player_id}传球失败!")
            return False
            
    def use_basketball_gun(self):
        """使用篮球枪特殊技能"""
        if self.has_ball and not self.is_dribbling:
            print(f"玩家{self.player_id}使用篮球枪特殊技能!")
            # 篮球枪特殊效果: 可以远距离精准投篮
            self.shooting_cooldown = 10  # 设置冷却时间
            return self.shoot()
        return False
        
    def jump(self):
        """跳跃"""
        if not self.is_jumping:
            self.is_jumping = True
            print(f"玩家{self.player_id}跳跃!")
            return True
        return False
        
    def update_position(self):
        """更新位置(考虑运球状态)"""
        if self.is_jumping:
            # 简化处理: 跳跃后自动落地
            self.is_jumping = False
            
        if self.is_dribbling and self.has_ball:
            # 运球时球跟随玩家
            pass
            
    def get_status(self):
        """获取玩家状态"""
        status = {
            "id": self.player_id,
            "position": self.position,
            "has_ball": self.has_ball,
            "ball_in_hand": self.ball_in_hand,
            "is_dribbling": self.is_dribbling,
            "score": self.score,
            "shooting_cooldown": self.shooting_cooldown
        }
        return status

class BasketballGunGame:
    def __init__(self, num_players=4):
        self.players = []
        self.basketball = None  # 篮球对象
        self.map_size = (100, 100)  # 地图大小
        self.basket_position = (50, 90)  # 篮筐位置
        self.game_over = False
        self.winner = None
        
        # 创建玩家和篮球
        self.initialize_game(num_players)
        
    def initialize_game(self, num_players):
        """初始化游戏"""
        # 创建玩家
        for i in range(1, num_players+1):
            # 随机初始位置
            x = random.randint(5, 95)
            y = random.randint(5, 85)  # 避免初始位置太靠近篮筐
            self.players.append(Player(i, (x, y)))
            
        # 创建篮球(随机位置)
        self.basketball = {
            "position": (random.randint(10, 90), random.randint(10, 80)),
            "in_play": True
        }
        
    def game_loop(self):
        """游戏主循环"""
        print("=== 元梦之星篮球枪大战 ===")
        print("使用方向键移动,尝试投篮得分!")
        print("篮球枪可以让你的投篮更精准、射程更远!")
        
        turn = 1
        while not self.game_over:
            print(f"\n=== 第{turn}回合 ===")
            
            # 显示球员状态
            for player in self.players:
                status = player.get_status()
                print(f"玩家{status['id']}状态: {'持球' if status['has_ball'] else '无球'}, 得分: {status['score']}")
                if status['has_ball']:
                    print(f"  球在手中: {'是' if status['ball_in_hand'] else '否'}, 运球中: {'是' if status['is_dribbling'] else '否'}")
            
            # 显示篮球位置
            if self.basketball and self.basketball["in_play"]:
                print(f"篮球位置: {self.basketball['position']}")
                
            # 玩家行动(简化为轮流行动)
            for i, player in enumerate(self.players):
                if self.basketball and self.basketball["in_play"] and not any(p.has_ball for p in self.players):
                    # 如果篮球在地上且没人持有,最近的玩家可以捡球
                    distances = [(i, math.sqrt((player.position[0]-self.basketball["position"][0])**2 + 
                                              (player.position[1]-self.basketball["position"][1])**2)) 
                                 for i, player in enumerate(self.players)]
                    distances.sort(key=lambda x: x[1])
                    closest_player_idx = distances[0][0]
                    player = self.players[closest_player_idx]
                    
                    if math.sqrt((player.position[0]-self.basketball["position"][0])**2 + 
                                (player.position[1]-self.basketball["position"][1])**2) < 3:
                        player.pickup_ball(self.basketball["position"])
                        self.basketball["in_play"] = False
                        
                if player.has_ball:
                    print(f"\n玩家{player.player_id}的回合")
                    
                    # 简化操作: 随机选择行动
                    action = random.choice(["移动", "运球", "传球", "投篮", "使用篮球枪"])
                    
                    if action == "移动":
                        direction = random.choice([(1,0), (-1,0), (0,1), (0,-1), (0,0)])
                        player.move(direction)
                    elif action == "运球" and player.has_ball:
                        player.dribble()
                    elif action == "传球" and player.has_ball:
                        # 随机选择一个队友传球
                        teammates = [p for p in self.players if p != player]
                        if teammates:
                            target = random.choice(teammates)
                            player.pass_ball(target)
                    elif action == "投篮" and player.has_ball:
                        if not player.use_basketball_gun():  # 先尝试使用篮球枪
                            player.shoot()  # 如果没有使用篮球枪或使用失败,普通投篮
                    elif action == "使用篮球枪" and player.has_ball and not player.is_dribbling:
                        player.use_basketball_gun()
                    
                    # 更新位置
                    player.update_position()
                    
                    # 检查是否有人得分
                    if player.has_ball and player.shooting_cooldown == 0:  # 如果投篮了但没处理结果
                        if player.has_ball:  # 如果投篮后球还在手中(可能没投出)
                            player.shoot()  # 再次尝试投篮
                            
                    # 检查游戏结束条件
                    self.check_game_over()
                    
                    if self.game_over:
                        break
                
            turn += 1
            
            # 防止无限循环
            if turn > 50:
                print("游戏达到最大回合数,结束!")
                self.calculate_final_scores()
                break
                
            time.sleep(1)  # 暂停1秒
        
        # 显示最终结果
        self.show_results()
        
    def check_game_over(self):
        """检查游戏是否结束"""
        if self.winner:
            return True
            
        # 检查是否有玩家得分超过指定分数(如10分)
        for player in self.players:
            if player.score >= 10:
                self.game_over = True
                self.winner = player
                print(f"玩家{player.player_id}得分达到{player.score},赢得比赛!")
                return True
                
        return False
        
    def calculate_final_scores(self):
        """计算最终得分(如果游戏达到最大回合数)"""
        if not self.players:
            return
            
        max_score = max(p.score for p in self.players)
        winners = [p for p in self.players if p.score == max_score]
        
        if len(winners) == 1:
            self.game_over = True
            self.winner = winners[0]
        else:
            # 平局,选择投篮命中率高的
            shooting_stats = []
            for p in self.players:
                if p.score > 0:
                    accuracy = p.score / (p.score + (10 - p.score)) if (p.score + (10 - p.score)) > 0 else 0
                else:
                    accuracy = 0
                shooting_stats.append((p, accuracy))
                
            # 按命中率排序
            shooting_stats.sort(key=lambda x: x[1], reverse=True)
            top_players = [p for p, acc in shooting_stats if acc == shooting_stats[0][1]]
            
            if len(top_players) == 1:
                self.game_over = True
                self.winner = top_players[0]
            else:
                # 平局,随机选择
                self.winner = random.choice(top_players)
                self.game_over = True
                
    def show_results(self):
        """显示游戏结果"""
        print("\n=== 游戏结束! ===")
        
        if self.winner:
            print(f"获胜者是玩家{self.winner.player_id},得分: {self.winner.score}")
        else:
            print("游戏意外结束,没有获胜者!")
            
        # 显示所有玩家得分
        print("\n最终得分:")
        for player in self.players:
            print(f"玩家{player.player_id}: {player.score}分")
            
    def display_map(self):
        """显示地图状态(简化)"""
        grid = [[' ' for _ in range(self.map_size[0])] for _ in range(self.map_size[1])]
        
        # 标记篮筐位置
        bpx, bpy = self.basket_position
        if 0 <= bpx < self.map_size[0] and 0 <= bpy < self.map_size[1]:
            grid[bpy][bpx] = 'O'  # 篮筐
            
        # 标记玩家
        for player in self.players:
            x, y = int(player.position[0]), int(player.position[1])
            if 0 <= x < self.map_size[0] and 0 <= y < self.map_size[1]:
                if player.has_ball and player.ball_in_hand:
                    grid[y][x] = str(player.player_id)[-1] + '*'  # 持球
                elif player.has_ball:
                    grid[y][x] = str(player.player_id)[-1] + 'H'  # 球在手中但不一定手持
                else:
                    grid[y][x] = str(player.player_id)[-1]  # 玩家ID最后一位
                    
        # 打印地图(简化显示)
        print("\n地图状态:")
        for row in grid:
            print(''.join(row))
        print()

# 运行游戏
if __name__ == "__main__":
    print("=== 元梦之星篮球枪模拟器 ===")
    print("1. 单人模式(演示篮球枪效果)")
    print("2. 多人模式(玩家对战)")
    
    choice = input("请选择模式(1-2): ")
    
    if choice == "1":
        # 单人模式演示
        print("\n=== 篮球枪效果演示 ===")
        player = Player(1, (50, 50))
        game = BasketballGunGame(num_players=1)
        game.players = [player]
        
        # 给玩家一个篮球
        player.pickup_ball((50, 50))
        
        print("初始状态:")
        print(f"玩家位置: {player.position}, 持球: {player.has_ball}")
        
        # 演示普通投篮
        print("\n演示普通投篮:")
        player.position = (40, 80)  # 靠近篮筐
        player.shoot()
        
        # 演示篮球枪投篮
        print("\n演示篮球枪投篮:")
        player.use_basketball_gun()
        
    elif choice == "2":
        # 多人模式
        num_players = int(input("请输入玩家数量(2-4): "))
        if num_players < 2 or num_players > 4:
            num_players = 4
            
        game = BasketballGunGame(num_players=num_players)
        game.game_loop()
    else:
        print("无效选择!")

3.发射器在这里插入图片描述

import random
import time
import math
from enum import Enum

class ProjectileType(Enum):
    BASIC = "基础弹"
    EXPLOSIVE = "爆炸弹"
    HOMING = "追踪弹"
    ICE = "冰冻弹"

class Launcher:
    def __init__(self):
        self.ammo = 10  # 初始弹药
        self.max_ammo = 10
        self.reload_time = 2.0  # 换弹时间(秒)
        self.is_reloading = False
        self.projectile_speed = 15  # 子弹速度
        self.current_ammo_type = ProjectileType.BASIC  # 默认基础弹
        
    def shoot(self, direction, position, target_position=None):
        """
        发射弹药
        :param direction: 发射方向(向量)
        :param position: 发射位置
        :param target_position: 目标位置(追踪弹需要)
        :return: 是否发射成功, 弹药类型
        """
        if self.is_reloading or self.ammo <= 0:
            return False, None
            
        if self.current_ammo_type == ProjectileType.EXPLOSIVE and random.random() > 0.7:
            # 爆炸弹有30%几率哑火
            print("爆炸弹哑火了!")
            return False, None
            
        if self.current_ammo_type == ProjectileType.HOMING and not target_position:
            # 追踪弹需要目标位置
            print("追踪弹需要指定目标位置!")
            return False, None
            
        # 消耗弹药
        self.ammo -= 1
        print(f"发射{self.current_ammo_type.value}! 剩余弹药: {self.ammo}")
        
        # 创建并发射弹药
        projectile = Projectile(
            self.current_ammo_type,
            position,
            direction,
            target_position=target_position if self.current_ammo_type == ProjectileType.HOMING else None
        )
        
        return True, projectile
        
    def reload(self):
        """换弹"""
        if self.is_reloading or self.ammo == self.max_ammo:
            return False
            
        print("正在换弹...")
        self.is_reloading = True
        time.sleep(self.reload_time)
        self.ammo = self.max_ammo
        self.is_reloading = False
        print(f"换弹完成! 弹药: {self.ammo}/{self.max_ammo}")
        return True
        
    def change_ammo(self, ammo_type):
        """切换弹药类型"""
        if ammo_type in ProjectileType:
            self.current_ammo_type = ammo_type
            print(f"切换为{ammo_type.value}")
            return True
        return False
        
    def get_status(self):
        """获取发射器状态"""
        return {
            "ammo": self.ammo,
            "max_ammo": self.max_ammo,
            "reload_time": self.reload_time,
            "is_reloading": self.is_reloading,
            "projectile_speed": self.projectile_speed,
            "current_ammo_type": self.current_ammo_type.value
        }

class Projectile:
    def __init__(self, ammo_type, position, direction, target_position=None):
        self.ammo_type = ammo_type
        self.position = position  # (x, y)坐标
        self.direction = direction  # (dx, dy)方向向量
        self.speed = 15  # 基础速度
        self.target_position = target_position  # 追踪弹目标
        self.lifespan = 100  # 子弹存在时间(帧)
        self.damage = self.get_damage(ammo_type)
        self.radius = 2  # 碰撞半径
        
        # 根据弹药类型调整属性
        if ammo_type == ProjectileType.EXPLOSIVE:
            self.damage = 30  # 爆炸弹伤害高
            self.explosion_radius = 10  # 爆炸范围
        elif ammo_type == ProjectileType.HOMING:
            self.speed = 12  # 追踪弹稍慢但更准
            self.homing_strength = 0.1  # 追踪强度
        elif ammo_type == ProjectileType.ICE:
            self.damage = 10  # 冰冻弹伤害低
            self.slow_effect = 0.5  # 减速效果50%
            self.slow_duration = 30  # 减速持续30帧
            
    @staticmethod
    def get_damage(ammo_type):
        """根据弹药类型返回基础伤害"""
        if ammo_type == ProjectileType.BASIC:
            return 15
        elif ammo_type == ProjectileType.EXPLOSIVE:
            return 30  # 实际伤害要考虑爆炸范围
        elif ammo_type == ProjectileType.HOMING:
            return 20
        elif ammo_type == ProjectileType.ICE:
            return 10
        return 0
        
    def update(self):
        """更新弹药位置"""
        if self.ammo_type == ProjectileType.HOMING and self.target_position:
            # 追踪弹逻辑: 向目标方向调整飞行路径
            dx = self.target_position[0] - self.position[0]
            dy = self.target_position[1] - self.position[1]
            distance = math.sqrt(dx*dx + dy*dy)
            
            if distance > 0:
                # 调整方向,但不完全转向目标(保持一定惯性)
                target_dir_x = dx / distance
                target_dir_y = dy / distance
                self.direction = (
                    self.direction[0] * (1 - self.homing_strength) + target_dir_x * self.homing_strength,
                    self.direction[1] * (1 - self.homing_strength) + target_dir_y * self.homing_strength
                )
                # 归一化方向向量
                length = math.sqrt(self.direction[0]**2 + self.direction[1]**2)
                if length > 0:
                    self.direction = (self.direction[0]/length, self.direction[1]/length)
        
        # 移动弹药
        self.position = (
            self.position[0] + self.direction[0] * self.speed,
            self.position[1] + self.direction[1] * self.speed
        )
        
        self.lifespan -= 1
        return self.lifespan > 0
        
    def check_collision(self, target_position, target_radius):
        """检测碰撞"""
        distance = math.sqrt((self.position[0] - target_position[0])**2 + 
                           (self.position[1] - target_position[1])**2)
        return distance < (self.radius + target_radius)
        
    def explode(self, targets):
        """爆炸效果"""
        affected = []
        for target in targets:
            distance = math.sqrt((self.position[0] - target.position[0])**2 + 
                               (self.position[1] - target.position[1])**2)
            if distance < self.explosion_radius + target.radius:
                # 伤害随距离衰减
                damage_factor = 1 - (distance / self.explosion_radius)
                damage = max(5, int(self.damage * damage_factor))  # 最低5点伤害
                target.take_damage(damage)
                affected.append(target)
        return affected
        
    def apply_ice_effect(self, target):
        """冰冻效果"""
        target.is_slowed = True
        target.slow_factor = self.slow_effect
        target.slow_duration = self.slow_duration
        target.freeze_effect_source = self
        print(f"目标被冰冻! 移动速度降低至{target.slow_factor*100}%")
        
    def get_status(self):
        """获取弹药状态"""
        status = {
            "ammo_type": self.ammo_type.value,
            "position": self.position,
            "direction": self.direction,
            "speed": self.speed,
            "damage": self.damage,
            "lifespan": self.lifespan
        }
        
        if self.ammo_type == ProjectileType.EXPLOSIVE:
            status["explosion_radius"] = self.explosion_radius
            
        if self.ammo_type == ProjectileType.ICE:
            status["slow_effect"] = self.slow_effect
            status["slow_duration"] = self.slow_duration
            
        return status

class Character:
    def __init__(self, character_id, position=(0, 0)):
        self.character_id = character_id
        self.position = position  # (x, y)坐标
        self.velocity = (0, 0)    # 当前速度向量
        self.is_alive = True
        self.health = 100
        self.radius = 5  # 碰撞半径
        self.is_slowed = False
        self.slow_factor = 1.0  # 减速因子
        self.slow_duration = 0  # 减速持续时间
        self.freeze_effect_source = None  # 冰冻效果来源
        self.score = 0
        
    def move(self, direction):
        """移动角色"""
        if not self.is_alive:
            return False
            
        # 应用减速效果
        current_speed = 5 * self.slow_factor if self.is_slowed and self.slow_duration > 0 else 5
            
        new_x = self.position[0] + direction[0] * current_speed
        new_y = self.position[1] + direction[1] * current_speed
        
        # 边界检查
        if 0 <= new_x <= 100 and 0 <= new_y <= 100:
            self.position = (new_x, new_y)
            return True
        else:
            print(f"角色{self.character_id}尝试移动到地图外!")
            return False
            
    def take_damage(self, damage):
        """受到伤害"""
        if not self.is_alive:
            return 0
            
        self.health -= damage
        if self.health <= 0:
            self.health = 0
            self.is_alive = False
            print(f"角色{self.character_id}被击败!")
        return damage
        
    def update_status(self):
        """更新状态(如减速效果)"""
        if self.is_slowed and self.slow_duration > 0:
            self.slow_duration -= 1
            if self.slow_duration <= 0:
                self.is_slowed = False
                self.slow_factor = 1.0
                self.freeze_effect_source = None
                print(f"角色{self.character_id}减速效果结束!")
                
    def get_status(self):
        """获取角色状态"""
        status = {
            "character_id": self.character_id,
            "position": self.position,
            "health": self.health,
            "is_alive": self.is_alive,
            "is_slowed": self.is_slowed,
            "slow_factor": self.slow_factor,
            "slow_duration": self.slow_duration
        }
        return status

class LauncherGame:
    def __init__(self, num_characters=4):
        self.launcher = Launcher()
        self.characters = []
        self.projectiles = []
        self.map_size = (100, 100)  # 地图大小
        self.game_over = False
        
        # 创建角色
        for i in range(1, num_characters+1):
            # 随机初始位置
            x = random.randint(5, 95)
            y = random.randint(5, 95)
            self.characters.append(Character(i, (x, y)))
            
    def game_loop(self):
        """游戏主循环"""
        print("=== 元梦之星发射器大战 ===")
        print("使用方向键移动,尝试击败其他角色!")
        print("发射器有多种弹药类型,选择合适的战术!")
        
        turn = 1
        while not self.game_over:
            print(f"\n=== 第{turn}回合 ===")
            
            # 显示角色状态
            for char in self.characters:
                if char.is_alive:
                    status = char.get_status()
                    print(f"角色{status['character_id']}状态: 生命值{status['health']}, "
                          f"位置{status['position']}, 减速: {'是' if status['is_slowed'] else '否'}")
            
            # 显示发射器状态
            launcher_status = self.launcher.get_status()
            print(f"\n发射器状态: 弹药{launcher_status['ammo']}/{launcher_status['max_ammo']}, "
                  f"当前弹药: {launcher_status['current_ammo_type']}")
            
            # 玩家选择(简化为控制第一个角色)
            if self.characters[0].is_alive:
                print("\n控制角色1:")
                self.handle_player_input(self.characters[0])
                
            # AI控制其他角色
            for i, char in enumerate(self.characters[1:], 1):
                if char.is_alive:
                    self.handle_ai_input(char, i)
            
            # 更新发射器状态
            if self.launcher.is_reloading:
                if self.launcher.reload():
                    print("发射器换弹完成!")
            
            # 更新弹药状态
            projectiles_to_remove = []
            for i, proj in enumerate(self.projectiles):
                if not proj.update():
                    projectiles_to_remove.append(i)
                    continue
                    
                # 检测碰撞
                for char in self.characters:
                    if char.is_alive and proj.check_collision(char.position, char.radius):
                        if proj.ammo_type == ProjectileType.EXPLOSIVE:
                            # 爆炸弹影响周围所有角色
                            affected = proj.explode(self.characters)
                            for affected_char in affected:
                                if affected_char.is_alive:
                                    print(f"角色{affected_char.character_id}被爆炸弹击中!")
                        else:
                            # 其他弹药直接命中
                            print(f"角色{char.character_id}{proj.ammo_type.value}击中!")
                            char.take_damage(proj.damage)
                            
                            # 冰冻弹特殊效果
                            if proj.ammo_type == ProjectileType.ICE:
                                proj.apply_ice_effect(char)
                                
                        projectiles_to_remove.append(i)
                        break
                        
            # 从后往前删除,避免索引问题
            for i in sorted(projectiles_to_remove, reverse=True):
                if i < len(self.projectiles):
                    del self.projectiles[i]
            
            # 更新角色状态
            for char in self.characters:
                if char.is_alive:
                    char.update_status()
                    
            # 检查游戏结束条件
            alive_chars = [c for c in self.characters if c.is_alive]
            if len(alive_chars) <= 1:
                self.game_over = True
                if alive_chars:
                    winner = alive_chars[0]
                    print(f"\n游戏结束! 角色{winner.character_id}获胜!")
                else:
                    print("\n游戏结束! 所有角色都被击败!")
                    
            turn += 1
            
            # 防止无限循环
            if turn > 50:
                print("游戏达到最大回合数,结束!")
                self.game_over = True
                
            time.sleep(1)  # 暂停1秒
        
        # 显示最终结果
        self.show_results()
        
    def handle_player_input(self, character):
        """处理玩家输入(简化为命令行选择)"""
        print("\n选择行动:")
        print("1. 移动")
        print("2. 切换弹药类型")
        print("3. 发射弹药")
        print("4. 换弹")
        
        choice = input("请输入选项(1-4): ")
        
        if choice == "1":
            # 移动
            print("选择移动方向:")
            print("1. 上(0,-1)")
            print("2. 下(0,1)")
            print("3. 左(-1,0)")
            print("4. 右(1,0)")
            dir_choice = input("请输入方向(1-4): ")
            
            direction = {
                "1": (0, -1),
                "2": (0, 1),
                "3": (-1, 0),
                "4": (1, 0)
            }.get(dir_choice, (0, 0))
            
            if direction != (0, 0):
                character.move(direction)
                
        elif choice == "2":
            # 切换弹药
            print("选择弹药类型:")
            print("1. 基础弹")
            print("2. 爆炸弹")
            print("3. 追踪弹")
            print("4. 冰冻弹")
            ammo_choice = input("请输入弹药类型(1-4): ")
            
            ammo_type = {
                "1": ProjectileType.BASIC,
                "2": ProjectileType.EXPLOSIVE,
                "3": ProjectileType.HOMING,
                "4": ProjectileType.ICE
            }.get(ammo_choice, ProjectileType.BASIC)
            
            self.launcher.change_ammo(ammo_type)
            
        elif choice == "3":
            # 发射弹药
            if self.launcher.ammo <= 0:
                print("弹药不足! 请先换弹!")
                return
                
            print("选择发射方向:")
            print("1. 上(0,-1)")
            print("2. 下(0,1)")
            print("3. 左(-1,0)")
            print("4. 右(1,0)")
            dir_choice = input("请输入方向(1-4): ")
            
            direction = {
                "1": (0, -1),
                "2": (0, 1),
                "3": (-1, 0),
                "4": (1, 0)
            }.get(dir_choice, (0, 0))
            
            if direction == (0, 0):
                print("无效方向!")
                return
                
            # 对于追踪弹,需要选择目标
            target_pos = None
            if self.launcher.current_ammo_type == ProjectileType.HOMING:
                print("选择追踪目标(输入角色编号1-4):")
                for i, char in enumerate(self.characters):
                    if char.is_alive:
                        print(f"{i+1}. 角色{i+1} 位置{char.position}")
                
                target_choice = input("请输入目标编号(0取消): ")
                if target_choice.isdigit() and 1 <= int(target_choice) <= len(self.characters):
                    target_idx = int(target_choice) - 1
                    if 0 <= target_idx < len(self.characters) and self.characters[target_idx].is_alive:
                        target_pos = self.characters[target_idx].position
                        
            # 发射
            success, projectile = self.launcher.shoot(direction, character.position, target_pos)
            if success and projectile:
                self.projectiles.append(projectile)
                
        elif choice == "4":
            # 换弹
            self.launcher.reload()
            
    def handle_ai_input(self, character, character_id):
        """处理AI角色输入"""
        if not character.is_alive:
            return
            
        # 简单AI: 随机移动和攻击
        action = random.choice(["移动", "攻击", "换弹", "切换弹药"])
        
        if action == "移动":
            direction = random.choice([(0, -1), (0, 1), (-1, 0), (1, 0)])
            character.move(direction)
            
        elif action == "攻击" and self.launcher.ammo > 0:
            # AI尝试攻击最近的活着的角色(除了自己)
            alive_chars = [c for c in self.characters if c.is_alive and c.character_id != character.character_id]
            if alive_chars:
                # 找到最近的角色
                nearest_char = min(alive_chars, key=lambda c: 
                                   math.sqrt((c.position[0]-character.position[0])**2 + 
                                             (c.position[1]-character.position[1])**2))
                
                # 计算方向
                dx = nearest_char.position[0] - character.position[0]
                dy = nearest_char.position[1] - character.position[1]
                distance = math.sqrt(dx*dx + dy*dy)
                direction = (dx/distance, dy/distance) if distance > 0 else (0, 0)
                
                # 对于追踪弹,目标就是最近的角色
                target_pos = nearest_char.position if self.launcher.current_ammo_type == ProjectileType.HOMING else None
                
                # 发射
                success, projectile = self.launcher.shoot(direction, character.position, target_pos)
                if success and projectile:
                    self.projectiles.append(projectile)
                    
        elif action == "换弹":
            self.launcher.reload()
            
        elif action == "切换弹药":
            # 随机切换弹药类型
            ammo_types = list(ProjectileType)
            current_idx = ammo_types.index(self.launcher.current_ammo_type)
            new_idx = (current_idx + random.randint(1, len(ammo_types)-1)) % len(ammo_types)
            new_ammo = ammo_types[new_idx]
            self.launcher.change_ammo(new_ammo)
            
    def show_results(self):
        """显示游戏结果"""
        print("\n=== 游戏结束! ===")
        
        alive_chars = [c for c in self.characters if c.is_alive]
        if alive_chars:
            winner = alive_chars[0]
            print(f"获胜者是角色{winner.character_id},剩余生命值: {winner.health}")
        else:
            print("游戏意外结束,没有获胜者!")
            
        # 显示所有角色最终状态
        print("\n最终状态:")
        for char in self.characters:
            status = char.get_status()
            print(f"角色{status['character_id']}: {'存活' if status['is_alive'] else '已死亡'}, "
                  f"生命值: {status['health']}, 位置: {status['position']}")
                  
        # 显示发射器状态
        launcher_status = self.launcher.get_status()
        print(f"\n发射器状态: 弹药{launcher_status['ammo']}/{launcher_status['max_ammo']}, "
              f"当前弹药: {launcher_status['current_ammo_type']}")
              
    def display_map(self):
        """显示地图状态(简化)"""
        grid = [[' ' for _ in range(self.map_size[0])] for _ in range(self.map_size[1])]
        
        # 标记角色位置
        for char in self.characters:
            if char.is_alive:
                x, y = int(char.position[0]), int(char.position[1])
                if 0 <= x < self.map_size[0] and 0 <= y < self.map_size[1]:
                    grid[y][x] = str(char.character_id)
        
        # 标记弹药
        for proj in self.projectiles:
            x, y = int(proj.position[0]), int(proj.position[1])
            if 0 <= x < self.map_size[0] and 0 <= y < self.map_size[1]:
                grid[y][x] = f"P{proj.ammo_type.value[0]}"  # P+弹药首字母
                
        # 打印地图(简化显示)
        print("\n地图状态:")
        for row in grid:
            print(''.join(row))
        print()

# 运行游戏
if __name__ == "__main__":
    import math
    
    print("=== 元梦之星发射器模拟器 ===")
    print("1. 单人模式(演示发射器效果)")
    print("2. 多人模式(角色对战)")
    
    choice = input("请选择模式(1-2): ")
    
    if choice == "1":
        # 单人模式演示
        print("\n=== 发射器效果演示 ===")
        launcher = Launcher()
        
        # 演示基础弹
        print("\n演示基础弹:")
        launcher.change_ammo(ProjectileType.BASIC)
        success, proj = launcher.shoot((1,0), (0,0))
        if success and proj:
            proj.update()  # 模拟移动
            print(f"弹药移动到{proj.position}")
            
        # 演示爆炸弹
        print("\n演示爆炸弹:")
        launcher.change_ammo(ProjectileType.EXPLOSIVE)
        success, proj = launcher.shoot((1,0), (0,0))
        if success and proj:
            # 模拟爆炸弹命中多个目标
            class MockTarget:
                def __init__(self, pos):
                    self.position = pos
                    self.radius = 5
                    self.is_alive = True
                    
                def take_damage(self, dmg):
                    print(f"目标受到{dmg}点伤害!")
                    
            targets = [MockTarget((5,0)), MockTarget((10,0)), MockTarget((15,0))]
            if proj.explode(targets):
                print("爆炸弹命中多个目标!")
                
        # 演示追踪弹
        print("\n演示追踪弹:")
        launcher.change_ammo(ProjectileType.HOMING)
        success, proj = launcher.shoot((1,0), (0,0), target_position=(10,10))
        if success and proj:
            for _ in range(5):
                if not proj.update():
                    break
                print(f"追踪弹移动到{proj.position}")
                
        # 演示冰冻弹
        print("\n演示冰冻弹:")
        launcher.change_ammo(ProjectileType.ICE)
        success, proj = launcher.shoot((1,0), (0,0))
        if success and proj:
            class MockCharacter:
                def __init__(self):
                    self.is_slowed = False
                    self.slow_factor = 1.0
                    self.slow_duration = 0
                    
                def take_damage(self, dmg):
                    print(f"角色受到{dmg}点伤害!")
                    
                def update_status(self):
                    if self.is_slowed and self.slow_duration > 0:
                        self.slow_duration -= 1
                        if self.slow_duration <= 0:
                            self.is_slowed = False
                            self.slow_factor = 1.0
                            
            char = MockCharacter()
            proj.apply_ice_effect(char)
            for _ in range(5):
                char.update_status()
                print(f"角色状态: 减速{'是' if char.is_slowed else '否'}, 速度因子{char.slow_factor}")
                
    elif choice == "2":
        # 多人模式
        num_characters = int(input("请输入角色数量(2-4): "))
        if num_characters < 2 or num_characters > 4:
            num_characters = 4
            
        game = LauncherGame(num_characters=num_characters)
        game.game_loop()
    else:
        print("无效选择!")

五.元梦之星道具:

在这里插入图片描述
1.香蕉皮

踩到香蕉皮后可以向前滑一段距离,可以用来搞怪也可以用来跨越障碍。

import random
import time
import math

class Player:
    def __init__(self, player_id, position=(0, 0)):
        self.player_id = player_id
        self.position = position  # (x, y)坐标
        self.velocity = (0, 0)    # 当前速度向量
        self.is_sliding = False   # 是否处于滑行状态
        self.slide_duration = 0   # 滑行剩余时间(帧)
        self.slide_distance = 0   # 已滑行距离
        self.normal_speed = 5     # 正常移动速度
        self.slide_speed = 12     # 滑行速度
        self.friction = 0.8       # 摩擦系数
        self.direction = (1, 0)   # 移动方向(默认向右)
        self.obstacles = []       # 场景障碍物
        self.banana_peels = []    # 场景香蕉皮
        
    def move(self, direction=None):
        """移动玩家"""
        if direction:
            self.direction = direction
            
        if self.is_sliding:
            # 滑行状态下的移动
            self.position = (
                self.position[0] + self.velocity[0],
                self.position[1] + self.velocity[1]
            )
            self.slide_distance += math.sqrt(self.velocity[0]**2 + self.velocity[1]**2)
            self.slide_duration -= 1
            
            # 检查是否滑出地图边界
            if (self.position[0] < 0 or self.position[0] > 100 or 
                self.position[1] < 0 or self.position[1] > 100):
                print(f"玩家{self.player_id}滑出了地图边界!")
                self.stop_slide()
                return False
                
            # 检查是否撞到障碍物
            if self.check_collision():
                print(f"玩家{self.player_id}撞到了障碍物!")
                self.stop_slide()
                return False
                
            # 滑行结束检查
            if self.slide_duration <= 0:
                self.stop_slide()
            return True
        else:
            # 正常移动
            new_x = self.position[0] + self.direction[0] * self.normal_speed
            new_y = self.position[1] + self.direction[1] * self.normal_speed
            
            # 边界检查
            if 0 <= new_x <= 100 and 0 <= new_y <= 100:
                self.position = (new_x, new_y)
                return True
            else:
                print(f"玩家{self.player_id}尝试移动到地图外!")
                return False
                
    def apply_banana_peel(self):
        """踩到香蕉皮,触发滑行"""
        if self.is_sliding:
            print(f"玩家{self.player_id}已经在滑行中!")
            return False
            
        print(f"玩家{self.player_id}踩到了香蕉皮!")
        self.is_sliding = True
        # 随机滑行方向(基于当前移动方向)
        slide_dir = (
            self.direction[0] + random.uniform(-0.5, 0.5),
            self.direction[1] + random.uniform(-0.5, 0.5)
        )
        # 归一化方向向量
        length = math.sqrt(slide_dir[0]**2 + slide_dir[1]**2)
        if length > 0:
            slide_dir = (slide_dir[0]/length, slide_dir[1]/length)
            
        self.velocity = (slide_dir[0] * self.slide_speed, slide_dir[1] * self.slide_speed)
        self.slide_duration = random.randint(10, 20)  # 滑行10-20帧
        self.slide_distance = 0
        
        return True
        
    def stop_slide(self):
        """停止滑行"""
        self.is_sliding = False
        self.velocity = (0, 0)
        print(f"玩家{self.player_id}停止滑行,共滑行了{self.slide_distance:.1f}距离")
        
    def check_collision(self):
        """检查是否与障碍物碰撞"""
        for obstacle in self.obstacles:
            # 简化的碰撞检测(圆形障碍物)
            distance = math.sqrt((self.position[0] - obstacle[0])**2 + 
                                (self.position[1] - obstacle[1])**2)
            if distance < 5:  # 假设障碍物半径为5
                return True
        return False
        
    def place_banana_peel(self):
        """放置香蕉皮"""
        print(f"玩家{self.player_id}放置了香蕉皮在位置{self.position}")
        self.banana_peels.append(self.position)
        
    def update_position(self):
        """更新位置(考虑滑行)"""
        if self.is_sliding:
            return self.move()
        return True
        
    def get_status(self):
        """获取玩家状态"""
        status = {
            "id": self.player_id,
            "position": self.position,
            "is_sliding": self.is_sliding,
            "slide_duration": self.slide_duration,
            "slide_distance": self.slide_distance,
            "direction": self.direction
        }
        return status

class GameMap:
    def __init__(self, width=100, height=100):
        self.width = width
        self.height = height
        self.players = []
        self.obstacles = self.generate_obstacles()
        
    def generate_obstacles(self):
        """生成随机障碍物"""
        obstacles = []
        # 添加一些固定障碍物
        fixed_obstacles = [(20, 20), (50, 50), (80, 30), (30, 70), (60, 80)]
        obstacles.extend(fixed_obstacles)
        
        # 添加随机障碍物
        for _ in range(10):
            x = random.randint(10, self.width-10)
            y = random.randint(10, self.height-10)
            # 确保不与固定障碍物重叠
            if (x, y) not in fixed_obstacles:
                obstacles.append((x, y))
                
        return obstacles
        
    def add_player(self, player):
        """添加玩家到地图"""
        self.players.append(player)
        
    def update(self):
        """更新游戏状态"""
        for player in self.players:
            # 更新玩家位置
            player.update_position()
            
            # 检查香蕉皮效果
            if player.is_sliding:
                # 检查是否踩到其他玩家的香蕉皮
                for other_player in self.players:
                    if other_player != player and (other_player.position in other_player.banana_peels):
                        # 简化逻辑: 如果玩家滑行到香蕉皮位置附近
                        distance = math.sqrt((player.position[0] - other_player.position[0])**2 + 
                                            (player.position[1] - other_player.position[1])**2)
                        if distance < 5:  # 假设香蕉皮影响范围为5
                            print(f"玩家{player.player_id}踩到了玩家{other_player.player_id}放置的香蕉皮!")
                            player.apply_banana_peel()
                            other_player.banana_peels.remove(other_player.position)  # 移除香蕉皮
                            break
                        
            # 检查香蕉皮是否过期(简化处理)
            for player in self.players:
                player.banana_peels = [bp for bp in player.banana_peels if 
                                      (self.width > bp[0] > 0 and self.height > bp[1] > 0)]
        
    def display(self):
        """显示地图状态(简化)"""
        grid = [[' ' for _ in range(self.width)] for _ in range(self.height)]
        
        # 标记障碍物
        for x, y in self.obstacles:
            if 0 <= x < self.width and 0 <= y < self.height:
                grid[y][x] = 'X'
                
        # 标记玩家
        for player in self.players:
            x, y = int(player.position[0]), int(player.position[1])
            if 0 <= x < self.width and 0 <= y < self.height:
                if player.is_sliding:
                    grid[y][x] = 'S'  # 滑行状态
                else:
                    grid[y][x] = str(player.player_id)[-1]  # 玩家ID最后一位
                    
        # 打印地图(简化显示)
        print("\n地图状态:")
        for row in grid:
            print(''.join(row))
        print()

class BananaPeelGame:
    def __init__(self, num_players=4):
        self.map = GameMap()
        self.players = []
        
        # 创建玩家
        for i in range(1, num_players+1):
            # 随机初始位置
            x = random.randint(5, 95)
            y = random.randint(5, 95)
            self.players.append(Player(i, (x, y)))
            
        # 添加玩家到地图
        for player in self.players:
            self.map.add_player(player)
            
    def game_loop(self):
        """游戏主循环"""
        print("=== 元梦之星香蕉皮大战 ===")
        print("使用方向键移动,尝试踩到其他玩家的香蕉皮!")
        print("踩到香蕉皮后会滑行一段距离,可以用来跨越障碍或搞怪!")
        
        # 初始放置一些香蕉皮
        for player in self.players:
            player.place_banana_peel()
            
        running = True
        while running:
            self.map.display()
            
            # 显示玩家状态
            for player in self.players:
                status = player.get_status()
                print(f"玩家{status['id']}状态: {'滑行中' if status['is_sliding'] else '正常'}")
                if status['is_sliding']:
                    print(f"  滑行剩余: {status['slide_duration']}帧, 已滑行: {status['slide_distance']:.1f}距离")
            
            # 玩家输入(简化为随机移动)
            for player in self.players:
                if not player.is_sliding:
                    # 随机移动方向
                    direction = random.choice([(1,0), (-1,0), (0,1), (0,-1), (0,0)])
                    player.move(direction)
                    
                    # 随机放置香蕉皮(20%概率)
                    if random.random() < 0.2:
                        player.place_banana_peel()
                else:
                    # 滑行状态自动移动
                    player.move()
            
            # 更新游戏状态
            self.map.update()
            
            # 检查游戏结束条件(简化为运行10轮)
            # 在实际游戏中可以添加更多结束条件
            
            time.sleep(1)  # 暂停1秒

# 运行游戏
if __name__ == "__main__":
    print("=== 元梦之星香蕉皮模拟器 ===")
    print("1. 单人模式(演示香蕉皮效果)")
    print("2. 多人模式(玩家对战)")
    
    choice = input("请选择模式(1-2): ")
    
    if choice == "1":
        # 单人模式演示
        print("\n=== 香蕉皮效果演示 ===")
        player = Player(1, (50, 50))
        game_map = GameMap()
        game_map.add_player(player)
        
        print("初始状态:")
        print(f"玩家位置: {player.position}")
        
        # 玩家正常移动
        print("\n玩家向前移动:")
        player.move((1,0))
        print(f"新位置: {player.position}")
        
        # 玩家踩到香蕉皮
        print("\n玩家踩到香蕉皮:")
        player.apply_banana_peel()
        for _ in range(5):  # 模拟滑行过程
            player.update_position()
        
        # 玩家停止滑行
        player.stop_slide()
        
    elif choice == "2":
        # 多人模式
        game = BananaPeelGame(num_players=4)
        game.game_loop()
    else:
        print("无效选择!")

云朵道具

使用云朵道具,可以让玩家爬上更高的地方。

在这里插入图片描述

火箭背包

火箭背包可以释放三次能飞渡一大段距离。

在这里插入图片描述

六.元梦之星皮肤:

小爱:
在这里插入图片描述

奥特曼:
在这里插入图片描述

奶龙:
在这里插入图片描述
孙尚香:
在这里插入图片描述
美团骑手:
在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值