代码---------------------------------------------------------------------------------------------------------------------------
# 沙盒类游戏:2D 网格世界
$gridWidth = 10
$gridHeight = 10
# 初始化游戏世界
$world = @()
for ($y = 0; $y -lt $gridHeight; $y++) {
$row = @()
for ($x = 0; $x -lt $gridWidth; $x++) {
$row += "."
}
$world += ,$row
}
# 玩家初始位置
$playerX = 5
$playerY = 5
$world[$playerY][$playerX] = "P"
# 显示世界的函数
function Show-World {
Clear-Host
for ($y = 0; $y -lt $gridHeight; $y++) {
$row = $world[$y] -join " "
Write-Host $row
}
}
# 游戏主循环
while ($true) {
Show-World
Write-Host "控制玩家(W=上, S=下, A=左, D=右, E=创建, Q=删除, X=退出)"
$input = Read-Host "请输入你的命令"
if ($input -eq "X") {
Write-Host "退出游戏..."
break
}
if ($input -eq "W" -and $playerY -gt 0) {
$world[$playerY][$playerX] = "."
$playerY--
} elseif ($input -eq "S" -and $playerY -lt $gridHeight - 1) {
$world[$playerY][$playerX] = "."
$playerY++
} elseif ($input -eq "A" -and $playerX -gt 0) {
$world[$playerY][$playerX] = "."
$playerX--
} elseif ($input -eq "D" -and $playerX -lt $gridWidth - 1) {
$world[$playerY][$playerX] = "."
$playerX++
} elseif ($input -eq "E") {
$world[$playerY][$playerX] = "#"
} elseif ($input -eq "Q") {
$world[$playerY][$playerX] = "."
}
$world[$playerY][$playerX] = "P"
}
说明---------------------------------------------------------------------------------------------------------------------------
世界的表示:世界是一个二维网格,由 $gridWidth 和 $gridHeight 控制,默认大小是 10x10。
玩家的移动:玩家用“WASD”键控制上下左右移动。玩家的位置用字符 P 表示。
物体的创建和删除:玩家可以在当前位置创建方块(按 E 键)或者删除方块(按 Q 键)。创建的方块用 # 表示,删除时恢复为 .。
主循环:每次循环都会显示当前世界状态,并等待用户输入命令。
玩法---------------------------------------------------------------------------------------------------------------------------
玩家可以通过 WASD 移动,E 创建方块,Q 删除方块。
游戏会在控制台上显示当前世界的状态,每个命令执行后更新世界显示。
游戏可以通过输入 X 退出。