使用electron为贪吃蛇游戏创建全局快捷键

本文介绍了一个基于Electron框架的简易贪吃蛇游戏实现。通过使用键盘上的上下左右键来控制游戏中的贪吃蛇,玩家可以享受经典的游戏体验。代码中详细展示了如何使用JavaScript和HTML Canvas来创建游戏界面,以及如何通过监听键盘事件来实现贪吃蛇的移动控制。

1037363-20190128112105659-1902933337.gif
上图就是我们的简体版贪吃蛇游戏,我们可以看到使用键盘上面的上下左右可以对贪吃蛇进行控制。
The picture above is our simplified version of Snake Eating Game. We can see that the top
and bottom of the keyboard can control Snake Eating.
所用到的代码如下
The code used is as follows

//这个是对方向进行的控制
//This is direction control.
window.document.onkeydown = function(event) {
  if (!allowPressKeys){
    return null;
  }
  let keyCode;
  if(!event)
  {
    keyCode = window.event.keyCode;
  }
  else
  {
    keyCode = event.keyCode;
  }

  switch(keyCode)
  {
    case 37:
      if (direction !== 'right') {
        moveLeft();
      }
      break;

    case 38:
      if (direction !== 'down'){
        moveUp();
      }
      break;

    case 39:
      if (direction !== 'left'){
        moveRight();
      }
      break;

    case 40:
      if (direction !== 'up'){
        moveDown();
      }
      break;

    default:
      break;
  }
};
app.css
body {
    margin: 1em;
    padding: 0;
    background: #111;
    color: white;
    font-family: helvetica;
  }
  
  canvas {
    border: solid 1px red;
    width: 800px;
    height: 400px;
  }
  
  #scoreboard {
    padding-bottom: 1em;
  }
  
  #label, #score, #bar {
      float: left;
      padding: 8px;
  }
  
  #pause_menu, #restart_menu {
    display: none;
  }
app.js
'use strict';
let currentState;
let canvas, ctx, gridSize, currentPosition, snakeBody, snakeLength, direction, score, suggestedPoint, allowPressKeys, interval, choice;

function updateScore () {
  score = (snakeLength - 3) * 10;
  document.getElementById('score').innerText = score;
}

function hasPoint (element) {
  return (element[0] === suggestedPoint[0] && element[1] === suggestedPoint[1]);
}

function makeFoodItem () {
  suggestedPoint = [Math.floor(Math.random()*(canvas.width/gridSize))*gridSize, Math.floor(Math.random()*(canvas.height/gridSize))*gridSize];
  if (snakeBody.some(hasPoint)) {
    makeFoodItem();
  } else {
    ctx.fillStyle = 'rgb(10,100,0)';
    ctx.fillRect(suggestedPoint[0], suggestedPoint[1], gridSize, gridSize);
  }
}

function hasEatenItself (element) {
  return (element[0] === currentPosition.x && element[1] === currentPosition.y);
}

function leftPosition(){
 return currentPosition.x - gridSize;
}

function rightPosition(){
  return currentPosition.x + gridSize;
}

function upPosition(){
  return currentPosition.y - gridSize;
}

function downPosition(){
  return currentPosition.y + gridSize;
}

function whichWayToGo (axisType) {
  if (axisType === 'x') {
    choice = (currentPosition.x > canvas.width / 2) ? moveLeft() : moveRight();
  } else {
    choice = (currentPosition.y > canvas.height / 2) ? moveUp() : moveDown();
  }
}

function moveUp(){
  if (upPosition() >= 0) {
    executeMove('up', 'y', upPosition());
  } else {
    whichWayToGo('x');
  }
}

function moveDown(){
  if (downPosition() < canvas.height) {
    executeMove('down', 'y', downPosition());
  } else {
    whichWayToGo('x');
  }
}

function moveLeft(){
  if (leftPosition() >= 0) {
    executeMove('left', 'x', leftPosition());
    } else {
    whichWayToGo('y');
  }
}

