Advanced Gamer's Game
Advanced Gamer's Game
DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" cntent="width=device-width, initial-scale=1.0" />
<titile>HTML Game</title>
<link rel="stylesheet" herf="style.css" />
</head>
<body>
<canvas id="gameCanvas"></canvas>
<script src="main.js"></script>
</body>
</html>
body {
margin: 0;
overflow: hidden;
background-color: black;
}
canvas {
display: block;
}
/ / Canvas Size
canvas.width = 800;
canvas.height = 600;
/ / Player Variables
let player = {
x: 50,
y: 500,
width: 50,
height: 50,
speed: 5,
dx: 0,
dy: 0,
gravity: 0.5,
jumpStrength: -10,
is jumping: false,
};
/ / Keyboard Input
let keys = {};
document.addEventListener( 'keydown ', (e) => (keys[e.key] = true));
document.addEventListener( 'keyup ' , (e) => (keys[e.key] = false));
/ / Game Loop
function gameLoop() {
update();
draw();
AnimationFrame(gameLoop);
}
/ / Update Function
function update() {
/ / Movement Controls
if (keys[ 'ArrowRight ' ]) player.dx = player.speed;
else if (keys[ 'ArrowLeft]) player.dx = player.speed;
else player.dx = 0;
}
/ / Jump Logic
if(keyes[' ']) jump();
/ / Jump Function
function jump() {
if (!player.isJumping) }
player.dy = player.jumpStrength;
player.isJumping = true;
}
}
/ / Draw Function
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
/ / Draw Player
ctx. fillstyle = 'red';
ctx.fillRect(player.x, player.y, player.width, player.height);
/ / Draw Ground
ctx.fillstyle = 'green';
ctx.fillRect(0, canvas.height - 10, canvas.width. 10);
}
/ /Enemy Variables
let enemy = {
x: 400
y: 550
height: 50
width: 50
speed: 2'
direction: 1 // 1 for right, -1 for left
};
/ / Update Enemy
function updateenemy({
enemy.x += enemy.speed * enemy.direction;
/ / Reset Game
function reset game() {
player.x = 50;
player.y = 500;
enemy.x = 400;
enemy.direction = 1;
}
/ / Draw Enemy
function drawEnemy() {
ctx.fillStyle = 'blue';
ctx.fillRect(enemy.x, enemy.width, enemy.height);
}
player.dy += player.gravity;
player.x += player.dx;
player.y += player.dy;
/ / Update Enemy AI
updateEnemy();
}
/ / Player
ctx.fillStyle = 'red';
ctx.fillRect(player.x, player.y, player.width, player.height);
/ / Enemy
drawEnemy();
/ / Ground
ctx.fillStyle = 'green';
ctx.fillRect(0, canvas.height - 10, canvas.width, 10);
}
/ / Sound Effects
let jumpSound = new Audio('assets/sounds/jump.mp3');
let collisionSound = new Audio('assets/sounds/collision.mp3');
/ / Collision Sound
function resetGame() {
collisionSound.play(); / / Play sound when colliding
player.x = 50;
player.y = 500;
enemy.x = 400;
enemy.direction = 1;
}