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

Lua版RPS(石头剪刀布)计分系统异常:最终分数始终归零求助

问题分析与解决

核心问题1:未定义r变量

代码中仅声明了p(Paper)和s(Scissors),但未给代表"Rock"的r赋值,导致:

  • hands数组包含nil值,Bot随机选出手势时可能出错
  • 玩家输入"Rock"时,与r(nil)的比较永远不成立,所有涉及Rock的胜负逻辑都不会触发,计分函数自然不会执行

核心问题2:计分变量作用域混乱

你用local ps = 0和local bs = 0声明了局部计分变量,但addPs/addBs函数修改的是全局变量_G.ps/_G.bs,最后打印的却是初始值为0的局部变量,所以无论游戏中全局变量如何变化,最终输出的都是初始的0。

修正后的完整代码

local r = "Rock"
local p = "Paper"
local s = "Scissors"
local pw = "Player wins!\n"
local bw = "Bot wins!\n"
local t = "Tie!\n"
local hands = {r, p, s}
local ps = 0 -- Player Score
local bs = 0 -- Bot Score

-- 直接操作局部计分变量,无需全局变量
local function addPs()
    ps = ps + 1
end

local function addBs()
    bs = bs + 1
end

print("Type 'stop' to stop the game.\n")

local function rps()
    while true do
        print("Rock, Paper, or Scissors:")
        local player = io.read()
        print()
        print("Player chooses " .. player .. "!\n")
        local bot = hands[math.random(#hands)]
        print("Bot chooses " .. bot .. "!\n")
   
        if player == r and bot == p then
            print(bw)
            addBs()
        elseif player == p and bot == r then
            print(pw)
            addPs()
        elseif player == r and bot == s then
            print(pw)
            addPs()
        elseif player == s and bot == r then
            print(bw)
            addBs()
        elseif player == p and bot == s then
            print(bw)
            addBs()
        elseif player == s and bot == p then
            print(pw)
            addPs()
        elseif player == r and bot == r then
            print(t)
        elseif player == p and bot == p then
            print(t)
        elseif player == s and bot == s then
            print(t)
        elseif player == "stop" then
            print("Stopping. . .")
            break
        -- 修正无效输入的判断逻辑
        elseif not (player == r or player == p or player == s) then
            print("Error: Player did not choose valid option(Rock; Paper; Scissors; stop)\nContinuing. . .\n")
        end
    end
end

rps()

local fs = ("Final Score:\nPlayer Score: " .. ps .. "\nBot Score: "  .. bs) -- Final Score
print()
print(fs)

关键修改点

  1. 添加local r = "Rock",补全手势变量定义
  2. 将计分函数改为局部函数,直接操作局部的ps和bs,避免作用域混淆
  3. 修正无效输入的判断逻辑,改为检查玩家输入是否为有效手势或"stop"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 04:10:35