xxxxxxxxxx
175
var gameover = false;
var score = 0;
var hiScore = 0;
var x = 250;
var y = 200;
var direction = 39;
var auto = false;
var compX = 150;
var compY = 200;
var compDir = 37;
function setup() {
createCanvas(400, 400);
background(8, 83, 204);
fill(0, 0, 0, 255);
rect(15, 15, 370, 370);
fill(8, 83, 204);
rect(300, 120, 50, 20);
rect(90, 300, 10, 70);
frameRate(30);
strokeWeight(2);
}
function draw() {
if (gameover) {
return;
}
//score display
score++;
noStroke();
fill(8, 83, 204);
rect(0, 0, 65, 30);
fill(0);
rect(3, 3, 59, 24);
textSize(20);
fill(255);
textAlign(RIGHT);
text(score, 60, 22);
human();
compDrive();
}
function human() {
stroke(111, 229, 252);
point(x, y);
if(auto) {
selfDrive();
}
if (direction === 37) {
x -= 2;
} else if (direction === 38) {
y -= 2;
} else if (direction === 39) {
x += 2;
} else if (direction === 40) {
y += 2;
}
if (notBlack(x,y)) {
fill(0);
stroke(255);
rect(75, 100, 260, 100);
textSize(35);
fill(255);
noStroke();
textAlign(CENTER);
text("Computer Wins!", 205, 150);
textSize(20);
text("Press R to restart", 205, 180);
if(score > hiScore)
hiScore = score;
fill(0);
rect(115, 215, 170, 30);
fill(255);
text("High Score: " + hiScore, 200, 235);
gameover = true;
}
}
function compDrive() {
stroke(129, 247, 192);
point(compX, compY);
if (compDir === 37 && notBlack(compX-2, compY))
compDir = 38;
else if (compDir === 38 && notBlack(compX, compY-2))
compDir = 39;
else if (compDir === 39 && notBlack(compX+2, compY))
compDir = 40;
else if (compDir === 40 && notBlack(compX, compY+2))
compDir = 37;
if (compDir === 37) {
compX -= 2;
} else if (compDir === 38) {
compY -= 2;
} else if (compDir === 39) {
compX += 2;
} else if (compDir === 40) {
compY += 2;
}
if (notBlack(compX,compY)) {
fill(0);
stroke(255);
rect(90, 100, 230, 100);
textSize(35);
fill(255);
noStroke();
textAlign(CENTER);
text("Human Wins!", 205, 150);
textSize(20);
text("Press R to restart", 205, 180);
if(score > hiScore)
hiScore = score;
fill(0);
rect(115, 215, 170, 30);
fill(255);
text("High Score: " + hiScore, 200, 235);
gameover = true;
}
}
function notBlack(x,y) {
var a = get(x, y);
if (a[0] !== 0) return true;
else if (a[1] !== 0) return true;
else if (a[2] !== 0) return true;
return false;
}
function keyPressed() {
if (keyCode >= 37 && keyCode <= 40) {
direction = keyCode;
}
if (key === "r") {
gameover = false;
noStroke();
fill(0);
rect(15, 15, 370, 370);
x = 200;
y = 200;
direction = 39;
compX = 100;
compY = 200;
compDir = 37;
score = 0;
fill(8, 83, 204);
rect(300, 120, 50, 20);
rect(90, 300, 10, 70);
}
if (key === "s") {
auto = !auto;
}
}
function selfDrive() {
if (direction === 37 && notBlack(x-2, y))
direction = 38;
else if (direction === 38 && notBlack(x, y-2))
direction = 39;
else if (direction === 39 && notBlack(x+2, y))
direction = 40;
else if (direction === 40 && notBlack(x, y+2))
direction = 37;
}