如何基于用户输入移动迷宫中代表玩家的O的位置?(附VB代码)
VB迷宫游戏:实现玩家移动功能解决方案
以下是完善后的代码,实现基于用户输入移动玩家(O)的功能,包含位置初始化、输入验证、移动逻辑和游戏循环:
Module Program Dim startx As Integer Dim starty As Integer Dim endx As Integer = 8 ' 终点坐标(x=8, y=9) Dim endy As Integer = 9 Dim maze As String(,) = { {"x ", "x ", "x ", "x ", "x ", "x ", "x ", "x ", "x ", "x"}, {"O ", " ", " ", " ", " ", " ", " ", " ", " ", "x"}, {"x ", "x ", "x ", "x ", "x ", " ", "x ", "x ", " ", "x"}, {"x ", "x ", " ", "x ", "x ", " ", "x ", "x ", " ", "x"}, {"x ", "x ", " ", " ", " ", " ", "x ", "x ", " ", "x"}, {"x ", "x ", "x ", "x ", "x ", " ", "x ", "x ", "x ", "x"}, {"x ", " ", " ", " ", " ", " ", " ", " ", " ", "x"}, {"x ", " ", "x ", "x ", "x ", "x ", "x ", "x ", " ", "x"}, {"x ", " ", " ", " ", " ", "x ", "x ", "x ", " ", " "}, {"x ", "x ", "x ", "x ", "x ", "x ", "x ", "x ", "x ", "x"}} Sub Main(args As String()) Console.WriteLine("这是一个迷宫游戏") Console.WriteLine("请输入你要移动到的坐标(格式:x y,用空格分隔)") ' 初始化玩家起点位置 InitializePlayerPosition() ' 游戏主循环 Do Console.Clear() DisplayChessboard() ' 检查是否到达终点 If startx = endx And starty = endy Then Console.WriteLine("恭喜你到达终点!游戏结束") Exit Do End If ' 处理玩家移动 MakeMove() Loop End Sub ' 初始化玩家初始位置 Sub InitializePlayerPosition() For x As Integer = 0 To 9 For y As Integer = 0 To 9 If maze(x, y) = "O " Then startx = x starty = y Exit Sub End If Next Next End Sub ' 显示迷宫 Sub DisplayChessboard() Console.WriteLine(" 0 1 2 3 4 5 6 7 8 9") For x As Integer = 0 To 9 Console.Write(x & " ") For y As Integer = 0 To 9 Console.Write(maze(x, y)) Next Console.WriteLine() Next End Sub ' 处理玩家移动逻辑 Sub MakeMove() Console.Write("输入移动坐标:") Dim input As String = Console.ReadLine().Trim() Dim coords() As String = input.Split({" "}, StringSplitOptions.RemoveEmptyEntries) ' 验证输入格式是否正确 If coords.Length <> 2 Then Console.WriteLine("输入格式错误,请输入x和y两个数字(用空格分隔)") Console.WriteLine("按任意键继续...") Console.ReadKey() Return End If Dim newX, newY As Integer ' 验证输入是否为整数 If Not Integer.TryParse(coords(0), newX) Or Not Integer.TryParse(coords(1), newY) Then Console.WriteLine("输入必须是整数,请重新输入") Console.WriteLine("按任意键继续...") Console.ReadKey() Return End If ' 验证坐标是否在迷宫范围内 If newX < 0 Or newX > 9 Or newY < 0 Or newY > 9 Then Console.WriteLine("坐标超出迷宫范围(0-9),请重新输入") Console.WriteLine("按任意键继续...") Console.ReadKey() Return End If ' 验证目标位置是否为墙(x) If maze(newX, newY) = "x " Then Console.WriteLine("该位置是墙,无法移动,请重新输入") Console.WriteLine("按任意键继续...") Console.ReadKey() Return End If ' 更新玩家位置 maze(startx, starty) = " " ' 原位置设为空格 maze(newX, newY) = "O " ' 新位置设为玩家标记 startx = newX starty = newY End Sub End Module
关键功能说明
- 初始化玩家位置:
InitializePlayerPosition遍历迷宫自动找到初始的O位置,避免硬编码坐标,提升灵活性。 - 游戏主循环:通过
Do-Loop持续运行游戏,每次循环清屏并重新绘制迷宫,直到玩家到达终点。 - 输入验证:检查输入格式、是否为整数、坐标范围以及目标位置是否为墙,避免非法操作导致的错误。
- 位置更新:移动时将原位置改为空格,新位置改为
O,并更新玩家当前坐标。
内容的提问来源于stack exchange,提问作者noob
相关产品推荐
相关产品推荐