function moveRight(){
  if (rightPosition() < canvas.width) {
    executeMove('right', 'x', rightPosition());
  } else {
    whichWayToGo('y');
  }
}

function executeMove(dirValue, axisType, axisValue) {
  direction = dirValue;
  currentPosition[axisType] = axisValue;
  drawSnake();
}

function moveSnake(){
  switch (direction) {
    case 'up':
      moveUp();
      break;

    case 'down':
      moveDown();
      break;

    case 'left':
      moveLeft();
      break;

    case 'right':
      moveRight();
      break;
  }
}

function restart () {
    document.getElementById('play_menu').style.display='block';
    document.getElementById('pause_menu').style.display='none';
    document.getElementById('restart_menu').style.display='none';
    pause();
    start();
}

function pause(){
    document.getElementById('play_menu').style.display='none';
    document.getElementById('pause_menu').style.display='block';
  clearInterval(interval);
  allowPressKeys = false;
}

function play(){
    document.getElementById('play_menu').style.display='block';
    document.getElementById('pause_menu').style.display='none';
  interval = setInterval(moveSnake,100);
  allowPressKeys = true;
}

function gameOver(){
  pause();
  window.alert('Game Over. Your score was ' + score);
  ctx.clearRect(0,0, canvas.width, canvas.height);
    document.getElementById('play_menu').style.display='none';
  document.getElementById('restart_menu').style.display='block';
}

function drawSnake() {
  if (snakeBody.some(hasEatenItself)) {
    gameOver();
    return false;
  }
  snakeBody.push([currentPosition.x, currentPosition.y]);
  ctx.fillStyle = 'rgb(200,0,0)';
  ctx.fillRect(currentPosition.x, currentPosition.y, gridSize, gridSize);
  if (snakeBody.length > snakeLength) {
    let itemToRemove = snakeBody.shift();
    ctx.clearRect(itemToRemove[0], itemToRemove[1], gridSize, gridSize);
  }
  if (currentPosition.x === suggestedPoint[0] && currentPosition.y === suggestedPoint[1]) {
    makeFoodItem();
    snakeLength += 1;
    updateScore();
  }
}

window.document.onkeydown = function(event) {
  if (!allowPressKeys){
    return null;
  }
  let keyCode;
  if(!event)
  {
    keyCode = window.event.keyCode;
  }
  else
  {
    keyCode = event.keyCode;
  }

  switch(keyCode)
  {
    case 37:
      if (direction !== 'right') {
        moveLeft();
      }
      break;

    case 38:
      if (direction !== 'down'){
        moveUp();
      }
      break;

    case 39:
      if (direction !== 'left'){
        moveRight();
      }
      break;

    case 40:
      if (direction !== 'up'){
        moveDown();
      }
      break;

    default:
      break;
  }
};

function start () {
  ctx.clearRect(0,0, canvas.width, canvas.height);
  currentPosition = {'x':50, 'y':50};
  snakeBody = [];
  snakeLength = 3;
  updateScore();
  makeFoodItem();
  drawSnake();
  direction = 'right';
  play();
}

function initialize () {
  canvas = document.querySelector('canvas');
  ctx = canvas.getContext('2d');
  gridSize = 10;
  start();
}

function togglePauseState () {
  if (currentState) {
    if (currentState === 'play') {
      pause();
        currentState = 'pause';
    } else {
      play();
        currentState = 'play';
    }
   } else {
     pause();
     currentState = 'play';
   }
}

const ipcRenderer = require('electron').ipcRenderer;

function togglePauseState () {
  if (currentState) {
    if (currentState === 'play') {
      pause();
      currentState = 'pause';
    } else {
      play();
      currentState = 'play';
    }
  } else {
    pause();
    currentState = 'play';
    }
}

ipcRenderer.on('togglePauseState', togglePauseState);

