前言
推箱子的逻辑部分都已经做好了注释。
并没有增加游戏如何胜利。
游戏的规则由自己决定。
演示
代码
using System;
namespace Game {
//推箱子
public class Sokoban {
//步数
public int steps;
//地图大小
public const int N = 10;
//角色的坐标
public int roleX;
public int roleY;
//箱子的坐标
public int boxX;
public int boxY;
//地图,二维数组
public int[,] map = new int[N,N];
//移动方向,上下左右
public int[] dx = new int[4] { -1,1,0,0};
public int[] dy = new int[4] { 0,0,-1,1};
//键盘的值,上下左右
public Dictionary<char, int> keyboradValue;
//初始化
public void initGame(int boxRow,int boxCol,int roleRow,int roleCol) {
steps = 0;
roleX = roleRow;
roleY = roleCol;
boxX = boxRow;
boxY = boxCol;
keyboradValue = new Dictionary<char, int>() {
{'W',0 },{'S',1 }, {'A',2 },{'D',3 }
//{ 'w', 0 },{ 's',1},{ 'a',2},{ 'd',3}
};
for(int i = 0; i < N; i++) {
for(int j = 0; j < N; j++) {
map[i,j] = 0;
if (i == 0 || i == N - 1 || j == 0 | j == N - 1) {
map[i, j] = -1;
}
}
}
}
//打印地图
public void showMap() {
for(int i = 0; i < N; i++) {
for(int j = 0; j < N; j++) {
/*
* box是箱子:用0表示
* -1是墙:用-1表示
* 空格是可移动区域
* role是角色:用@表示
*/
if (i == boxX && j == boxY) Console.Write("0");
else if (map[i, j] == -1) Console.Write("#");
else if (i == roleX && j == roleY) Console.Write("@");
else if (map[i, j] == 0) Console.Write(" ");
}
Console.WriteLine();
}
}
//判断坐标是否在N×N的地图中
public bool coordinateIsValid(int x,int y) {
return (x > 0 && x < N && y > 0 && y < N);
}
//角色移动:通过键盘
public void moveRole(char keyValue) {
if (keyboradValue.ContainsKey(keyValue)) {
int direction = keyboradValue[keyValue];
int newX = roleX+dx[direction];
int newY = roleY+dy[direction];
if(coordinateIsValid(newX,newY)) {
bool isBox = false;
bool isPushed = false;
//如果前进的点碰到了箱子
if(newX==boxX && newY==boxY) {
isBox = true;
int newBoxX = boxX+dx[direction];
int newBoxY = boxY+dy[direction];
if (coordinateIsValid(newBoxX, newBoxY) &&map[newBoxX, newBoxY] !=-1) {
boxX = newBoxX;
boxY = newBoxY;
isPushed= true;
}
}
//如果前面是箱子,但是没推动,说明角色不能动
if (isBox && isPushed == false) return;
roleX = newX;
roleY = newY;
}
}
}
//主函数
public static void Main(string[] args) {
Sokoban sokoban = new Sokoban();
sokoban.initGame(4, 6, 2, 3);
Console.WriteLine("推箱子:你可以按下键盘的[WASD]来控制角色的移动!\n当你按下[e]可以推出游戏。");
char keyValue;
while (true) {
//从键盘获取输入,并且不显示在屏幕上
keyValue = (char)(Console.ReadKey(true).Key);
if (keyValue == 'e' || keyValue == 'E') break;
sokoban.steps++;
sokoban.moveRole(keyValue);
Console.Clear();
sokoban.showMap();
Console.WriteLine($"你已经走了: {sokoban.steps} 步");
}
}
}
}