Sure, I can help you create a simple Snake game using JavaScript and Electron. Here's a step-by-step guide on how to make this game run on your Mac:
- Install Node.js: If you haven't already, download and install Node.js (LTS version) from the official website: https://nodejs.org/en/download/. This will help us create the project using npm.
- Install Electron: Open your terminal and run the following command to install the Electron framework:
npm install electron --save-dev
- Create a new directory for your project and navigate to it using the terminal:
mkdir snake-game
cd snake-game
- Initialize the project with npm:
npm init -y
- Install the necessary dependencies:
npm install --save pixi.js
- Create a new file named
main.js in your project directory and add the following code:
const { app, BrowserWindow } = require('electron');
const { pixi } = require('pixi.js');
function createWindow() {
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: false,
contextIsolation: true,
},
});
win.loadFile('index.html');
}
app.whenReady().then(() => {
createWindow();
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
});
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
- Create a new file named
index.html in your project directory and add the following code:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Snake Game</title>
<link rel="stylesheet" href="styles.css" />
</head>
<body>
<div id="game"></div>
<script src="main.js"></script>
</body>
</html>
- Create a new file named
styles.css in your project directory and add the following code:
body, html {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
}
#game {
position: fixed;
display: block;
}
- Create a new file named
game.js in your project directory and add the following code:
const { app, BrowserWindow } = require('electron');
const { PIXI } = require('pixi.js');
const game = module.exports = {};
game.create = function () {
const canvas = document.getElementById('game');
const renderer = PIXI.autoDetectRenderer(800, 600);
const stage = new PIXI.Stage();
const snake = createSnake();
snake.position.x = canvas.width / 2;
snake.position.y = canvas.height / 2;
stage.addChild(snake);
const gridSize = 20;
const grid = Array.from({ length: gridSize }, () =>
Array.from({ length: gridSize }, () => 0)
);
const app = require('electron').app;
const isLinux = require('electron').isLinux;
const isWindows = require('electron').isWindows;
document.addEventListener('keydown', (e) => {
if (e.keyCode === 37) {
snake.direction.x = -1;
snake.direction.y = 0;
} else if (e.keyCode === 39) {
s