2013-10-08 3 views
1

Я работаю над текстовой игрой, а window.close(); - это то, что я использую, когда персонаж умирает. Однако, когда используется обработчик window.close();, он не закрывает окно и просто полностью пропускает часть, переходя к другим операторам оповещения/if else.window.close() не исполняется

alert("Part 2 of game commencing."); 
alert("For this part of the game, you can re-state your computer password."); 

var password = prompt("Enter your new password now!"); 
var passwordConfirm = prompt("Confirm your password."); 
if (passwordConfirm == password) { 
    alert("Correct! Both passwords match."); 
} else if (passwordConfirm != password) { 
    alert("Both passwords do not match."); 
    var newPassword = prompt("Let's try this again, retype the password you want."); 
    var newPassword = password; 
    var passwordConfirm = prompt("Confirm your password (don't screw it up this time  you fool)"); 
    if (passwordConfirm == password) { 
     alert("Correct! Both passwords match."); 
    } else if (passwordConfirm != password) { 
     alert("Wrong. You've missed your chance at getting a new password. Just use rat_race."); 
    } 
} 

alert("You're starting to feel hungry."); 
alert("You look up where you could eat for the night."); 

var roomService = prompt("Do you (a) get room service or (b) eat out?"); 
if (roomService == "a") { 
    alert("You call room service, and you ask for spaghetti."); 
    alert("After five minutes, your meal arrives. You eat it."); 
} else if (roomService == "b") { 
    alert("You leave your room, taking your room key with you."); 
    var elevator = prompt("You enter the elevator. Do you take floor B, 1, 2, 3, 4, 5  (case sensitive)"); 
    switch (elevator) { 
     case "B": 
      alert("You head down to the garage."); 
      break; 
     case "1": 
      alert("You go to floor 1 and the doors slide open. You realise you're on the wrong floor. You go back in, and you press on B."); 
      break; 
     case "2": 
      alert("You go to floor 2 and the doors slide open. You realise you're on the wrong floor. You go back in, and you press on B."); 
      break; 
     case "3": 
      alert("You go to floor 3 and the doors slide open. You realise you're on the wrong floor. You go back in, and you press on B."); 
      break; 
     case "4": 
      alert("You go to floor 4 and the doors slide open. You realise you're on the wrong floor. You go back in, and you press on B."); 
      break; 
     case "5": 
      alert("You go to floor 5 and the doors slide open. You realise you're on the wrong floor. You go back in, and you press on B."); 
      break; 
     default: 
      alert("Enter a valid option next time! Skipping exercise."); 
    } 
    alert("The elevator doors slide open."); 
    alert("You walk over to your car, and you drive out of the parking lot."); 
    alert("You arrive at the restaurant."); 
    alert("You make your order, eat, and go back to your room."); 
} 

alert("You're feeling sleepy. You go to bed."); 
var wakeUp = prompt("You wake up. Do you (a) sleep in, or (b) get out of bed?"); 
if (wakeUp == "a") { 
    alert("You wake up again."); 
} else if (wakeUp == "n") { 
    //DO NOTHING// 
} 

alert("You decide that before going in for your kill, you should do some reconnaissance   first."); 
alert("You head down to the garage, and you climb into your car."); 
alert("You head to the Trenton Air Force Base."); 
alert("You realise it's probably going to be pretty tough to actually get INTO the base."); 

var enterBase = prompt("Do you (a) crash your car through the main gate and kill the  guard, or (b) pull out your old military ID and bullshit your way through?"); 
if (enterBase == "a") { 
    alert("You arrive at the base. You put the pedal to the metal, and you crash through the fence."); 
    alert("You swing open the door of your car and you shoot the guard in the head."); 
    var killPeople = prompt("You're faced with a choice: you can either (a) get out of  the car and start shooting, or (b) drive past the 5 or more soldiers that are getting ready to kill you."); 
    if (killPeople == "a") { 
     alert("The minute you step out of the car you are shredded by machine gun fire."); 
     alert("You have died! Restart game."); 
     window.close(); 
    } else if (killPeople == "b") { 
     alert("You slam on the gas pedal and barely evade the machine gun fire."); 
     alert("You make a U-turn and you get out of the base"); 
     alert("You can see a trail of police cars behind you as you try and get to the country roads."); 
     var shootCops = prompt("Do you (a) put your hand out the window and try and shoot some of them down or (b) stay focused and keep driving?"); 
     if (shootCops == "a") { 
      alert("While trying to fit your arm out the window, you lose control of the car and you swerve into a tree."); 
      alert("You have died! Restart game."); 
      window.close(); 
     } else if (shootCops == "b") { 
      //DO NOTHING// 
     } 
     alert("The police cars keep getting closer and close..."); 
     alert("You keep on looking back, and eventually, you lose control of the car and you crash into a tree."); 
     alert("You have died! Restart game."); 
     window.close(); 
    } 
} else if (enterBase == "b") { 
    alert("You slowly drive up to the fence, and the security guard comes to greet you."); 
    alert("You hand him your ID, he nods and opens the fence."); 
} 

alert("You feel like that was a little too easy. But none the less, you find barrack 212, and you then locate the admin he works in."); 
alert("You spot him through the window, and you retreat to your car so that you can follow him home."); 
alert("Surely enough, after several hours, he goes on his lunch break."); 

var followHim = prompt("You know he'll be back shortly. Do you (a) still follow him, just to be sure, or (b) stay there and watch dumb videos on your phone."); 
if (followHim == "a") { 
    alert("You rev your engine, and slowly follow him to his vehicle. You keep  following him around, and he stops at subway for a meal."); 
    alert("You follow him back to the admin, where he returns to his work."); 
} else if (followHim == "b") { 
    alert("You stay where you are."); 
    alert("After half an hour, he returns but this time with a coffee in hand."); 
} 

alert("You wait a few more hours, and he leaves the admin with his bag. He's done work for the day."); 
alert("You follow him home."); 
alert("You write down his address, and you head back to the hotel."); 
alert("You find yourself in the hotel parking garage."); 
+1

Пожалуйста, удалите всю лишнюю информацию из вашего примера (я сомневаюсь, что «roomService» необходим, чтобы понять вашу проблему или помочь вам). Я также не уверен, что вы подразумеваете под «обработчиком window.close()». Вы установили прослушиватель для события закрытия? –

+1

Лично я думаю, что это решение было бы лучше, если бы вы написали элемент в элемент 'Div' /' Span', а не использовали навязчивое 'alert' каждый раз. ИМО. – Nunners

ответ

4

https://developer.mozilla.org/en-US/docs/Web/API/Window.close

Под Описание:

Этот метод допускается только называется для окон, которые были открыты с помощью сценария с помощью метода window.open. Если окно не было открыто скриптом, в консоли JavaScript появляется следующая ошибка: Сценарии могут не закрывать окна, которые не были открыты скриптом.

1

Это правда, что вы не можете использовать window.open, если окно не было открыто скриптом. Один из способов обойти это с помощью

window.open('', '_self', ''); 
window.close(); 

Это позволит обойти требование в некоторых браузерах, он работает в хром, но я не пробовал другие.

Я действительно рекомендую переосмыслить это. Запись в div или какой-то текстовый ящик будет намного проще для пользователя.

+0

+1 для прохладной находки. Работает в IE (по крайней мере, по крайней мере), в Chrome и Safari. В Firefox нет кубиков. – Adam

Смежные вопросы