Skip to content

Instantly share code, notes, and snippets.

@mexelout
Created October 5, 2017 20:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mexelout/e85fbc43a00f6ac009428fd4faf32397 to your computer and use it in GitHub Desktop.
Save mexelout/e85fbc43a00f6ac009428fd4faf32397 to your computer and use it in GitHub Desktop.
javascript game
window.onload = function() {
var canvas = document.createElement('canvas');
canvas.width = 640;
canvas.height = 480;
document.body.appendChild(canvas);
var context = canvas.getContext('2d');
var player = Object();
var obstacles = [Object(), Object(), Object()];
var init = function() {
player.y = 0;
player.fall = 0;
player.velocity = 0;
obstacles.some(function(obstacle, index) {
obstacle.x = 640 + index * 300;
});
}
init();
var space = false;
document.onkeydown = function() {
if (event.keyCode == 32) space = true
}
document.onkeyup = function() {
if (event.keyCode == 32) space = false
}
var game = function() {
// ジャンプ可能 & ジャンプキー推した
if(player.y == 0 && space) {
player.fall = 20;
}
// 落ちる速度上昇
player.fall -= 1.5;
// playerを落とす
player.y += player.fall;
// 地面にめり込んだ?
if(player.y < 0) {
player.y = 0;
player.fall = 0;
}
obstacles.some(function(obstacle, index) {
obstacle.x -= 10;
if(30 < obstacle.x + 40 &&
player.y < 40 &&
90 > obstacle.x &&
player.y + 60 > 0) {
init();
}
if(obstacle.x < -40) {
obstacle.x = 700 + Math.random() * 500;
}
})
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillStyle = 'rgb(0, 198, 0)';
context.fillRect(0, 400, 640, 80);
context.fillStyle = 'rgb(0, 0, 198)';
context.fillRect(30, 340 - player.y, 60, 60);
obstacles.some(function(obstacle, index) {
context.fillStyle = 'rgb(198, 0, 0)';
context.fillRect(obstacle.x, 360, 40, 40);
});
setTimeout(game, 50);
}
setTimeout(game, 50);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment