Osaka expo 2025 snake game
by Tsuneo Yoshioka
HTML
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<div class="main" style="width: 100%; height:100%;">
<canvas style="width: 100vw; height:100vh;border:0; margin:0; padding: 0;"></canvas>
<div style="position: absolute; left:0; top: 0;">
score: <span class="score" style="font-size: xx-large; font-width: bold;"></span>
</div>
</div>
CSS
html{
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
body{
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
JavaScript
$('canvas').attr('width', $(".main").width());
$('canvas').attr('height', $(".main").height());
var canvas = $("canvas")[0];
var context = canvas.getContext('2d');
function drawItem(context, x, y){
context.fillStyle = 'red';
context.beginPath();
let w = 10 + Math.random()*10;
let h = 10 + Math.random()*10;
context.ellipse(x, y, w, h, Math.PI / 4, 0, 2 * Math.PI);
context.fill();
x += Math.random()*3;
y += Math.random()*3;
context.fillStyle = 'white';
context.beginPath();
context.ellipse(x, y, 10, 10, Math.PI / 4, 0, 2 * Math.PI);
context.fill();
context.fillStyle = 'blue';
context.beginPath();
const r = Math.random() * Math.PI * 2;
context.ellipse(x+5*Math.cos(r), y+5*Math.sin(r), 3, 3, Math.PI / 4, 0, 2 * Math.PI);
context.fill();
}
function play()
{
context.clearRect(0, 0, canvas.width, canvas.height);
let x = canvas.width/2;
let y = canvas.height/2;
let dx = 20;
let dy = 0;
let score = 0;
let timer = setInterval(() => {
drawItem(context, x, y);
x += dx;
y += dy;
const p = context.getImageData(x, y, 1, 1).data;
// console.log("p=", p);
if(x<0 || x >= canvas.width || y < 0 || y>=canvas.height || p[0]!==0 || p[1]!==0 || p[2]!==0){
clearInterval(timer);
play();
}
score += 1;
$(".score").text(score);
}, 200);
$(document).on('keydown', (event) => {
if(event.key === 'ArrowRight'){
[dx, dy] = [-dy, dx];
}else if(event.key === 'ArrowLeft'){
[dx, dy] = [dy, -dx];
}
});
}
play();