首页 > 其他分享 >ChatGTP - 使用js实现升级游戏

ChatGTP - 使用js实现升级游戏

时间:2023-08-15 16:13:18浏览次数:32  
标签:ChatGTP console log currentPlayerIndex players js player return 游戏

实现一个完整且复杂的升级游戏涉及到很多方面,包括玩家操作、游戏状态管理、游戏规则和逻辑等等。下面是一个较为简化的升级游戏的代码示例:

// 游戏状态枚举
const GameState = {
  NOT_STARTED: 'NOT_STARTED',
  BETTING: 'BETTING',
  PLAYING: 'PLAYING',
  END: 'END'
};

class Player {
  constructor(name, money) {
    this.name = name;
    this.money = money;
    this.hand = [];
  }
}

class Game {
  constructor(numPlayers) {
    this.numPlayers = numPlayers;
    this.players = [];
    this.state = GameState.NOT_STARTED;
    this.currentPlayerIndex = -1;
    this.round = 0;
    this.pot = 0;
  }

  // 开始游戏
  start() {
    if (this.state !== GameState.NOT_STARTED) {
      console.log('游戏已经开始!');
      return;
    }

    this.state = GameState.BETTING;
    console.log('游戏开始!');
    console.log('请玩家下注!');
  }

  // 玩家下注
  placeBet(playerIndex, amount) {
    if (this.state !== GameState.BETTING) {
      console.log('请等待其他玩家下注!');
      return;
    }

    const player = this.players[playerIndex];
    if (amount > player.money) {
      console.log('你没有足够的金钱下注!');
      return;
    }

    player.money -= amount;
    this.pot += amount;

    console.log(`${player.name} 下注了 ${amount} 元!`);

    // 检查是否所有玩家完成下注
    if (this.players.every(player => player.money === 0)) {
      this.dealCards();
    } else {
      this.currentPlayerIndex = (this.currentPlayerIndex + 1) % this.numPlayers;
      console.log(`请 ${this.players[this.currentPlayerIndex].name} 下注!`);
    }
  }

  // 发牌
  dealCards() {
    this.state = GameState.PLAYING;
    console.log('正在发牌...');

    // 初始化牌组
    const deck = [];
    for (let i = 2; i <= 10; i++) {
      deck.push(i, i, i, i, 'J', 'J', 'Q', 'Q', 'K', 'K', 'A', 'A');
    }
    deck.push('小王', '小王', '大王', '大王');

    // 洗牌函数
    const shuffle = function (deck) {
      for (let i = deck.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [deck[i], deck[j]] = [deck[j], deck[i]];
      }
      return deck;
    }

    const shuffledDeck = shuffle(deck);

    for (let i = 0; i < this.numPlayers; i++) {
        const player = this.players[i];
        player.hand = shuffledDeck.splice(0, 17);
    }

    this.currentPlayerIndex = 0;
    console.log(`第 ${this.round + 1} 轮开始!`);
    console.log(`${this.players[this.currentPlayerIndex].name} 先行动!`);
  }

  // 玩家出牌
  play(playerIndex, cards) {
    if (this.state !== GameState.PLAYING) {
      console.log('请等待你的回合!');
      return;
    }

    const player = this.players[playerIndex];
    const currentPlayer = this.players[this.currentPlayerIndex];

    if (playerIndex !== this.currentPlayerIndex) {
      console.log('还没有轮到你出牌!');
      return;
    }

    if (!this.isValidMove(cards)) {
      console.log('出牌不合法!');
      return;
    }

    player.hand = player.hand.filter(card => !cards.includes(card));
    currentPlayer.hand = currentPlayer.hand.concat(cards);
    currentPlayer.hand.sort((a, b) => this.getCardValue(b) - this.getCardValue(a));

    console.log(`${player.name} 出牌:${cards.join(' ')}`);
    
    if (player.hand.length === 0) {
      this.round++;
      
      if (this.round === 3) {
        this.state = GameState.END;
        console.log(`游戏结束!夺得最终胜利的玩家是 ${this.findWinner().name}!`);
      } else {
        this.currentPlayerIndex = (this.currentPlayerIndex + 1) % this.numPlayers;
        console.log(`第 ${this.round + 1} 轮开始!`);
        console.log(`${this.players[this.currentPlayerIndex].name} 先出牌!`);
      }
    } else {
      this.currentPlayerIndex = (this.currentPlayerIndex + 1) % this.numPlayers;
      console.log(`${this.players[this.currentPlayerIndex].name} 下一个出牌!`);
    }
  }

  // 寻找最终胜利的玩家
  findWinner() {
    let highestMoney = -1;
    let winner = null;

    for (let player of this.players) {
      if (player.money > highestMoney) {
        highestMoney = player.money;
        winner = player;
      }
    }

    return winner;
  }

  // 点数转换函数
  getCardValue(card) {
    if (!isNaN(parseInt(card))) {
      return parseInt(card);
    }

    switch (card) {
      case 'J':
        return 11;
      case 'Q':
        return 12;
      case 'K':
        return 13;
      case 'A':
        return 14;
      case '小王':
        return 15;
      case '大王':
        return 16;
      default:
        return 0;
    }
  }

