javascript游戏的重启按钮

Posted

技术标签:

【中文标题】javascript游戏的重启按钮【英文标题】:Restart button for javascript game 【发布时间】:2020-10-03 20:48:50 【问题描述】:

我有一个 javascript 蛇游戏,它是按照教程制作的。我需要帮助来实现我自己制作的重启按钮

var canvas = document.getElementById('game');
var context = canvas.getContext('2d');
// var startBtn = document.getElementById('startbutton')

var score = 0;

var grid = 16;
var count = 0;

var snake = 
  x: 160,
  y: 160,

  // snake velocity. moves one grid length every frame in either the x or y direction
  dx: grid,
  dy: 0,

  // keep track of all grids the snake body occupies
  cells: [],

  // length of the snake. grows when eating an apple
  maxCells: 4
;
var apple = 
  x: 320,
  y: 320
;

function update(score) 
  document.getElementById("scores").innerhtml = "Score: " + score;



// get random whole numbers in a specific range
// @see https://***.com/a/1527820/2124254
function getRandomInt(min, max) 
  return Math.floor(Math.random() * (max - min)) + min;



// game loop
function loop() 
  update(score)
  requestAnimationFrame(loop);

  // slow game loop to 15 fps instead of 60 (60/15 = 4)
  if (++count < 5) 
    return;

  


  count = 0;
  context.clearRect(0, 0, canvas.width, canvas.height);

  // move snake by it's velocity
  snake.x += snake.dx;
  snake.y += snake.dy;

  // wrap snake position horizontally on edge of screen
  if (snake.x < 0) 
    snake.x = canvas.width - grid;
   else if (snake.x >= canvas.width) 
    snake.x = 0;
  

  // wrap snake position vertically on edge of screen
  if (snake.y < 0) 
    snake.y = canvas.height - grid;
   else if (snake.y >= canvas.height) 
    snake.y = 0;
  

  // keep track of where snake has been. front of the array is always the head
  snake.cells.unshift(
    x: snake.x,
    y: snake.y
  );

  // remove cells as we move away from them
  if (snake.cells.length > snake.maxCells) 
    snake.cells.pop();
  

  // draw apple
  context.fillStyle = 'red';
  context.fillRect(apple.x, apple.y, grid - 1, grid - 1);

  // draw snake one cell at a time
  context.fillStyle = 'green';
  snake.cells.forEach(function(cell, index) 

    // drawing 1 px smaller than the grid creates a grid effect in the snake body so you can see how long it is
    context.fillRect(cell.x, cell.y, grid - 1, grid - 1);

    // snake ate apple
    if (cell.x === apple.x && cell.y === apple.y) 
      snake.maxCells++;
      score++;

      // canvas is 400x400 which is 25x25 grids 
      apple.x = getRandomInt(0, 25) * grid;
      apple.y = getRandomInt(0, 25) * grid;
    

    // check collision with all cells after this one (modified bubble sort)
    for (var i = index + 1; i < snake.cells.length; i++) 

      // snake occupies same space as a body part. reset game
      if (cell.x === snake.cells[i].x && cell.y === snake.cells[i].y) 
        again()
        snake.x = 160;
        snake.y = 160;
        snake.cells = [];
        snake.maxCells = 4;
        snake.dx = grid;
        snake.dy = 0;

        apple.x = getRandomInt(0, 25) * grid;
        apple.y = getRandomInt(0, 25) * grid;
        score = 0
        // startBtn.style.display: 'none';
        // document.getElementById('start')

      
    
  );


// listen to keyboard events to move the snake
document.addEventListener('keydown', function(e) 
  // prevent snake from backtracking on itself by checking that it's 
  // not already moving on the same axis (pressing left while moving
  // left won't do anything, and pressing right while moving left
  // shouldn't let you collide with your own body)

  // left arrow key
  if (e.which === 37 && snake.dx === 0) 
    snake.dx = -grid;
    snake.dy = 0;
  
  // up arrow key
  else if (e.which === 38 && snake.dy === 0) 
    snake.dy = -grid;
    snake.dx = 0;
  
  // right arrow key
  else if (e.which === 39 && snake.dx === 0) 
    snake.dx = grid;
    snake.dy = 0;
  
  // down arrow key
  else if (e.which === 40 && snake.dy === 0) 
    snake.dy = grid;
    snake.dx = 0;
  
);

