我计划基于 ajax 请求创建一个简单的浏览器游戏。我在客户端上有一张由 10x10 div 组成的地图。在服务器上,我有一个表示我的 div 状态的数组 [10,10],例如,如果客户端单击某个 div,则会在后台发送一个 ajax 请求,更新我的数组并将数字 1 插入适当的阵列位置。基于这个想法,我希望所有客户端都看到相同的地图,所以我正在考虑将我的地图数组存储在应用程序状态中(除非有更好的方法来做到这一点),因为我们都知道应用程序状态在所有客户端之间共享。所以我的问题是我将如何做到这一点,或者我如何真正进入 Asp.Net MVC 中的应用程序状态。我搜索了很多,找不到在 Asp 中以应用程序状态插入数据的正确方法。Net MVC 3 尤其是二维数组,这让事情变得有点困难。到目前为止,我的代码或多或少在不使用应用程序状态的情况下工作。我的意思是,每次我创建地图数组的新实例并将该实例从服务器返回到客户端时,这是错误的,因为我只是想实例化一张地图并将同一张地图返回给每个人,这就是我要堆叠的部分。
//当用户访问我的网站时
public class HomeController : Controller
{
public MapModel mapModel = new MapModel();
public ActionResult Index()
{
return View(mapModel);
}
}
//当用户点击一个div(地图瓦片)时的Ajax请求
$(".mapTile").click(function () {
var xx = $(this).attr("y");
var yy = $(this).attr("x");
$("#info").text($(this).attr("x"));
var tile = {
X: xx,
Y: yy,
Value: 1
};
$.ajax({
beforeSend: function () { ShowAjaxLoader(); },
url: "/Game/ShowTiles",
type: "POST",
contentType: "application/json;charset=utf-8",
dataType: "json",
data: JSON.stringify(tile),
success: function (data) {
HideAjaxLoader(), $.each(data, function (index, item) {
if (item.Value === 1) {
var xCordinate = item.X;
var yCordinate = item.Y;
$("#" + yCordinate + xCordinate).css("background-color", "red");
}
});
},
error: function () { showErrorMsg(); }
});
});
//我的模型
// 地图模型
public class MapModel
{
private TileModel[,] mapTilesArray;
public TileModel[,] MapTilesArray
{
get
{
return mapTilesArray;
}
set
{
mapTilesArray = value;
}
}
public MapModel()
{
MapTilesArray = new TileModel[10,10];
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
MapTilesArray[i, j] = new TileModel();
}
}
}
}
//平铺模型
public class TileModel
{
public int X{ get; set; }
public int Y{ get; set; }
public int Value { get; set; }
}
//我的游戏控制器
[HttpPost]
public JsonResult ShowTiles(TileModel tile)
{
MapModel map = new MapModel();
map.MapTilesArray[tile.X, tile.Y].Value = 1;
map.MapTilesArray[tile.X, tile.Y].X = tile.X;
map.MapTilesArray[tile.X, tile.Y].Y = tile.Y;
return Json(map.MapTilesArray);
}