  // 判断出牌是否合法
  isValidMove(cards) {
    // 检查出牌是否符合规则
    if (!this.isStraight(cards) && !this.isSameRank(cards)) {
      return false;
    }

    // 检查出牌是否大于上家
    if (this.currentPlayerIndex > 0) {
      const prevPlayer = this.players[(this.currentPlayerIndex - 1) % this.numPlayers];
      const prevCards = prevPlayer.hand.slice(0, cards.length);
      if (this.getCardValue(cards[0]) <= this.getCardValue(prevCards[0])) {
        return false;
      }
    }

    return true;
  }

  // 判断是否是顺子
  isStraight(cards) {
    if (cards.length < 5) {
      return false;
    }

    const values = cards.map(card => this.getCardValue(card));
    values.sort((a, b) => b - a);

    for (let i = 1; i < values.length; i++) {
      if (values[i - 1] - values[i] !== 1) {
        return false;
      }
    }

    return true;
  }

  // 判断是否是相同点数
  isSameRank(cards) {
    if (cards.length < 5) {
      return false;
    }

    const ranks = new Set(cards.map(card => card.slice(0, -1)));

    return ranks.size === 1;
  }
}

// 运行游戏
const game = new Game(3);
game.players.push(new Player('张三', 100));
game.players.push(new Player('李四', 100));
game.players.push(new Player('王五', 100));
game.start();
game.placeBet(0, 30);
game.placeBet(1, 30);
game.placeBet(2, 30);
game.play(0, ['2♥', '2♠', '2♦']);
game.play(1, ['3♥', '3♠', '3♦']);
game.play(2, ['4♥', '4♠', '4♦']);

在这个代码示例中,我们定义了一个Game类来管理升级游戏的状态和逻辑,使用Player类表示每个玩家。游戏开始后,玩家依次下注,下注完毕后进行发牌,然后轮流出牌,每轮出牌按照轮到玩家的上家的牌决定大小。游戏通过isValidMove方法判断出牌是否符合规则和是否大于上家牌,根据规则进行判断胜负,并最终决出最终胜利者。

这个示例中的游戏逻辑相对比较简单,你可以根据自己的需求来修改和扩展代码,实现更复杂的升级游戏。

标签:ChatGTP,console,log,currentPlayerIndex,players,js,player,return,游戏
From: https://www.cnblogs.com/kitty-blog/p/17631441.html

相关文章

  • 以对话为场景本质,AIGC 将如何改变游戏规则
    生成式AI公司MosaicML以约13亿美元的价格被大数据巨头Databricks收购,这个发生于6月底的收购事件成为年内AIGC领域最大收购案。关注【融云全球互联网通信云】了解更多全球对人工智能的投资正在迅速增加。01正在构建的游戏规则《时代周刊》文章称,人工智能在许多任务上超......
  • fastjson反序列化 TODO
    参考链接fastjson反序列化入门文章https://tttang.com/archive/1579/https://xz.aliyun.com/t/12096ASM动态加载相关,如何查看内存生成的类的源码https://juejin.cn/post/6974566732224528392#heading-6https://blog.csdn.net/wjy160925/article/details/85288569关闭ASM去......
  • spring mvc 前端返回 js
    @RequestMapping(value="/test",produces="text/html;charset=UTF-8")@ResponseBodypublicStringtest(){Stringurl="";return"<script>window.location.href='"+url+"';</script>"; ......
  • 详细讲解原生js拖拽
    场景描述今天遇见一个问题,那就是产品希望在弹出来的窗口。可以移动这个弹窗的位置增加用户体验,我们直接使用的element-ui中的Dialog对话框我们现在需要拖拽标题,移动元素位置元素拖拽的思路要让元素按下移动,我们需要实现以下几个步骤:1.鼠标按下元素跟随光标移动2.鼠标抬......
  • js 如何调用摄像头拍照
    1.第一种 业务逻辑需要人脸验证,需要通过调用摄像头获取人脸来调用接口做对比,所以学习了一下js关于调用摄像头拍照。主要通过video调用摄像头和canvas截取画面。<!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><metahttp-equiv="X-UA-Compatible......
  • “优雅”的js
    ......
  • 如何单独在js中引入elementUI的通知组件
    在页面上可以直接使用的通知:open1(){this.$notify({title:'成功',message:'这是一条成功的提示消息',type:'success'});}, 但是在单独的js当中使用时,会提示  .$notify未定义,原因是在单独的js当中未引入el......
  • nodejs的版本管理工具NVM
    nvm(NodeVersionManager)是一个node的版本管理工具,可以快捷的进行node版本的安装、切换、卸载、查看等。它能够在项目开发中根据不同需求轻松切换所依赖不同版本的Node.js,从而让开发者可以在不同的环境之间进行切换,从而更好地保证软件的稳定性运行。1.从官网下载安装包https://g......
  • Python写一个剪刀石头布小游戏
    #导入包importrandom#调用randint()函数,表示随机取其中的任意一个数,左闭右也毕#初始化变量n=0pc=0#表示电脑计分person=0#表示人计分whilen<3:a=random.randint(1,3)#a代表电脑b=int(input('请出拳(1.剪刀,2.石头,3.布):'))#改变变量n+=1#if判断,当电脑出剪刀时:......
  • Jackson解析JSON
    Jackson有三个核心包,分别是Streaming、Databind、Annotations,通过这些包可以方便的对JSON进行操作1.Streaming:在jackson-core模块。定义了一些流处理相关的API以及特定的JSON实现2.Annotations:在jackson-annotations模块,包含了Jackson中的注解3.Databind:在j......