Last day for makeup work is Thursday, May 29th!
Copy and paste this code into the editor and then open the Serial Monitor.
Rock, Paper, Scissors
#include <Arduino.h>
// Function declarations
String getComputerChoice();
String determineWinner(String userChoice, String computerChoice);
void clearSerialBuffer();
void setup() {
Serial.begin(9600);
randomSeed(analogRead(0)); // Initialize random number generator
Serial.println("Enter 'R' for Rock, 'P' for Paper, or 'S' for Scissors:");
}
void loop() {
String userChoice = "";
String computerChoice;
String result;
if (Serial.available() > 0) {
// Read user input from the serial monitor
char input = Serial.read();
// Check for valid input
if (input == 'R' || input == 'r') {
userChoice = "Rock";
} else if (input == 'P' || input == 'p') {
userChoice = "Paper";
} else if (input == 'S' || input == 's') {
userChoice = "Scissors";
} else if (isAlpha(input)) { // Check if input is an alphabetic character
Serial.println("Invalid input. Please enter 'R', 'P', or 'S'.");
}
clearSerialBuffer();
if (userChoice.length() > 0) {
computerChoice = getComputerChoice();
result = determineWinner(userChoice, computerChoice);
// Output the results
Serial.println("You chose: " + userChoice);
Serial.println("Computer chose: " + computerChoice);
Serial.println(result);
Serial.println(); // Print an empty line
// Prompt for the next round
Serial.println("Enter 'R' for Rock, 'P' for Paper, or 'S' for Scissors:");
}
}
}
String getComputerChoice() {
int randNumber = random(3); // Generate a random number (0, 1, or 2)
if (randNumber == 0) {
return "Rock";
} else if (randNumber == 1) {
return "Paper";
} else {
return "Scissors";
}
}
String determineWinner(String userChoice, String computerChoice) {
if (userChoice == computerChoice) {
return "It's a tie!";
} else if ((userChoice == "Rock" && computerChoice == "Scissors") ||
(userChoice == "Scissors" && computerChoice == "Paper") ||
(userChoice == "Paper" && computerChoice == "Rock")) {
return "You win!";
} else {
return "You lose!";
}
}
void clearSerialBuffer() {
while (Serial.available() > 0) {
Serial.read();
}
}
Number Guessing Game
#include <Arduino.h>
// Declare variables for the game
int numberToGuess;
int numberOfTries;
const int lowerBound = 1; // Lower bound of the range
const int upperBound = 100; // Upper bound of the range
void setup() {
Serial.begin(9600);
randomSeed(analogRead(0)); // Seed the random number generator
startNewGame(); // Start a new game when the Arduino is reset
}
void loop() {
if (Serial.available() > 0) {
int guess = Serial.parseInt(); // Parse the next number from Serial
clearSerialBuffer(); // Clear any leftover serial data
if (guess != 0) { // Check if a number was entered
numberOfTries++; // Increment the number of tries
if (guess == numberToGuess) {
// If the guess is correct
Serial.print("Correct! The number was ");
Serial.print(numberToGuess);
Serial.print(". It took you ");
Serial.print(numberOfTries);
Serial.println(" tries.");
startNewGame(); // Start a new game
} else if (guess < numberToGuess) {
Serial.println("Too low. Try again.");
} else {
Serial.println("Too high. Try again.");
}
} else {
Serial.println("Please enter a valid number between 1 and 100.");
}
}
}
void startNewGame() {
numberToGuess = random(lowerBound, upperBound + 1); // Random number between lower and upper bound
numberOfTries = 0;
Serial.println("I'm thinking of a number between 1 and 100. Try to guess it!");
}
void clearSerialBuffer() {
while (Serial.available() > 0) {
Serial.read();
}
}
High or Low Card Game
#include <Arduino.h>
// Constants for the game
const int lowestCard = 2;
const int highestCard = 14; // In a real deck, this would be an Ace
// Variables for the current and next card
int currentCard;
int nextCard;
int score;
void setup() {
Serial.begin(9600);
randomSeed(analogRead(0)); // Initialize random number generator
startNewGame();
}
void loop() {
if (Serial.available() > 0) {
char input = Serial.peek(); // Peek at the next byte in the serial buffer
clearSerialBuffer(); // Clear the serial buffer to ensure we only read valid inputs
if (input == 'H' || input == 'h' || input == 'L' || input == 'l') {
nextCard = drawCard(currentCard); // Pass the current card for comparison
Serial.print("Next card is: ");
Serial.println(cardName(nextCard));
if ((input == 'H' || input == 'h') && nextCard > currentCard) {
Serial.println("Correct! The card was higher.");
score++;
} else if ((input == 'L' || input == 'l') && nextCard < currentCard) {
Serial.println("Correct! The card was lower.");
score++;
} else {
Serial.print("Incorrect. Game over. Your score was: ");
Serial.println(score);
startNewGame();
return;
}
currentCard = nextCard; // The next card becomes the current card for the next round
promptNextGuess();
} else if (isAlpha(input)) {
Serial.println("Invalid input. Please enter 'H' for higher or 'L' for lower.");
promptNextGuess();
}
}
}
void startNewGame() {
currentCard = drawCard(-1); // -1 ensures the first draw has no comparison
score = 0;
Serial.println("\nWelcome to High or Low!");
Serial.print("The current card is: ");
Serial.println(cardName(currentCard));
promptNextGuess();
}
int drawCard(int previousCard) {
int card;
do {
card = random(lowestCard, highestCard + 1); // Draw a new card
} while (card == previousCard); // Continue drawing if the same as previous card
return card;
}
String cardName(int cardNumber) {
switch (cardNumber) {
case 11: return "Jack";
case 12: return "Queen";
case 13: return "King";
case 14: return "Ace";
default: return String(cardNumber); // Number cards as is
}
}
void promptNextGuess() {
Serial.println("Will the next card be Higher (H) or Lower (L)? Enter 'H' or 'L':");
}
void clearSerialBuffer() {
while (Serial.available() > 0) {
Serial.read();
}
}
Snake
#include <Arduino.h>
const int gridWidth = 10;
const int gridHeight = 10;
int snakeX[100], snakeY[100]; // Positions of the snake segments
int snakeLength; // Length of the snake
int foodX, foodY; // Position of the food
char direction; // Current movement direction
bool gameOver;
void setup() {
Serial.begin(9600);
randomSeed(analogRead(0));
initGame();
}
void loop() {
if (gameOver) {
Serial.println("Game Over! Resetting in 5 seconds...");
delay(5000);
initGame();
return;
}
if (Serial.available() > 0) {
char input = Serial.read();
clearSerialBuffer();
if (input == 'w' || input == 'a' || input == 's' || input == 'd') {
char newDirection = toupper(input);
// Prevent reversing direction
if ((newDirection == 'W' && direction != 'S') ||
(newDirection == 'S' && direction != 'W') ||
(newDirection == 'A' && direction != 'D') ||
(newDirection == 'D' && direction != 'A')) {
direction = newDirection;
}
}
}
delay(800); // Delay for 800 milliseconds before moving the snake again
moveSnake();
if (checkCollision()) {
gameOver = true;
} else {
if (snakeX[0] == foodX && snakeY[0] == foodY) {
snakeLength++;
placeFood();
}
printGrid();
}
}
void initGame() {
snakeLength = 3; // Reset snake length
direction = 'D'; // Start moving right
gameOver = false;
// Position snake in the middle of the grid
int startX = gridWidth / 2 - 1;
int startY = gridHeight / 2;
for (int i = 0; i < snakeLength; i++) {
snakeX[i] = startX - i;
snakeY[i] = startY;
}
placeFood(); // Place initial food
printGrid();
Serial.println("Use W (up), A (left), S (down), D (right) to move the snake.");
}
void placeFood() {
bool isOnSnake;
do {
foodX = random(1, gridWidth + 1);
foodY = random(1, gridHeight + 1);
isOnSnake = false;
for (int i = 0; i < snakeLength; i++) {
if (snakeX[i] == foodX && snakeY[i] == foodY) {
isOnSnake = true;
break;
}
}
} while (isOnSnake);
}
void moveSnake() {
for (int i = snakeLength - 1; i > 0; i--) {
snakeX[i] = snakeX[i - 1];
snakeY[i] = snakeY[i - 1];
}
switch (direction) {
case 'W': snakeY[0]--; break;
case 'S': snakeY[0]++; break;
case 'A': snakeX[0]--; break;
case 'D': snakeX[0]++; break;
}
}
bool checkCollision() {
if (snakeX[0] < 1 || snakeX[0] > gridWidth || snakeY[0] < 1 || snakeY[0] > gridHeight) {
return true;
}
for (int i = 1; i < snakeLength; i++) {
if (snakeX[0] == snakeX[i] && snakeY[0] == snakeY[i]) {
return true;
}
}
return false;
}
void printGrid() {
Serial.println("\n---------Snake Game---------");
for (int y = 1; y <= gridHeight; y++) {
for (int x = 1; x <= gridWidth; x++) {
bool printed = false;
if (x == snakeX[0] && y == snakeY[0]) {
Serial.print('H');
printed = true;
} else {
for (int j = 1; j < snakeLength; j++) {
if (x == snakeX[j] && y == snakeY[j]) {
Serial.print('B');
printed = true;
break;
}
}
}
if (!printed) {
Serial.print((x == foodX && y == foodY) ? 'F' : '.');
}
}
Serial.println();
}
Serial.println("---------------------------");
}
void clearSerialBuffer() {
while (Serial.available() > 0) {
char t = Serial.read();
}
}
Blackjack
#include <Arduino.h>
int playerScore = 0;
int dealerScore = 0;
bool playerTurn = true; // True while it's the player's turn
void setup() {
Serial.begin(9600);
randomSeed(analogRead(0));
Serial.println("Welcome to Arduino Blackjack!");
Serial.println("Press 'D' to deal cards.");
}
void loop() {
if (Serial.available() > 0) {
char input = Serial.read();
clearSerialBuffer();
if (input == 'd' || input == 'D') {
dealInitialCards();
} else if (playerTurn) {
switch(input) {
case 'h':
case 'H':
playerHits();
break;
case 's':
case 'S':
playerStands();
break;
}
} else if (!playerTurn) {
dealerPlays();
}
}
}
void dealInitialCards() {
playerScore = drawCard() + drawCard();
dealerScore = drawCard();
Serial.print("Dealer's face-up card: ");
Serial.println(dealerScore);
dealerScore += drawCard(); // Dealer's second card, hidden
Serial.print("Your initial cards total: ");
Serial.println(playerScore);
Serial.println("Hit (H) or Stand (S)?");
playerTurn = true; // Make sure player turn is reset here
}
int drawCard() {
return random(2, 12); // Simplified card draw, Ace is always 11
}
void playerHits() {
int card = drawCard();
playerScore += card;
Serial.print("You drew a ");
Serial.print(card);
Serial.print(". Your total is now ");
Serial.println(playerScore);
if (playerScore > 21) {
Serial.println("Bust! You lose.");
resetGame();
} else {
Serial.println("Hit (H) or Stand (S)?");
}
}
void playerStands() {
Serial.println("You stand.");
playerTurn = false; // Turn over to the dealer
}
void dealerPlays() {
Serial.print("Dealer's score: ");
Serial.println(dealerScore);
while (dealerScore < 17) {
int card = drawCard();
dealerScore += card;
Serial.print("Dealer draws a ");
Serial.print(card);
Serial.print(", total is ");
Serial.println(dealerScore);
}
if (dealerScore > 21) {
Serial.println("Dealer busts. You win!");
} else if (dealerScore >= playerScore) {
Serial.println("Dealer wins!");
} else {
Serial.println("You win!");
}
resetGame();
}
void resetGame() {
Serial.println("Play again? Press 'D' to deal new cards.");
}
void clearSerialBuffer() {
while (Serial.available() > 0) {
char t = Serial.read();
}
}