Hello there! I would want you to code me a simple game in ONLY HTML code. The game is simple: There is chessboard, and a cube controlled by the player with the arrow keys. It moves on the chessboard. There is also another snake, but a simple ''algorithm''. There is also an apple in the middle, which is the goal for both the snakes. Every 5 seconds, there is the name of a chess piece labeled at the top, and it determines which characteristics you can use to go on the chess board. There is also a score.
Assistant
Hello! I'd be happy to help you create a simple game as described. Since HTML alone isn't sufficient for interactive functionality, we'll use HTML combined with JavaScript and CSS all within a single HTML file. Below is the complete code for your game:
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Chessboard Cube Game</title>
<style>
body {
text-align: center;
font-family: Arial, sans-serif;
}
#chessboard {
display: grid;
grid-template-columns: repeat(8, 60px);
grid-template-rows: repeat(8, 60px);
margin: 20px auto;
border: 2px solid #333;
}
.cell {
width: 60px;
height: 60px;
box-sizing: border-box;
}
.white {
background-color: #f0d9b5;
}
.black {
background-color: #b58863;
}
.player, .snake {
width: 50px;
height: 50px;
margin: 5px auto;
border-radius: 5px;
position: relative;
z-index: 2;
}
.player {
background-color: blue;
}
.snake {
background-color: red;
}
#apple {
width: 50px;
height: 50px;
margin: 5px auto;
background-color: green;
border-radius: 50%;
position: relative;
z-index: 1;
}
#info {
margin: 10px;
}
#chess-piece {
font-weight: bold;
font-size: 20px;
}
</style>
</head>
<body>
<h1>Chessboard Cube Game</h1>
<div id="info">
<span>Current Chess Piece: <span id="chess-piece">None</span></span> |
<span>Score: <span id="score">0</span></span>
</div>
<div id="chessboard"></div>
<script>
const chessboard = document.getElementById('chessboard');
const chessPieceDisplay = document.getElementById('chess-piece');
const scoreDisplay = document.getElementById('score');
const boardSize = 8;
let score = 0;
// Initialize chessboard
for (let row = 0; row < boardSize; row++) {
for (let col = 0; col < boardSize; col++) {
const cell = document.createElement('div');
cell.classList.add('cell');
cell.classList.add((row + col) % 2 === 0 ? 'white' : 'black');
cell.dataset.row = row;
cell.dataset.col = col;
chessboard.appendChild(cell);
}
}
// Player and Snake positions
let playerPos = { row: 0, col: 0 };
let snakePos = { row: boardSize - 1, col: boardSize - 1 };
const applePos = { row: Math.floor(boardSize / 2), col: Math.floor(boardSize / 2) };
// Current chess piece
const chessPieces = ['King', 'Queen', 'Rook', 'Bishop', 'Knight', 'Pawn'];
let currentChessPiece = 'None';
// Movement rules based on chess piece
const movementRules = {
'King': [[-1, -1], [-1,0], [-1,1], [0,-1], [0,1], [1,-1], [1,0], [1,1]],
'Queen': [[-1, -1], [-1,0], [-1,1], [0,-1], [0,1], [1,-1], [1,0], [1,1]],
'Rook': [[-1,0], [0,-1], [0,1], [1,0]],
'Bishop': [[-1, -1], [-1,1], [1,-1], [1,1]],
'Knight': [[-2,-1], [-2,1], [-1,-2], [-1,2], [1,-2], [1,2], [2,-1], [2,1]],
'Pawn': [[-1,0]] // Simple upward movement
};
// Initialize positions
function render() {
// Clear all positions
document.querySelectorAll('.player, .snake, #apple').forEach(el => el.remove());
// Render apple
const appleCell = getCell(applePos.row, applePos.col);
appleCell.appendChild(createElement('div', 'apple'));
// Render player
const playerCell = getCell(playerPos.row, playerPos.col);
playerCell.appendChild(createElement('div', 'player'));
// Render snake
const snakeCell = getCell(snakePos.row, snakePos.col);
snakeCell.appendChild(createElement('div', 'snake'));
}
function createElement(tag, className) {
const el = document.createElement('div');
if (className === 'apple') {
el.id = 'apple';
} else {
el.classList.add(className);
}
return el;
}
function getCell(row, col) {
return document.querySelector(`.cell[data-row='${row}'][data-col='${col}']`);
}
// Handle player movement
document.addEventListener('keydown', (e) => {
let direction;
switch(e.key) {
case 'ArrowUp': direction = 'up'; break;
case 'ArrowDown': direction = 'down'; break;
case 'ArrowLeft': direction = 'left'; break;
case 'ArrowRight': direction = 'right'; break;
default: return;
}
let delta;
switch(direction) {
case 'up': delta = [-1,0]; break;
case 'down': delta = [1,0]; break;
case 'left': delta = [0,-1]; break;
case 'right': delta = [0,1]; break;
}
if (currentChessPiece !== 'None') {
const allowedMoves = movementRules[currentChessPiece];
const moveAllowed = allowedMoves.some(m => m[0] === delta[0] && m[1] === delta[1]);
if (!moveAllowed) {
return; // Move not allowed by current chess piece
}
}
const newRow = playerPos.row + delta[0];
const newCol = playerPos.col + delta[1];
if (isValid(newRow, newCol)) {
playerPos = { row: newRow, col: newCol };
checkCollision();
render();
}
});
function isValid(row, col) {
return row >=0 && row < boardSize && col >=0 && col < boardSize;
}
// Simple snake AI: move towards the apple
function moveSnake() {
if (snakePos.row < applePos.row) {
snakePos.row +=1;
} else if (snakePos.row > applePos.row) {
snakePos.row -=1;
}
if (snakePos.col < applePos.col) {
snakePos.col +=1;
} else if (snakePos.col > applePos.col) {
snakePos.col -=1;
}
checkCollision();
render();
}
// Check for collisions
function checkCollision() {
// Player or snake reached apple
if ((playerPos.row === applePos.row && playerPos.col === applePos.col) ||
(snakePos.row === applePos.row && snakePos.col === applePos.col)) {
score +=1;
scoreDisplay.textContent = score;
// Optionally, relocate the apple
// applePos.row = Math.floor(Math.random() * boardSize);
// applePos.col = Math.floor(Math.random() * boardSize);
}
// Player collides with snake
if (playerPos.row === snakePos.row && playerPos.col === snakePos.col) {
alert('Game Over! Your score: ' + score);
// Reset game
playerPos = { row: 0, col: 0 };
snakePos = { row: boardSize -1, col: boardSize -1 };
score = 0;
scoreDisplay.textContent = score;
}
}
// Update chess piece every 5 seconds
function updateChessPiece() {
currentChessPiece = chessPieces[Math.floor(Math.random() * chessPieces.length)];
chessPieceDisplay.textContent = currentChessPiece;
}
// Initial render
render();
updateChessPiece();
// Set intervals
setInterval(moveSnake, 1000); // Move snake every second
setInterval(updateChessPiece, 5000); // Change chess piece every 5 seconds
</script>
</body>
</html>
Explanation of the Code
HTML Structure:
The <div id="chessboard"></div> serves as the container for the chessboard grid.
The <div id="info"> displays the current chess piece and the player's score.
CSS Styling:
The chessboard is styled as an 8x8 grid with alternating colors to mimic a real chessboard.
Player, snake, and apple are represented with colored divs positioned within the grid cells.
JavaScript Functionality:
Initialization:
Creates an 8x8 grid representing the chessboard.
Sets initial positions for the player (blue cube), snake (red), and apple (green).
Rendering:
The render function updates the positions of the player, snake, and apple on the board.
Player Movement:
Listens for arrow key presses to move the player.
Movement is restricted based on the current chess piece's movement rules.
Snake AI:
The snake moves towards the apple every second using a simple algorithm.
Collision Detection:
Increments the score if the player or snake reaches the apple.
Ends the game if the player collides with the snake.
Chess Piece Update:
Every 5 seconds, a random chess piece is selected, and its movement rules are applied to the player's possible moves.
How to Use
Save the Code:
Copy the entire code above and paste it into a text editor.
Save the file with a .html extension, for example, chessboard_game.html.
Run the Game:
Open the saved HTML file in a web browser (e.g., Chrome, Firefox).
Game Controls:
Use the arrow keys on your keyboard to move the blue cube (player) around the chessboard.
Every 5 seconds, a chess piece is displayed, which restricts your movement based on that piece's movement rules.
Avoid the red snake and try to reach the green apple to earn points.
Notes and Potential Improvements
Chess Piece Movements:
Currently, movements are limited to one step based on the chess piece. For example, the Queen can move one step in any direction. For a more accurate representation, you could allow multiple steps based on each piece's traditional movement.
Apple Relocation:
After the apple is eaten, it stays in the center. You might want to randomize its position to increase the game's challenge.
Snake AI:
The snake uses a simple logic to move towards the apple. Enhancing the AI can make the game more challenging.
Visual Enhancements:
Adding images or more sophisticated graphics can improve the game's appearance.
Feel free to modify and enhance the game further as per your requirements. Enjoy coding and playing your game!