Game
Game
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Swordigo-like Game</title>
<style>
body, html {
margin: 0;
padding: 0;
overflow: hidden;
}
canvas {
display: block;
background-color: #87CEEB; /* Sky Blue */
}
</style>
</head>
<body>
<canvas id="gameCanvas"></canvas>
<script>
const canvas = document.getElementById("gameCanvas");
const ctx = canvas.getContext("2d");
// Canvas setup
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// Game Variables
const gravity = 0.5;
let player = {
x: 50,
y: 50,
width: 50,
height: 50,
color: 'red',
speedX: 0,
speedY: 0,
jumping: false,
moveSpeed: 5,
health: 3,
score: 0,
sword: {
width: 20,
height: 5,
active: false,
direction: 'right' // Track which way the player is facing
}
};
// Platforms
let platforms = [
{ x: 0, y: canvas.height - 50, width: canvas.width, height: 50, color:
'green' },
{ x: 200, y: canvas.height - 150, width: 200, height: 20, color:
'green' }
];
// Enemies
let enemies = [
{ x: 300, y: canvas.height - 150 - 40, width: 40, height: 40, color:
'blue', speed: 2, alive: true }
];
// Collectibles
let collectibles = [
{ x: 150, y: canvas.height - 100, width: 20, height: 20, color:
'yellow', collected: false }
];
// Jumping
if (keys["ArrowUp"] && !player.jumping) {
player.jumping = true;
player.speedY = -10;
}
player.speedY += gravity;
player.x += player.speedX;
player.y += player.speedY;
function drawSword() {
if (player.sword.active) {
ctx.fillStyle = 'silver';
let swordX = player.x + player.width; // Default sword position
(right side)
if (player.sword.direction === 'left') {
swordX = player.x - player.sword.width; // Sword on the left
when facing left
}
ctx.fillRect(swordX, player.y + player.height / 2,
player.sword.width, player.sword.height);
}
}
// Move enemies
function moveEnemies() {
enemies.forEach(enemy => {
if (enemy.alive) {
enemy.x += enemy.speed;
if (enemy.x + enemy.width > 400 || enemy.x < 200) {
enemy.speed *= -1; // Reverse direction when hitting
platform edges
}
}
});
}
// Draw collectibles
function drawCollectibles() {
collectibles.forEach(collectible => {
if (!collectible.collected) {
ctx.fillStyle = collectible.color;
ctx.fillRect(collectible.x, collectible.y, collectible.width,
collectible.height);
}
});
}
movePlayer();
moveEnemies();
drawPlatforms();
drawPlayer();
drawSword();
drawEnemies();
drawCollectibles();
drawHUD();
checkSwordHit();
checkPlayerEnemyCollision();
checkCollectibles();
requestAnimationFrame(gameLoop);
}