window.onload = initialize;
<html>
  <head>
    <title>Snake</title>
    <link href="app.css" rel="stylesheet" />
    <script src="app.js"></script>
  </head>
  <body>
    <div id="scoreboard">
      <span id="label">Score:</span>
      <span id="score"></span>
            <div id="bar">
                    <div id="play_menu">
                    <button onclick="pause();">Pause</button>
                    </div>
                  <div id="pause_menu">
                    <button onclick="play();">Resume</button>
                        <button onclick="restart();">Restart</button>
                  </div>
                  <div id="restart_menu">
                    <button onclick="restart();">Restart</button>
                  </div>
                </div>
            </div>
    </div>
    <canvas></canvas>
  </body>
</html>
main.js
'use strict';

const {app, globalShortcut, BrowserWindow} = require('electron');

let mainWindow = null;

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') app.quit();
});

app.on('ready', () => {
  mainWindow = new BrowserWindow({
    width: 840,
    height: 470,
    useContentSize: true
  });
  mainWindow.loadURL(`file://${__dirname}/index.html`);
  mainWindow.on('closed', () => { mainWindow = null; });
  const pauseKey = globalShortcut.register('CommandOrControl+P', () => {
    mainWindow.webContents.send('togglePauseState');
  });
  if (!pauseKey) alert('You will not be able to pause the game from the keyboard');
});

app.on('will-quit', () => {
  globalShortcut.unregister('CommandOrControl+P');
});
{ "name": "snake-electron", "version": "1.0.0", "description": "The Snake game, built with Electron for the book 'Cross Platform Desktop Applications'", "main": "main.js", "scripts": { "start": "node_modules/.bin/electron .", "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [ "electron", "keyboard", "shortcuts" ], "author": "Paul Jensen ", "license": "MIT", "dependencies": { "electron-prebuilt": "^1.2.5" } }

本文的例子学习自 <<跨平台桌面应用开发基于Electron与NW.js>>这本书
by要学的东西很多,我还差很远

转载于:https://www.cnblogs.com/smart-girl/p/10329453.html

一、数据采集层:多源人脸数据获取 该层负责从不同设备 / 渠道采集人脸原始数据,为后续模型训练与识别提供基础样本,核心功能包括: 1. 多设备适配采集 实时摄像头采集: 调用计算机内置摄像头(或外接 USB 摄像头),通过OpenCV的VideoCapture接口实时捕获视频流,支持手动触发 “拍照”(按指定快捷键如Space)或自动定时采集(如每 2 秒采集 1 张),采集时自动框选人脸区域(通过Haar级联分类器初步定位),确保样本聚焦人脸。 支持采集参数配置:可设置采集分辨率(如 640×480、1280×720)、图像格式(JPG/PNG)、单用户采集数量(如默认采集 20 张,确保样本多样性),采集过程中实时显示 “已采集数量 / 目标数量”,避免样本不足。 本地图像 / 视频导入: 支持批量导入本地人脸图像文件(支持 JPG、PNG、BMP 格式),自动过滤非图像文件;导入视频文件(MP4、AVI 格式)时,可按 “固定帧间隔”(如每 10 帧提取 1 张图像)或 “手动选择帧” 提取人脸样本,适用于无实时摄像头场景。 数据集对接: 支持接入公开人脸数据集(如 LFW、ORL),通过预设脚本自动读取数据集目录结构(按 “用户 ID - 样本图像” 分类),快速构建训练样本库,无需手动采集,降低系统开发与测试成本。 2. 采集过程辅助功能 人脸有效性校验:采集时通过OpenCV的Haar级联分类器(或MTCNN轻量级模型)实时检测图像中是否包含人脸,若未检测到人脸(如遮挡、侧脸角度过大),则弹窗提示 “未识别到人脸,请调整姿态”,避免无效样本存入。 样本标签管理:采集时需为每个样本绑定 “用户标签”(如姓名、ID 号),支持手动输入标签或从 Excel 名单批量导入标签(按 “标签 - 采集数量” 对应),采集完成后自动按 “标签 - 序号” 命名文件(如 “张三
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值