#include <stdio.h>
#include "pico/stdlib.h"
#include "hardware/gpio.h"
#include "pico/multicore.h"
// Define LED and button pins
#define LD1_PIN 1
#define LD2_PIN 2
#define LD3_PIN 3
#define LD4_PIN 4
#define BT1_PIN 5
#define BT2_PIN 6
#define BT3_PIN 7
#define BT4_PIN 8
// Function to configure GPIO pins
void configurePins() {
gpio_init(LD1_PIN);
gpio_init(LD2_PIN);
gpio_init(LD3_PIN);
gpio_init(LD4_PIN);
gpio_init(BT1_PIN);
gpio_init(BT2_PIN);
gpio_init(BT3_PIN);
gpio_init(BT4_PIN);
gpio_set_dir(LD1_PIN, GPIO_OUT);
gpio_set_dir(LD2_PIN, GPIO_OUT);
gpio_set_dir(LD3_PIN, GPIO_OUT);
gpio_set_dir(LD4_PIN, GPIO_OUT);
gpio_set_dir(BT1_PIN, GPIO_IN);
gpio_set_dir(BT2_PIN, GPIO_IN);
gpio_set_dir(BT3_PIN, GPIO_IN);
gpio_set_dir(BT4_PIN, GPIO_IN);
}
// Function to control LEDs
void setLED(int pin, int state) {
gpio_put(pin, state);
}
// Function to read buttons
int readButton(int pin) {
return gpio_get(pin);
}
// Function to generate a random number between 1 and 4
int RNgen() {
return (rand() % 4) + 1;
}
// Function to generate an array of random numbers
void arraygen(int n, int* randomArray) {
for (int i = 0; i < n; i++) {
randomArray[i] = RNgen();
}
}
// Function to play the game
void Game() {
stdio_init_all();
configurePins();
int level = 1;
int maxLevel = 10;
int continueGame = 1;
while (continueGame) {
// Part 1: Display the level on LEDs
int gamearray[level]; // Create an array for the current level
arraygen(level, gamearray); // Generate random values for the current level
for (int i = 0; i < level; i++) {
setLED(gamearray[i], 1); // Turn on the LED corresponding to the value
sleep_ms(500); // Delay for half a second
setLED(gamearray[i], 0); // Turn off the LED
sleep_ms(500); // Delay for half a second
}
// Part 2: Ask the user to press buttons
int match = 1; // Flag to check if buttons match the sequence
for (int i = 0; i < level; i++) {
while (readButton(gamearray[i]) == 0) {
// Wait for the correct button to be pressed
}
sleep_ms(100); // Debounce delay
if (readButton(gamearray[i]) == 0) {
match = 0; // Button press does not match
break;
}
}
if (match) {
printf("Level %d clear!\n", level);
level++; // Move to the next level
} else {
printf("Level %d failed! Resetting to level 1.\n", level);
level = 1; // Reset the game to level 1
}
// Check if the game should continue
if (level > maxLevel) {
printf("Congratulations! You've completed all levels.\n");
continueGame = 0; // End the game
}
}
}
int main() {
Game();
return 0;
}