let gameState = "start";
let score = 0;
let roads = [];
let playerImage;
function setup() {
createCanvas(400, 400);
noStroke();
rectMode(CENTER);
textAlign(CENTER, CENTER);
imageMode(CENTER);
playerImage = loadImage('car.png');
resetGame();
}
function draw() {
updateGame();
drawGame();
}
function resetGame() {
score = 0;
createRoads();
}
function createRoads() {
roads = [];
for (let i = 0; i < 21; i++) {
roads.push({
x: 200,
y: 20 * i,
});
}
}
function updateGame() {
if (gameState === "start" || gameState === "gameover") {
return;
}
updateRoads();
detectGameover();
score++;
}
function updateRoads() {
for (let i = 0; i < roads.length; i++) {
roads[i].y += 1;
if (roads[i].y >= 410) {
roads[i].x = 200 + 100 * sin(score * 0.01);
roads[i].y = -10;
}
}
}
function detectGameover() {
let gameover = true;
for (let i = 0; i < roads.length; i++) {
let distanceX = abs(mouseX - roads[i].x);
let distanceY = abs(mouseY - roads[i].y);
if (distanceX <= 75 && distanceY <= 10) {
gameover = false;
}
}
if (gameover) {
gameState = "gameover";
}
}
function drawGame() {
background(0);
drawRoads();
drawPlayer();
drawScore();
if (gameState === "start") {
drawStart();
} else if (gameState === "gameover") {
drawGameover();
}
}
function drawRoads() {
fill(255);
for (let i = 0; i < roads.length; i++) {
rect(roads[i].x, roads[i].y, 150, 20);
}
}
function drawPlayer() {
image(playerImage, mouseX, mouseY, 30, 30);
}
function drawScore(){
fill(255, 0, 0);
textSize(15);
text(score, 320, 30);
}
function drawStart() {
fill(255, 0, 0);
textSize(30);
text("レーシングゲーム", 200, 200);
textSize(15);
text("タップしてスタート", 200, 250);
}
function drawGameover() {
fill(255, 0, 0);
textSize(30);
text("ゲームオーバー", 200, 200);
textSize(15);
text("タップしてリスタート", 200, 250);
}
function mousePressed() {
if (gameState === "start") {
gameState = "play";
}else if (gameState === "gameover") {
resetGame();
gameState = "play";
}
}