// start the game
// document.getElementById("scores").innerHTML = score;
function again() 
  document.getElementById("start").addEventListener("click", function restart() 
    requestAnimationFrame(loop);

  )

again()
html,
body 
  height: 100%;
  margin: 0;


body 
  background: black !important;
  display: flex;
  align-items: center;
  justify-content: center;


canvas 
  border: 1px solid white;


a 
  align-items: left;


#cent 
  position: absolute;
  margin-left: 20px;
  margin-right: 20px;
  margin-bottom: 50px;
  bottom: 0;


#startbutton 
  border: none;
  background: none;
  position: absolute;
  top: 50%;
  left: 50%;
  z-index: 1;
  transform: translate(-50%, -50%);
  -webkit-transform: translate(-50%, -50%);
  -moz-transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);


#start 
  border: none;
  background: none;
  position: absolute;
  top: 50%;
  left: 50%;
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<title>RBGamez</title>
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>

<div id="cent">
  <a href="url_for('home')"><button type="button" class="btn btn-primary">Return home</button></a>
</div>
<div style="position: absolute; left: 45%; top: 50px; width:200px; height:100px;">
  <h3>
    <p id="scores" style="color: white;"></p>
  </h3>
</div>

<button type="button" class="btn btn-primary" id="start" onclick="requestAnimationFrame(loop)">Restart</button>
<canvas   id="game"></canvas>

【问题讨论】:

我还想补充一点,每当我按下重新启动按钮时,我目前实现的功能都会不断提高蛇的速度。 您可能应该尽最大努力准确地确定您想要发生的事情以及您希望此新功能在代码中执行的位置,然后编辑您的帖子,以便只包含相关代码。例如。可能你不需要在这个问题中包含 CSS,可能你应该只发布 javascript 的相关部分。 【参考方案1】:

检查这个。通过实施此解决了速度增加的问题:https://***.com/a/10748750/9487478

On 按钮按下again 方法现在被触发。此外,我为applesnake添加了初始值,用于重置对象。

var canvas = document.getElementById('game');
var context = canvas.getContext('2d');
// var startBtn = document.getElementById('startbutton')

var requestId;

var score = 0;

var grid = 16;
var count = 0;

var snake;
var snake_init = 
  x: 160,
  y: 160,

  // snake velocity. moves one grid length every frame in either the x or y direction
  dx: grid,
  dy: 0,

  // keep track of all grids the snake body occupies
  cells: [],

  // length of the snake. grows when eating an apple
  maxCells: 4
;

var apple;
var apple_init = 
  x: 320,
  y: 320
;

function update(score) 
  document.getElementById("scores").innerHTML = "Score: " + score;



// get random whole numbers in a specific range
// @see https://***.com/a/1527820/2124254
function getRandomInt(min, max) 
  return Math.floor(Math.random() * (max - min)) + min;


// game loop
function loop() 
  requestId = undefined;
  start();
  update(score)

  // slow game loop to 15 fps instead of 60 (60/15 = 4)
  if (++count < 5) 
    return;

  


  count = 0;
  context.clearRect(0, 0, canvas.width, canvas.height);

  // move snake by it's velocity
  snake.x += snake.dx;
  snake.y += snake.dy;

  // wrap snake position horizontally on edge of screen
  if (snake.x < 0) 
    snake.x = canvas.width - grid;
   else if (snake.x >= canvas.width) 
    snake.x = 0;
  

  // wrap snake position vertically on edge of screen
  if (snake.y < 0) 
    snake.y = canvas.height - grid;
   else if (snake.y >= canvas.height) 
    snake.y = 0;
  

  // keep track of where snake has been. front of the array is always the head
  snake.cells.unshift(
    x: snake.x,
    y: snake.y
  );

  // remove cells as we move away from them
  if (snake.cells.length > snake.maxCells) 
    snake.cells.pop();
  

  // draw apple
  context.fillStyle = 'red';
  context.fillRect(apple.x, apple.y, grid - 1, grid - 1);

  // draw snake one cell at a time
  context.fillStyle = 'green';
  snake.cells.forEach(function(cell, index) 

    // drawing 1 px smaller than the grid creates a grid effect in the snake body so you can see how long it is
    context.fillRect(cell.x, cell.y, grid - 1, grid - 1);

    // snake ate apple
    if (cell.x === apple.x && cell.y === apple.y) 
      snake.maxCells++;
      score++;

      // canvas is 400x400 which is 25x25 grids 
      apple.x = getRandomInt(0, 25) * grid;
      apple.y = getRandomInt(0, 25) * grid;
    

    // check collision with all cells after this one (modified bubble sort)
    for (var i = index + 1; i < snake.cells.length; i++) 

      // snake occupies same space as a body part. reset game
      if (cell.x === snake.cells[i].x && cell.y === snake.cells[i].y) 
        again()
        snake.x = 160;
        snake.y = 160;
        snake.cells = [];
        snake.maxCells = 4;
        snake.dx = grid;
        snake.dy = 0;

        apple.x = getRandomInt(0, 25) * grid;
        apple.y = getRandomInt(0, 25) * grid;
        score = 0
        // startBtn.style.display: 'none';
        // document.getElementById('start')

      
    
  );


