this is original code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8">…
- User
this is original code:
const tileSize = 50; // Size of each grid cell in pixels const boardRows = 3; const boardCols = 6; const bulletSpeed = 5; // Bullets move faster const playerFireCooldown = 500; // 500ms cooldown between player shots const enemyFireCooldown = 800; // 800ms cooldown for enemy shots let player = { row: 1, col: 0, hp: 10, lastFireTime: 0 }; let bullets = []; let keysPressed = {}; // Load images const playerImage = new Image(); playerImage.src = 'mc.png'; const enemyImage = new Image(); enemyImage.src = 'm.png'; const tileImage = new Image(); tileImage.src = 'tile.png'; class Tile { constructor() { this.health = 10; // Default health of a tile this.image = tileImage; } isWalkable() { return this.health > 0; } takeDamage(amount) { this.health = Math.max(0, this.health - amount); } draw(x, y) { if (this.isWalkable()) { ctx.drawImage(this.image, x, y, tileSize, tileSize); } else { ctx.fillStyle = '#777'; ctx.fillRect(x, y, tileSize, tileSize); } ctx.strokeStyle = '#ccc'; ctx.strokeRect(x, y, tileSize, tileSize); } } class Enemy { constructor(row, col) { this.row = row; this.col = col; this.hp = 10; this.lastFireTime = 0; } draw() { const scale = Math.min(tileSize / enemyImage.width, tileSize / enemyImage.height); const imgWidth = enemyImage.width * scale; const imgHeight = enemyImage.height * scale; ctx.drawImage( enemyImage, this.col * tileSize + (tileSize - imgWidth) / 2, this.row * tileSize + tileSize - imgHeight, imgWidth, imgHeight ); } shoot(currentTime) { if (currentTime - this.lastFireTime >= enemyFireCooldown) { bullets.push({ row: this.row, col: this.col - 1, dir: -1, source: this, damagesTiles: false }); this.lastFireTime = currentTime; } } updatePosition() { if (Math.abs(player.row - this.row) > 0 && Math.random() < 0.1) { this.row += player.row > this.row ? 1 : -1; } } drawBullet(bullet) { if (bullet.dir === -1) { ctx.fillStyle = 'red'; // Enemy bullet color ctx.beginPath(); ctx.moveTo(bullet.col * tileSize + tileSize / 2, bullet.row * tileSize); ctx.lineTo(bullet.col * tileSize, bullet.row * tileSize + tileSize); ctx.lineTo(bullet.col * tileSize + tileSize, bullet.row * tileSize + tileSize); ctx.closePath(); ctx.fill(); } } } let board = Array.from({ length: boardRows }, () => Array.from({ length: boardCols }, () => new Tile())); let enemies = [ new Enemy(0, 3), new Enemy(2, 5) ]; function drawBoard() { ctx.clearRect(0, 0, canvas.width, canvas.height); for (let r = 0; r < boardRows; r++) { for (let c = 0; c < boardCols; c++) { board[r][c].draw(c * tileSize, r * tileSize); } } if (player.hp > 0) { const scale = Math.min(tileSize / playerImage.width, tileSize / playerImage.height); const imgWidth = playerImage.width * scale; const imgHeight = playerImage.height * scale; ctx.drawImage( playerImage, player.col * tileSize + (tileSize - imgWidth) / 2, player.row * tileSize + tileSize - imgHeight, imgWidth, imgHeight ); } enemies.forEach(enemy => enemy.draw()); bullets.forEach(bullet => { if (bullet.col >= 0 && bullet.col < boardCols) { if (bullet.dir === 1) { ctx.fillStyle = 'blue'; ctx.beginPath(); ctx.ellipse( bullet.col * tileSize + tileSize / 2, bullet.row * tileSize + tileSize / 2, tileSize / 4, tileSize / 8, 0, 0, Math.PI * 2 ); ctx.fill(); } else { bullet.source.drawBullet(bullet); } } }); ctx.fillStyle = 'black'; ctx.font = '12px Arial'; ctx.fillText(`Player HP: ${player.hp}`, 10, canvas.height - 20); enemies.forEach((enemy, index) => { ctx.fillText(`Enemy ${index + 1} HP: ${enemy.hp}`, 120, canvas.height - 20 - (15 * index)); }); } function updateEntityPositions() { if (keysPressed['w'] && player.row > 0 && board[player.row - 1][player.col].isWalkable()) { player.row--; keysPressed['w'] = false; } if (keysPressed['s'] && player.row < boardRows - 1 && board[player.row + 1][player.col].isWalkable()) { player.row++; keysPressed['s'] = false; } if (keysPressed['a'] && player.col > 0 && board[player.row][player.col - 1].isWalkable()) { player.col--; keysPressed['a'] = false; } if (keysPressed['d'] && player.col < boardCols / 2 - 1 && board[player.row][player.col + 1].isWalkable()) { player.col++; keysPressed['d'] = false; } } function shoot(currentTime, shooter) { if (shooter.hp > 0 && currentTime - shooter.lastFireTime >= playerFireCooldown) { bullets.push({ row: shooter.row, col: shooter.col + 1, dir: 1, source: shooter, damagesTiles: false }); shooter.lastFireTime = currentTime; } } function updateBullets() { bullets.forEach((bullet, index) => { bullet.col += bullet.dir * bulletSpeed * deltaTime; if (bullet.col < 0 || bullet.col >= boardCols) { bullets.splice(index, 1); } else { const roundedCol = Math.round(bullet.col); if (bullet.row === player.row && roundedCol === player.col && bullet.dir === -1) { player.hp = Math.max(0, player.hp - 1); bullets.splice(index, 1); } enemies.forEach((enemy, enemyIndex) => { if (bullet.row === enemy.row && roundedCol === enemy.col && bullet.dir === 1) { enemy.hp = Math.max(0, enemy.hp - 1); bullets.splice(index, 1); if (enemy.hp === 0) { enemies.splice(enemyIndex, 1); } } }); // Damage tiles only if the bullet is meant to affect them if (bullet.damagesTiles && Math.floor(bullet.col) === roundedCol) { board[bullet.row][roundedCol].takeDamage(1); } } }); } let lastFrameTime = performance.now(); let deltaTime = 0; function gameLoop(currentTime) { deltaTime = (currentTime - lastFrameTime) / 1000; lastFrameTime = currentTime; updateEntityPositions(); updateBullets(); enemies.forEach(enemy => { if (enemy.hp > 0) { enemy.updatePosition(); enemy.shoot(currentTime); } }); drawBoard(); if (player.hp === 0) { alert("You lost!"); resetGame(); } else if (enemies.length === 0) { alert("You won!"); resetGame(); } else { requestAnimationFrame(gameLoop); } } function resetGame() { player = { row: 1, col: 0, hp: 10, lastFireTime: 0 }; bullets = []; keysPressed = {}; board = Array.from({ length: boardRows }, () => Array.from({ length: boardCols }, () => new Tile())); enemies = [ new Enemy(0, 3), new Enemy(2, 5) ]; lastFrameTime = performance.now(); requestAnimationFrame(gameLoop); } document.addEventListener('keydown', (event) => { keysPressed[event.key] = true; if (event.key === ' ') { shoot(Date.now(), player); } }); document.addEventListener('keyup', (event) => { keysPressed[event.key] = false; }); let imagesLoaded = 0; playerImage.onload = () => { imagesLoaded++; if (imagesLoaded === 3) requestAnimationFrame(gameLoop); }; enemyImage.onload = () => { imagesLoaded++; if (imagesLoaded === 3) requestAnimationFrame(gameLoop); }; tileImage.onload = () => { imagesLoaded++; if (imagesLoaded === 3) requestAnimationFrame(gameLoop); }; </script> - Assistant
- User
let;s optimise the coding, I can see the enemy fire time is still out side of the enemy's class. let following the object oriented best practice and put all the attribute related to the enemy within the enemy class
- Assistant
- User
follow similar logic, the player should be in a class and being instantiate as well. play the player as a class and all related attributes within in regarding the bullet speed, it still outside, player and enemy should have different speed let keep trace of the speed in seperate class
- Assistant
- User
messed up, why key press is not defined?
- Assistant
It seems like there might be a misunderstanding. The
keysPressedobject should be defined outside of any function or class so that it's accessible throughout the script. This object is intended to keep track of which keys are currently pressed, enabling movement and actions like shooting.Based on the previous configurations,
keysPressedshould have been defined at a global level as follows:let keysPressed = {};This line should be included near other global variables, at the beginning of the script, just outside any class or function definitions. Make sure that it is not inadvertently modified or missed. Here is the corrected portion for context:
let board = Array.from({ length: boardRows }, () => Array.from({ length: boardCols }, () => new Tile())); let player = new Player(1, 0, playerImage); let bullets = []; let keysPressed = {}; // Keep track of which keys are pressed let enemies = [ new Enemy(0, 3, enemyImage), new Enemy(2, 5, enemyImage) ]; // Remaining logic... - User
full code please
- Assistant
- User
still messed up, the key press is not moving 2 squares for some reason
- Assistant
- User
#gameBoard { font-family: 'Courier New', Courier, monospace; font-size: 16px; resize: none; }
body { background-color: black; }
why is the body blackground colour not showing
- Assistant
The body background color not showing could be due to a few different reasons. Here are some potential causes and steps to troubleshoot:
-
Canvas Covering Entire Viewport:
- If the canvas element covers the entire viewport, it will obscure any background color applied to the body. Ensure that the canvas does not take up the entire space or adjust its size to allow the body background to be visible.
Example CSS to reduce canvas size:
canvas { width: 600px; /* or any appropriate size */ height: 300px; /* other styles */ } -
HTML/CSS Specificity:
- Ensure you haven’t inadvertently set a specific background on the canvas. If so, the canvas itself may need a transparent background to show the body’s color.
-
- User
- Assistant