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

VB开发noughts and crosses(井字棋)重玩与落位校验问题咨询

VB 井字棋问题修复方案

1. 重玩选项重复询问问题

问题原因

  • 你采用递归调用Main()的方式实现重玩,旧局的外层循环在新局结束后仍会继续执行playagain()逻辑,导致重复弹出两次选择提示
  • 全局变量winner、marker在重玩时没有重置为初始值,状态残留也会导致逻辑异常

修复方法

不要用递归调用Main()的方式重玩,调整playagain()逻辑返回用户选择结果,同时每次开局前重置所有全局状态:

' 修改playagain返回布尔值,True代表要重玩,False代表退出
Function playagain() As Boolean
    If winner = True Then
        Console.WriteLine("What would you like to do now?")
        Console.WriteLine("1. Play again")
        Console.WriteLine("2. Leave")
        choice = Console.ReadLine()

        Select Case choice
            Case "1"
                ' 重置全局状态
                winner = False
                marker = "X"
                Return True
            Case "2"
                Console.WriteLine("Thanks for playing!")
                Console.ReadLine()
                Return False
        End Select
    End If
    Return False
End Function

' Main方法调整外层逻辑
Sub Main()
    Do
        Console.WriteLine("Players are represented with a character")
        Console.WriteLine(" Player 1 = X.  Player 2 = O")
        setup()
        showboard()
        Do
            ' 原游戏核心循环逻辑不变
            Do
                Console.WriteLine("player pick a number")
                position = Console.ReadLine
            Loop Until board(position) <> "X" And board(position) <> "O"
            board(position) = marker
            showboard()
            check()
            If marker = "X" Then
                marker = "O"
            Else
                marker = "X"
            End If
        Loop Until winner
    Loop While playagain() ' 外层加循环控制重玩
End Sub

2. 落子位置占用提示功能

问题原因

  • 原有输入校验的循环条件写为board(position) <> "X" Or board(position) <> "O",逻辑永远成立,不管位置有没有被占都会通过校验
  • 你编写的checkvalidmove判断逻辑错误:不是判断位置等于当前marker,只要位置值是X或O就属于被占用

修复方法

补全checkvalidmove方法,调整输入校验逻辑:

Function checkvalidmove(pos As Integer) As Boolean
    If board(pos) = "X" Or board(pos) = "O" Then
        Console.WriteLine("position taken")
        Console.ReadLine()
        Return False
    End If
    Return True
End Function

' 修改Main里的输入校验循环
Do
    Console.WriteLine("player pick a number")
    position = Console.ReadLine
Loop Until checkvalidmove(position)

额外需要修正的笔误

你check方法里最后一个胜负判断的代码有笔误:winner = Console.ReadLine() 需要改成普通的Console.ReadLine(),不然会把用户输入赋值给winner变量导致后续逻辑异常。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 17:06:03