// listen to keyboard events to move the snake
document.addEventListener('keydown', function(e) 
  // prevent snake from backtracking on itself by checking that it's 
  // not already moving on the same axis (pressing left while moving
  // left won't do anything, and pressing right while moving left
  // shouldn't let you collide with your own body)

  // left arrow key
  if (e.which === 37 && snake.dx === 0) 
    snake.dx = -grid;
    snake.dy = 0;
  
  // up arrow key
  else if (e.which === 38 && snake.dy === 0) 
    snake.dy = -grid;
    snake.dx = 0;
  
  // right arrow key
  else if (e.which === 39 && snake.dx === 0) 
    snake.dx = grid;
    snake.dy = 0;
  
  // down arrow key
  else if (e.which === 40 && snake.dy === 0) 
    snake.dy = grid;
    snake.dx = 0;
  
);

function start() 
  if (!requestId) 
    requestId = window.requestAnimationFrame(loop);
  


function stop() 
  if (requestId) 
    window.cancelAnimationFrame(requestId);
    requestId = undefined;
  


// start the game
function again() 
  document.getElementById("start").addEventListener("click", function restart() 
    // -----------------
    // Reset all values.
    // -----------------

    // Let's make a deep copy of snake_init for resetting.
    snake = JSON.parse(JSON.stringify(snake_init));
    apple =  ...apple_init ;
    score = 0;
    count = 0;
    stop();
    start();
  )

again()
<title></title><style>html,
body 
  height: 100%;
  margin: 0;


body 
  background: black !important;
  display: flex;
  align-items: center;
  justify-content: center;


canvas 
  border: 1px solid white;


a 
  align-items: left;


#cent 
  position: absolute;
  margin-left: 20px;
  margin-right: 20px;
  margin-bottom: 50px;
  bottom: 0;


#startbutton 
  border: none;
  background: none;
  position: absolute;
  top: 50%;
  left: 50%;
  z-index: 1;
  transform: translate(-50%, -50%);
  -webkit-transform: translate(-50%, -50%);
  -moz-transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);


#start 
  border: none;
  background: none;
  position: absolute;
  top: 50%;
  left: 50%;
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<title>RBGamez</title>
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>

<div id="cent">
  <a href="url_for('home')"><button type="button" class="btn btn-primary">Return home</button></a>
</div>
<div style="position: absolute; left: 45%; top: 50px; width:200px; height:100px;">
  <h3>
    <p id="scores" style="color: white;"></p>
  </h3>
</div>

<button type="button" class="btn btn-primary" id="start" onclick="again">Restart</button>
<canvas   id="game"></canvas>

【讨论】:

以上是关于javascript游戏的重启按钮的主要内容,如果未能解决你的问题,请参考以下文章

javascript或jquery在不同的按钮点击上更改不同的图像[重复]

Unity- 游戏结束以及重启游戏

你如何使用tkinter按钮重启python程序?

学编程太枯燥,整理11个边玩游戏边学编程网站,越学越上瘾

Django - 修改 Inlineformset 删除按钮

一个家伙与javascript的故事