我正在观看有关如何使用JavaScript和jQuery制作类似于Zork的游戏的教程。到目前为止,它一直在工作,但是当我尝试使用方向命令更改运行游戏的位置时,我得到的是不确定的,而不是新的房间。
var currentRoom = "start" ;
function changeRoom(dir) {
if(rooms[currentRoom].directions[dir] !== undefined) {
currentRoom = rooms[currentRoom].directions[dir];
$('#game-text').append("<p>" + rooms[currentRoom].description + "</p>");
} else {
$('#game-text').append("<p> You cannot go that way </p>");
}
}
编辑:此代码位于上面的代码之后
$(document).ready(function(){
$('#game-text').append("<p>" + rooms.start.description + "</p>");
$(document).keypress(function(key){
if(key.which === 13 && $('#user-input').is(':focus')){
var value = $('#user-input').val().toLowerCase();
switch(value) {
case "north":
changeRoom("north");
break;
case "south":
changeRoom("south");
break;
case "east":
changeRoom("east");
break;
case "west":
changeRoom("west");
break;
default:
alert("Invalid move!")
}
}
})
})
我认为这与这段代码有关。出现“您不能那样走”消息时,应该出现;但是我没有得到我进入的房间的描述,只有一条未定义的消息。抱歉,如果我不清楚,这是我的拳头尝试,我对JavaScript知之甚少。
编辑:这是两个“房间”。
var rooms = {
"start": {
"description": "It is a sunny day, perfect for a walk!\
While walking, you come across an intersection;\
you can go <b>North</b>, <b>South</b>, <b>East</b> or\
<b>West</b>, which way do you choose?",
"directions": {
"north": "deadend",
"west": "shortcut",
"east": "garden",
"south": "home"
}
"garden": {
"discription": "Ahh the right path, I see you choose the long\
way around which leads through a lovley garden",
"directions": {
"west": "start",
"east": "deadend"
}
},