xxxxxxxxxx
106
let serial;
let moleHole = -1;
let startTime;
let score = 0;
let gameStarted = false;
let holes = [];
function setup() {
createCanvas(400, 400);
// Instantiate our SerialPort object
serial = new p5.SerialPort();
// Assuming our Arduino is connected, let's open the connection to it
// Replace 'COM6' with your Arduino's port name
serial.open("COM6");
// Here are the callbacks that you can register
serial.on('connected', serverConnected);
serial.on('data', serialEvent);
serial.on('error', gotError);
serial.on('open', gotOpen);
serial.on('close', gotClose);
// Initialize the holes array
for (let i = 0; i < 4; i++) {
holes[i] = {
x: (i + 1) * 80,
y: height / 2,
size: 50,
active: false,
};
}
}
function draw() {
background(220);
// Draw holes
for (let i = 0; i < holes.length; i++) {
fill(holes[i].active ? 'brown' : 'black');
ellipse(holes[i].x, holes[i].y, holes[i].size);
}
// Display score and time
let elapsedTime = millis() - (startTime || 0);
let remainingTime = 60000 - elapsedTime;
textAlign(CENTER);
textSize(24);
fill(0);
text("Score: " + score, width / 2, height - 50);
text("Time: " + (remainingTime / 1000).toFixed(1), width / 2, 50);
if (gameStarted && elapsedTime < 60000) {
if (millis() > (startTime || 0) + 2000) { // Change mole every 2 seconds
if (moleHole !== -1) {
holes[moleHole].active = false; // Deactivate the previous mole
}
moleHole = floor(random(0, 4));
holes[moleHole].active = true; // Activate the new mole
startTime = millis();
}
} else if (elapsedTime >= 60000) {
gameStarted = false;
text("Game Over! Final Score: " + score, width / 2, height / 2);
} else {
text("Click any button to start", width / 2, height / 2);
}
}
function serverConnected() {
print("Connected to Server");
}
function gotOpen() {
print("Serial Port is Open");
}
function gotClose() {
print("Serial Port is Closed");
}
function gotError(theerror) {
print(theerror);
}
function serialEvent() {
let data = serial.read();
if (data !== null && data !== '') {
handleButtonPress(Number(data));
}
}
function handleButtonPress(button) {
if (!gameStarted && button === 49) { // Red button value is 49
gameStarted = true;
startTime = millis();
score = 0;
} else if (gameStarted) {
let moleButton = moleHole + 49; // Calculate expected mole button value
if (button === moleButton) {
score++;
}
}
}