Skip to content

Instantly share code, notes, and snippets.

@phuctvt
Created January 16, 2020 09:49
Show Gist options
  • Save phuctvt/4c4d1993c87e4c4e9a191333d4f037ca to your computer and use it in GitHub Desktop.
Save phuctvt/4c4d1993c87e4c4e9a191333d4f037ca to your computer and use it in GitHub Desktop.
Game
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="style.css">
<title>Document</title>
</head>
<body>
<canvas id="game" width="150" height="150"></canvas>
<script src="script.js"></script>
</body>
</html>
const CODE_ARROW_UP = 'ArrowUp';
const CODE_ARROW_RIGHT = 'ArrowRight';
const CODE_ARROW_DOWN = 'ArrowDown';
const CODE_ARROW_LEFT = 'ArrowLeft';
class Position {
constructor() {
this.x = 0;
this.y = 0;
}
}
class Character {
constructor(ctx) {
this.ctx = ctx;
this.position = new Position();
this.MOVEMENT_SIZE = 5;
}
update(code) {
if (code === CODE_ARROW_UP) {
this.position.y -= this.MOVEMENT_SIZE;
} else if (code === CODE_ARROW_DOWN) {
this.position.y += this.MOVEMENT_SIZE;
} else if (code === CODE_ARROW_LEFT) {
this.position.x -= this.MOVEMENT_SIZE;
} else if (code === CODE_ARROW_RIGHT) {
this.position.x += this.MOVEMENT_SIZE;
}
}
draw() {
this.ctx.fillStyle = 'rgb(200, 0, 0)';
this.ctx.fillRect(this.position.x, this.position.y, 20, 20);
console.log(this.position.x, this.position.y, 20, 20);
}
}
class Game {
constructor() {
this.canvas = document.getElementById('game');
this.ctx = this.canvas.getContext('2d');
this.character = new Character(this.ctx);
this.loop();
}
onKeyDown(e) {
console.log(e.code)
this.character.update(e.code);
}
loop() {
setInterval(() => {
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
this.character.draw();
}, 33);
}
}
function main() {
let game = new Game();
document.onkeydown = e => game.onKeyDown(e);
}
main();
#game {
border: 1px solid;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment