xxxxxxxxxx
104
let currentColor, nextColor;
let gridColors = [];
let gridSize = 2;
let ellipseSize = 100;
let currentPage = -1;
let startImage;
let serial;
let latestData = "waiting for data";
function preload() {
startImage = loadImage('Start.jpeg');
}
function setup() {
createCanvas(600, 600);
noLoop();
currentColor = randomColor();
nextColor = randomColor();
// Setting up Serial Communication
serial = new p5.SerialPort();
serial.open("/dev/tty.usbmodem1411");
serial.on('data', serialEvent);
}
function draw() {
if (currentPage === -1) {
drawStartPage();
} else if (currentPage === 0) {
drawFirstPage();
} else {
drawGamePage();
}
}
function drawStartPage() {
background(startImage);
fill(0);
rect(width / 2 - 30, height / 2 - 20, 60, 40);
fill(255);
textAlign(CENTER, CENTER);
text('Start', width / 2, height / 2);
}
function drawFirstPage() {
background(220);
fill(currentColor);
ellipse(width / 2, height / 2, 120, 120);
fill(0);
rect(width - 80, 20, 60, 40);
fill(255);
textAlign(CENTER, CENTER);
text('Next', width - 50, 40);
}
function drawGamePage() {
background(220);
fill(nextColor);
ellipse(width / 2, 100, 120, 120);
let padding = 230;
for (let i = 0; i < gridSize; i++) {
for (let j = 0; j < gridSize; j++) {
fill(gridColors[i * gridSize + j]);
ellipse(padding + j * (ellipseSize + 50), padding + i * (ellipseSize + 50), ellipseSize, ellipseSize);
}
}
}
function serialEvent() {
let data = serial.readStringUntil('\r\n'); // Read the string from the serial port until a new line
if (data) {
latestData = data.trim(); // trim off any whitespace or newline characters
checkButtonPress(latestData);
}
}
function checkButtonPress(button) {
if (currentPage === -1 && button === 'start') {
currentPage = 0;
redraw();
} else if (currentPage === 0 && button === 'next') {
gridColors = Array.from({length: gridSize * gridSize}, () => randomColor());
gridColors[int(random(gridSize * gridSize))] = currentColor;
currentPage++;
redraw();
} else if (currentPage > 0) {
let index = parseInt(button);
if (gridColors[index] === currentColor) {
prepareNextLevel();
}
}
}
function prepareNextLevel() {
currentColor = nextColor;
nextColor = randomColor();
gridColors = Array.from({length: gridSize * gridSize}, () => randomColor());
gridColors[int(random(gridSize * gridSize))] = currentColor;
redraw();
}
function randomColor() {
return color(random(255), random(255), random(255));
}