You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Svelte中实现带庄家逻辑的双人叫牌历史组件

Svelte叫牌历史组件实现方案

核心需求

  • 双玩家游戏,玩家叫牌记录存入bids数组
  • 当dealer(庄家)值为1时,需在player 0的叫牌序列中添加空值;庄家值为0时无此操作
  • 基于bids数组,不同玩家视角展示对应叫牌历史(庄家为0时,player0与player1的显示效果存在差异)

具体实现步骤

1. 庄家为1时的空值处理逻辑

在初始化或首次叫牌前,判断庄家状态并插入空记录:

export let bids = [];
export let dealer = 0;

// 组件初始化时处理
onMount(() => {
  if (dealer === 1) {
    // 给player0插入初始空叫牌记录
    bids = [{ player: 0, bid: null }, ...bids];
  }
});

// 或在添加叫牌前判断
function addBid(playerId, bidValue) {
  if (dealer === 1 && bids.length === 0) {
    bids = [...bids, { player: 0, bid: null }];
  }
  bids = [...bids, { player: playerId, bid: bidValue }];
}

2. 分玩家视角渲染叫牌历史

根据当前玩家ID和庄家状态,动态调整叫牌的展示顺序与样式:

<div class="bid-history">
  {#each getViewableBids() as bid}
    <div class={`bid-card ${bid.player === currentPlayer ? 'self-bid' : 'opponent-bid'}`}>
      {bid.bid ?? '-'}
    </div>
  {/each}
</div>

<script>
  export let bids = [];
  export let dealer = 0;
  export let currentPlayer = 0;

  function getViewableBids() {
    let displayBids = [...bids];
    // 庄家为0时,player1视角反转叫牌顺序并映射玩家ID
    if (dealer === 0 && currentPlayer === 1) {
      displayBids = displayBids.reverse().map(item => ({
        ...item,
        player: item.player === 0 ? 1 : 0
      }));
    }
    return displayBids;
  }
</script>

<style>
  .bid-history {
    display: flex;
    flex-direction: column;
    gap: 10px;
    padding: 10px;
  }
  .self-bid {
    align-self: flex-end;
    background-color: #dcf8c6;
    padding: 6px 12px;
    border-radius: 6px;
  }
  .opponent-bid {
    align-self: flex-start;
    background-color: #f0f0f0;
    padding: 6px 12px;
    border-radius: 6px;
  }
</style>

3. 叫牌记录更新逻辑优化

确保每次叫牌操作都正确维护bids数组的结构,同时兼容庄家状态:

// 示例叫牌触发函数
function handleBid(playerId, bid) {
  let updatedBids = [...bids];
  // 庄家为1且无记录时,先插入player0的空值
  if (dealer === 1 && updatedBids.length === 0) {
    updatedBids.push({ player: 0, bid: null });
  }
  // 添加当前玩家的叫牌
  updatedBids.push({ player: playerId, bid });
  // 更新数组(Svelte响应式更新)
  bids = updatedBids;
}

内容的提问来源于stack exchange,提问作者balaji

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 07:00:04