*
{
font-family: emulogic;
padding: 0px;
margin: 0px;
}
@font-face
{
font-family: emulogic;
src: url("../fonts/emulogic.ttf");
/*
Note: Firefox requires that the font file
be in the same folder as the CSS file.
If you are using Firefox, copy the emulogic.ttf font
into the src folder and use this src property:
src: url("../fonts/emulogic.ttf");
*/
}
h1
{
text-align: center;
font-size: 24px;
color: #FFBF00;
padding-bottom: 20px;
text-shadow: 3px 3px lime;
-webkit-text-stroke: 1px #000;
-moz-text-stroke: 1px #000;
text-stroke: 1px #000;
}
p
{
text-align: center;
font-size: 12px;
padding-bottom: 20px;
color: #FFBF00;
}
input
{
font-size: 15px;
background-color: black;
color: #FFBF00;
width: 75px;
padding: 5px 10px;
border: 1px solid lime;
-webkit-border-radius: 10px;
-moz-border-radius: 10px;
border-radius: 10px;
}
button
{
font-size: 15px;
color: #FFBF00;
padding: 5px 10px;
border: 2px solid lime;
-webkit-border-radius: 10px;
-moz-border-radius: 10px;
border-radius: 10px;
background: black;
-webkit-user-select: none;
-moz-user-select: none;
user-select: none;
}
button:hover
{
background-color: #FFBF00;
color: #000;
}
button:active
{
background-color: #9e7606;
color: #000;
}
#game
{
margin: 0px auto;
width: 330px;
height: auto;
padding: 15px;
border: black;
background:-webkit-linear-gradient(300deg, #588063, #000);
background:-moz-linear-gradient(top, #588063, #000);
background: linear-gradient(top, #588063, #000);
-webkit-box-shadow: 5px 5px 5px rgba(0, 0, 0, 0.5);
-moz-box-shadow: 5px 5px 5px rgba(0, 0, 0, 0.5);
box-shadow: 5px 5px 5px rgba(0, 0, 0, 0.5);
-webkit-border-radius: 10px;
-moz-border-radius: 10px;
border-radius: 10px;
}
#stage
{
margin: 0px auto;
width: 300px;
height: 300px;
position: relative;
-webkit-box-shadow: 5px 5px 5px rgba(0, 0, 0, 0.5);
-moz-box-shadow: 5px 5px 5px rgba(0, 0, 0, 0.5);
box-shadow: 5px 5px 5px rgba(0, 0, 0, 0.5);
margin-bottom: 20px;
border: 1px solid lime;
}
#background
{
width: 300px;
height: 300px;
position: absolute;
top: 0px;
left: 0px;
background-image: url(https://i.ibb.co/n0DkPx2/background.png);
}
#cannon
{
width: 20px;
height: 20px;
position: absolute;
top: 270px;
left: 140px;
background-image: url(https://i.ibb.co/6wghWkq/cannon.png);
}
#alien
{
width: 20px;
height: 20px;
position: absolute;
top: 20px;
left: 80px;
background-image: url(https://i.ibb.co/7nx5Kxm/alien.png);
}
#missile
{
width: 10px;
height: 10px;
position: absolute;
top: 240px;
left: 145px;
background-image: url(https://i.ibb.co/qRTtRvB/missile.png);
}
#explosion
{
width: 20px;
height: 20px;
position: absolute;
top: 0px;
left: 0px;
background-image: url(https://i.ibb.co/cc4mwW2/explosion.png);
display: none;
}
<!doctype html>
<meta charset="utf-8">
<title>Alien Attack</title>
<link rel="stylesheet" href="alienAttack.css">
<section id="game">
<h1>Alien Attack!</h1>
<div id="stage">
<div id="background"></div>
<div id="cannon"></div>
<div id="missile"></div>
<div id="alien"></div>
<div id="explosion"></div>
</div>
<p id="output">Enter the X and Y position (0-300), then click fire.</p>
<input id="inputX" type="text" placeholder="X…" autofocus>
<input id="inputY" type="text" placeholder="Y…">
<button>fire!</button>
</section>
<script>
//Game variables
var alienX = Math.floor(Math.random() * 280);
var alienY = 20;
var guessX = 0;
var guessY = 0;
var shotsRemaining = 8;
var shotsMade = 0;
var gameState = "";
var gameWon = false;
//The game objects
var cannon = document.querySelector("#cannon");
var alien = document.querySelector("#alien");
var missile = document.querySelector("#missile");
var explosion = document.querySelector("#explosion");
//The input and output fields
var inputX = document.querySelector("#inputX");
var inputY = document.querySelector("#inputY");
var output = document.querySelector("#output");
//The button
var button = document.querySelector("button");
button.style.cursor = "pointer";
button.addEventListener("click", clickHandler, false);
//Listen for enter key presses
window.addEventListener("keydown", keydownHandler, false);
function clickHandler()
{
validateInput();
}
function keydownHandler(event)
{
if(event.keyCode === 13)
{
validateInput();
}
}
function validateInput()
{
guessX = parseInt(inputX.value);
guessY = parseInt(inputY.value);
if(isNaN(guessX) || isNaN(guessY) )
{
output.innerHTML = "Please enter a number.";
}
else if(guessX > 300 || guessY > 300)
{
output.innerHTML = "Please enter a number less than 300.";
}
else
{
playGame();
}
}
function render()
{
//Position the alien
alien.style.left = alienX + "px";
alien.style.top = alienY + "px";
//Position the cannon
cannon.style.left = guessX + "px";
//Position the missile
missile.style.left = guessX + "px";
missile.style.top = guessY + "px";
//display the explosion and hide the
//alien if it's been destroyed
if(gameWon)
{
//Display the explosion
explosion.style.display = "block";
explosion.style.left = alienX + "px";
explosion.style.top = alienY + "px";
//Hide the alien
alien.style.display = "none";
//Hide the missile
missile.style.display = "none";
}
}
function playGame()
{
shotsRemaining = shotsRemaining - 1;
shotsMade = shotsMade + 1;
gameState
= " Shots: " + shotsMade + ", Remaining: " + shotsRemaining;
//Find out whether the player's x and y guesses are inside
//The alien's area
if(guessX >= alienX && guessX <= alienX + 20)
{
//Yes, it's within the X range, so now let's
//check the Y range
if(guessY >= alienY && guessY <= alienY + 20)
{
//It's in both the X and Y range, so it's a hit!
gameWon = true;
endGame();
}
}
else
{
output.innerHTML = "Miss!" + "<br>" + gameState;
//Check for the end of the game
if (shotsRemaining < 1)
{
endGame();
}
}
//Update the alien's position if the
//game hasn't yet been won
if(!gameWon)
{
//Update the alien's X position
alienX = Math.floor(Math.random() * 281);
//Add 30 to the new Y position so that
//the alien moves down
alienY += 30;
}
//Render the new game state
render();
console.log("X: " + alienX);
console.log("Y: " + alienY);
}
function endGame()
{
if(gameWon)
{
output.innerHTML
= "Hit! You saved the earth!" + "<br>"
+ "It only took you " + shotsMade + " shots.";
}
else
{
output.innerHTML
= "You lost!" + "<br>"
+ "The earth has been invaded!";
}
//Disable the button
button.removeEventListener("click", clickHandler, false);
button.disabled = true;
//Disable the enter key
window.removeEventListener("keydown", keydownHandler, false);
//Disable the input fields
inputX.disabled = true;
inputY.disabled = true;
}
</script>
Я спросил, почему игра требует дополнительного щелчка мыши, чтобы зарегистрировать взрыв после того, как первое предположение неверно. Я также обнаружил, что игра не проверяет наличие отрицательные числа либо для удержания корабля в стадии игры. и, наконец, похоже, есть проблема с изображением, которое может вырезать инопланетянина, но не зарегистрировать попадание. поэтому, чтобы ответить на мой собственный вопрос, я обнаружил, что добавление -10 в статус if (guessX> = alienX - 10 && guessX <= alienX + 20) к проверке на столкновение устраняет проблему касания изображений, но не регистрации попадания. а дополнительный щелчок для регистрации взрыва после первого предположения можно исправить, переместив все операторы check if из функции playgame () в функцию render (), это заставит инопланетянина обнаруживать более точные изображения и вызывать взрыв без требуется дополнительный щелчок после первого предположения. и, наконец, добавив else if (guessx <0 || guessy <0) {output.inner HTML = "Пожалуйста, введите число больше 0";} после else if (guessx> 300 || guessy> 300) { output.inner HTML = "Пожалуйста, введите число меньше 300.";} исправляет ошибку, позволяющую кому-то вводить отрицательные числа. Я также меняю значение с 300 на 280, чтобы сохранить все изображение на сцене, так как изображение 20 пикселей в ширину. так что, если вы пытаетесь учиться на основе игрового дизайна с html и javascript. и сбиты с толку одной из первых игр рассмотрим эти проблемы