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

JS骰子游戏求助:实现投掷总分累计与游戏结束触发逻辑

骰子游戏开发问题解决方案

问题描述

我正在开发一个学校作业的骰子游戏,规则为:玩家选择6-9之间的数字,之后投掷两枚骰子,若骰子总和等于所选数字则游戏结束。目前遇到两个问题:

  • 无法实现每次投掷后总分的累计,仅能显示单次投掷的骰子和;
  • 不知道如何实现当骰子总和等于“淘汰数(knockoutSiffra)”时触发游戏结束的逻辑。

原代码

JavaScript部分

let knockoutSiffra = 0;

const dices = document.querySelectorAll('.dice');
console.log(dices);

dices.forEach(bt =>{
    bt.addEventListener('click', (e) =>{
        knockoutSiffra = e.target.innerHTML;
        console.log(knockoutSiffra)
    })
})

document.getElementById('go')
.addEventListener('click', () => {
    if(knockoutSiffra != 0){
        choose.style.display = 'none'
        play.style.display = 'block'
        console.log('kör')
    } else{
        console.log('välj ett nummer')
    }

    const showNumber = document.getElementById('showNumber');
    showNumber.innerText = 'Ditt valda nummer är:' + " " + knockoutSiffra
})

// Slide 3
let lost = document.querySelector('.lost')
lost.style.display = 'none';

const dice1 = document.querySelector('.dice1');
const dice2 = document.querySelector('.dice2');
const result = document.querySelector('.dice-result');
const game = document.querySelector('.game');

let score = 0;

game.addEventListener('click', () => {
    let d1 = GetRandomDice ();
    let d2 = GetRandomDice ();

    dice1.src = `Dice img/Dice-${d1}.png`;
    dice2.src = `Dice img/Dice-${d2}.png`;

    let sum = d1 + d2;
    result.innerText = 'Antal poäng:' + " " + sum;

    function GetRandomDice(){
        return Math.ceil(Math.random() * 6);
    }
})

HTML部分(片段)

<h1 id="showNumber">Ditt valda nummer är: </h1>
<h2 class="dice-result">Antal poäng:</h2>

<button class="game">Kasta tärningarna</button>

<section class="throw">
   <img src="Dice img/Dice-3.png" alt="3" class="dice1">
   <img src="Dice img/Dice-6.png" alt="6" class="dice2">
</section>

<section>
    <h2 class="lost">Du förlorade!</h2>
    <button class="playAgain">Spela igen</button>
</section>

解决方案

1. 实现总分累计

问题根源是仅计算单次投掷的和,未对全局score变量进行累加。修改步骤:

  • 将knockoutSiffra转为数字类型,避免字符串与数字比较的潜在bug;
  • 每次投掷后,若未触发淘汰,则将单次和累加到score;
  • 更新结果文本为累计总分。

修改后的选择数字事件:

dices.forEach(bt =>{
    bt.addEventListener('click', (e) =>{
        knockoutSiffra = parseInt(e.target.innerHTML); // 转为数字类型
        console.log(knockoutSiffra)
    })
})

修改后的投掷按钮事件(累计分数部分):

game.addEventListener('click', () => {
    let d1 = GetRandomDice();
    let d2 = GetRandomDice();

    dice1.src = `Dice img/Dice-${d1}.png`;
    dice2.src = `Dice img/Dice-${d2}.png`;

    let sum = d1 + d2;
    // 未淘汰则累加分数
    if (sum !== knockoutSiffra) {
        score += sum;
        result.innerText = `Antal poäng: ${score}`;
    } else {
        // 触发淘汰逻辑
        endGame();
    }

    function GetRandomDice(){
        return Math.ceil(Math.random() * 6);
    }
})

2. 实现淘汰触发游戏结束逻辑

封装endGame函数处理游戏结束的UI更新,同时添加重新开始的逻辑:

// 游戏结束逻辑
function endGame() {
    lost.style.display = 'block';
    game.style.display = 'none'; // 隐藏投掷按钮
    result.innerText = `Slutlig poäng: ${score}`; // 显示最终分数
}

// 重新开始游戏逻辑
const playAgain = document.querySelector('.playAgain');
playAgain.addEventListener('click', () => {
    // 重置所有状态
    score = 0;
    knockoutSiffra = 0;
    lost.style.display = 'none';
    game.style.display = 'block';
    result.innerText = 'Antal poäng:';
    document.getElementById('showNumber').innerText = 'Ditt valda nummer är:';
    // 回到选号界面
    choose.style.display = 'block';
    play.style.display = 'none';
    // 重置骰子图片
    dice1.src = 'Dice img/Dice-3.png';
    dice2.src = 'Dice img/Dice-6.png';
})

完整修改后代码

JavaScript

let knockoutSiffra = 0;
let score = 0;

const dices = document.querySelectorAll('.dice');
const lost = document.querySelector('.lost');
const dice1 = document.querySelector('.dice1');
const dice2 = document.querySelector('.dice2');
const result = document.querySelector('.dice-result');
const game = document.querySelector('.game');
const playAgain = document.querySelector('.playAgain');
const showNumber = document.getElementById('showNumber');

// 初始化隐藏失败提示
lost.style.display = 'none';

// 选择淘汰数字
dices.forEach(bt =>{
    bt.addEventListener('click', (e) =>{
        knockoutSiffra = parseInt(e.target.innerHTML);
        console.log(knockoutSiffra)
    })
})

// 开始游戏按钮
document.getElementById('go').addEventListener('click', () => {
    if(knockoutSiffra !== 0){
        choose.style.display = 'none';
        play.style.display = 'block';
        console.log('kör');
    } else{
        console.log('välj ett nummer');
    }
    showNumber.innerText = `Ditt valda nummer är: ${knockoutSiffra}`;
})

// 投掷骰子按钮
game.addEventListener('click', () => {
    let d1 = GetRandomDice();
    let d2 = GetRandomDice();

    dice1.src = `Dice img/Dice-${d1}.png`;
    dice2.src = `Dice img/Dice-${d2}.png`;

    let sum = d1 + d2;
    if (sum !== knockoutSiffra) {
        score += sum;
        result.innerText = `Antal poäng: ${score}`;
    } else {
        endGame();
    }

    function GetRandomDice(){
        return Math.ceil(Math.random() * 6);
    }
})

// 游戏结束处理
function endGame() {
    lost.style.display = 'block';
    game.style.display = 'none';
    result.innerText = `Slutlig poäng: ${score}`;
}

// 重新开始游戏
playAgain.addEventListener('click', () => {
    score = 0;
    knockoutSiffra = 0;
    lost.style.display = 'none';
    game.style.display = 'block';
    result.innerText = 'Antal poäng:';
    showNumber.innerText = 'Ditt valda nummer är:';
    choose.style.display = 'block';
    play.style.display = 'none';
    dice1.src = 'Dice img/Dice-3.png';
    dice2.src = 'Dice img/Dice-6.png';
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 12:25:53