###前提・実現したいこと
HTMLでゲームのコードを書いたのですが、こんな風になりました
###該当のソースコード
lang
1<!DOCTYPE html> 2<html> 3<head> 4<title>SnakeBite</title> 5<meta http-equiv="X-UA-Compatible" content="IE=edge" /> 6<script type="text/javascript"> 7var W, H, S = 20; 8var snake = [], foods = []; 9var keyCode = 0; 10var point = 0; 11var timer = NaN; 12var ctx; 13// Pointオブジェクト 14function Point(x, y) { 15this.x = x; 16this.y = y; 17} 18// 初期化関数 19function init() { 20var canvas = document.getElementById('field'); 21W = canvas.width / S; 22H = canvas.height / S; 23ctx = canvas.getContext('2d'); 24ctx.font = "20px sans-serif"; 25// 蛇の初期化 26snake.push(new Point(W / 2, H / 2)); 27// 餌の初期化 28for (var i = 0 ; i < 10 ; i++) { 29addFood(); 30} 31timer = setInterval("tick()", 200); 32window.onkeydown = keydown; 33} 34// 餌の追加 35function addFood() { 36while (true) { 37var x = Math.floor(Math.random() * W); 38var y = Math.floor(Math.random() * H); 39if (isHit(foods, x, y) || isHit(snake, x, y)) { 40continue; 41} 42foods.push(new Point(x, y)); 43break; 44} 45} 46// 衝突判定 47function isHit(data, x, y) { 48for (var i = 0 ; i < data.length ; i++) { 49if (data[i].x == x && data[i].y == y) { 50return true; 51} 52} 53return false; 54} 55function moveFood(x, y) { 56foods = foods.filter(function (p) { 57return (p.x != x || p.y != y); 58}); 59addFood(); 60} 61function tick() { 62var x = snake[0].x; 63var y = snake[0].y; 64switch (keyCode) { 65case 37: x--; break; // 左 66case 38: y--; break; // 上 67case 39: x++; break; // 右 68case 40: y++; break; // 下 69default: paint(); return; 70} 71// 自分 or 壁に衝突? 72if (isHit(snake, x, y) || x < 0 || x >= W || y < 0 || y >= H) { 73clearInterval(timer); 74paint(); 75return; 76} 77// 頭を先頭に追加 78snake.unshift(new Point(x, y)); 79if (isHit(foods, x, y)) { 80point += 10; // 餌を食べた 81moveFood(x, y); 82} else { 83snake.pop(); // 食べてない→しっぽを削除 84} 85paint(); 86} 87function paint() { 88ctx.clearRect(0, 0, W * S, H * S); 89ctx.fillStyle = "rgb(256,0,0)"; 90ctx.fillText(point, S, S * 2); 91ctx.fillStyle = "rgb(0,0,255)"; 92foods.forEach(function (p) { 93ctx.fillText("+", p.x * S, (p.y + 1) * S); 94}); 95snake.forEach(function (p) { 96ctx.fillText("*", p.x * S, (p.y + 1) * S); 97}); 98} 99function keydown(event) { 100keyCode = event.keyCode; 101} 102</script> 103</head> 104<body onload="init()"> 105<canvas id="field" width="400" height="400" style="background:#cccccc"> 106</canvas> 107</body> 108</html>
###補足情報(言語/FW/ツール等のバージョンなど)
Google Chromeです
回答3件
あなたの回答
tips
プレビュー