Simon Says

Use your Getting Started Kit to create a Simon Says memory game!

Prerequisites

This project assumes you are familiar with the following

Setup

All you need for this project is the Getting Started Kit.

Getting Started Kit

Write code (Java)

Copy the code below into a new Java project. If you need a reminder of how to do this, revisit the Getting Started Course.

Not your programming language? Set your preferences so we can display relevant code examples

  
//Add Phidgets Library.
import com.phidget22.*;
import java.util.ArrayList;

public class SimonSays {
    //Track number of button events
    public static int numEvents = 0;    
    
    public static void main(String[] args) throws Exception {        
        //Track user input and solutions
        ArrayList<Integer> sequenceKey = new ArrayList<>();
        ArrayList<Integer> userAnswer = new ArrayList<>();
        
        //Determine starting # of colors
        int numColors = 3; 
        
        //Determine if game should continue looping
        boolean continueGame = true; 
    
        //Create
        DigitalInput redButton = new DigitalInput();
        DigitalOutput redLED = new DigitalOutput();
        DigitalInput greenButton = new DigitalInput();
        DigitalOutput greenLED = new DigitalOutput();

        //Address
        redButton.setHubPort(0);
        redButton.setIsHubPortDevice(true);
        redLED.setHubPort(1);
        redLED.setIsHubPortDevice(true);
        greenButton.setHubPort(5);
        greenButton.setIsHubPortDevice(true);
        greenLED.setHubPort(4);
        greenLED.setIsHubPortDevice(true);

        //Event for red button
        redButton.addStateChangeListener(new DigitalInputStateChangeListener() {
            public void onStateChange(DigitalInputStateChangeEvent e) {
                try{
                    redLED.setState(e.getState());
                    if (e.getState()) {
                        userAnswer.add(0);
                        numEvents++;
                    }
                } catch(PhidgetException ex){
                    System.out.println("Error: " + ex);
                }
            }
        });
        
        //Event for green button
        greenButton.addStateChangeListener(new DigitalInputStateChangeListener() {
            public void onStateChange(DigitalInputStateChangeEvent e) {
                try{
                    greenLED.setState(e.getState());
                    if (e.getState()) {
                        userAnswer.add(1);
                        numEvents++;
                    }
                }catch(PhidgetException ex){
                    System.out.println("Failure: " + ex);
                }
            }
        });
        
        //Open 
        redLED.open(1000);
        greenLED.open(1000);
        redButton.open(1000);        
        greenButton.open(1000);

        
        System.out.println("Starting game, look at the LEDs.");
        Thread.sleep(2000);
        
        //Game loop
        while (continueGame) {
            //Generate answer key for this round
            sequenceKey.clear();             
            for (int i = 0; i < numColors; i++) {
                sequenceKey.add((int) (Math.random() * 2)); //randomly generate either 0 or 1
            }

            //Flash the answer key for user to memorize
            for (int i = 0; i < sequenceKey.size(); i++) {
                if (sequenceKey.get(i) == 0){ //0 is assigned to red
                    redLED.setState(true);
                    Thread.sleep(500);
                    redLED.setState(false);
                } 
                else{ //1 is assigned to green
                    greenLED.setState(true);
                    Thread.sleep(500);
                    greenLED.setState(false);
                }
                Thread.sleep(500);
            }
            
            //reset before accepting answers
            numEvents = 0; 
            userAnswer.clear();
            
            System.out.println("Please enter your answer:");
            //Wait for user input
            while (numEvents < sequenceKey.size()){
                Thread.sleep(150);
            }

            //Compare user answers to key
            for (int i = 0; i < sequenceKey.size(); i++) {
                if (userAnswer.get(i) != sequenceKey.get(i)) {
                    System.out.println("Game Over! You reached level: " + (numColors-3));
                    continueGame = false;
                }
            }

            if (continueGame)
            {
                //Indicates the user got the sequence correct
                System.out.println("Congrats! Starting next level...");
                Thread.sleep(2000);
                numColors++;
            }
        }
    }
}
  
  
package simonsays;

//Add Phidgets Library.
import com.phidget22.*;
import java.util.ArrayList;

public class SimonSays {
    //Track number of button events
    public static int numEvents = 0;    
    
    public static void main(String[] args) throws Exception {        
        //Track user input and solutions
        ArrayList<Integer> sequenceKey = new ArrayList<>();
        ArrayList<Integer> userAnswer = new ArrayList<>();
        
        //Determine starting # of colors
        int numColors = 3; 
        
        //Determine if game should continue looping
        boolean continueGame = true; 
    
        //Create
        DigitalInput redButton = new DigitalInput();
        DigitalOutput redLED = new DigitalOutput();
        DigitalInput greenButton = new DigitalInput();
        DigitalOutput greenLED = new DigitalOutput();

        //Address
        redButton.setHubPort(0);
        redButton.setIsHubPortDevice(true);
        redLED.setHubPort(1);
        redLED.setIsHubPortDevice(true);
        greenButton.setHubPort(5);
        greenButton.setIsHubPortDevice(true);
        greenLED.setHubPort(4);
        greenLED.setIsHubPortDevice(true);

        //Event for red button
        redButton.addStateChangeListener(new DigitalInputStateChangeListener() {
            public void onStateChange(DigitalInputStateChangeEvent e) {
                try{
                    redLED.setState(e.getState());
                    if (e.getState()) {
                        userAnswer.add(0);
                        numEvents++;
                    }
                } catch(PhidgetException ex){
                    System.out.println("Error: " + ex);
                }
            }
        });
        
        //Event for green button
        greenButton.addStateChangeListener(new DigitalInputStateChangeListener() {
            public void onStateChange(DigitalInputStateChangeEvent e) {
                try{
                    greenLED.setState(e.getState());
                    if (e.getState()) {
                        userAnswer.add(1);
                        numEvents++;
                    }
                }catch(PhidgetException ex){
                    System.out.println("Failure: " + ex);
                }
            }
        });
        
        //Open 
        redLED.open(1000);
        greenLED.open(1000);
        redButton.open(1000);        
        greenButton.open(1000);

        
        System.out.println("Starting game, look at the LEDs.");
        Thread.sleep(2000);
        
        //Game loop
        while (continueGame) {
            //Generate answer key for this round
            sequenceKey.clear();             
            for (int i = 0; i < numColors; i++) {
                sequenceKey.add((int) (Math.random() * 2)); //randomly generate either 0 or 1
            }

            //Flash the answer key for user to memorize
            for (int i = 0; i < sequenceKey.size(); i++) {
                if (sequenceKey.get(i) == 0){ //0 is assigned to red
                    redLED.setState(true);
                    Thread.sleep(500);
                    redLED.setState(false);
                } 
                else{ //1 is assigned to green
                    greenLED.setState(true);
                    Thread.sleep(500);
                    greenLED.setState(false);
                }
                Thread.sleep(500);
            }
            
            //reset before accepting answers
            numEvents = 0; 
            userAnswer.clear();
            
            System.out.println("Please enter your answer:");
            //Wait for user input
            while (numEvents < sequenceKey.size()){
                Thread.sleep(150);
            }

            //Compare user answers to key
            for (int i = 0; i < sequenceKey.size(); i++) {
                if (userAnswer.get(i) != sequenceKey.get(i)) {
                    System.out.println("Game Over! You reached level: " + (numColors-3));
                    continueGame = false;
                }
            }

            if (continueGame)
            {
                //Indicates the user got the sequence correct
                System.out.println("Congrats! Starting next level...");
                Thread.sleep(2000);
                numColors++;
            }
        }
    }
}
  
  
Code not available.
  

Write code (Python)

Copy the code below into a new Python project. If you need a reminder of how to do this, revisit the Getting Started Course.

Not your programming language? Set your preferences so we can display relevant code examples

  
#Add Phidgets Library 
from Phidget22.Phidget import *
from Phidget22.Devices.DigitalInput import *
from Phidget22.Devices.DigitalOutput import *
#Required for sleep statement 
import time
#Required for random number generator
import random

#Track number of button events
num_events = 0

#Track user input and solution
sequence_key = []
user_answer = []

#Determine starting # of colors
num_colors = 3

#Determine if game should continue looping
continue_game = True

#Event
def onRedButton_StateChange(self, state):
    global num_events
    redLED.setState(state)
    if (state):
        user_answer.append(0)
        num_events += 1
#Event
def onGreenButton_StateChange(self, state):
    global num_events
    greenLED.setState(state)
    if (state):
        user_answer.append(1)
        num_events += 1 
        
#Create 
redButton = DigitalInput()
redLED =  DigitalOutput()
greenButton = DigitalInput()
greenLED = DigitalOutput()
 
#Address 
redButton.setHubPort(0)
redButton.setIsHubPortDevice(True)
redLED.setHubPort(1)
redLED.setIsHubPortDevice(True)
greenButton.setHubPort(5)
greenButton.setIsHubPortDevice(True)
greenLED.setHubPort(4)
greenLED.setIsHubPortDevice(True)

#Subscribe to Events 
redButton.setOnStateChangeHandler(onRedButton_StateChange)
greenButton.setOnStateChangeHandler(onGreenButton_StateChange)

#Open 
redLED.openWaitForAttachment(1000)
greenLED.openWaitForAttachment(1000)
redButton.openWaitForAttachment(1000)
greenButton.openWaitForAttachment(1000)

print("Starting game, look at the LEDS.")
time.sleep(2)

#Game loop
while (continue_game):
    #Generate answer key for this round
    sequence_key.clear()
    for i in range(num_colors):
        sequence_key.append(int(random.random() * 2)) #randomly generate either 0 or 1
    
    #Flash the answer key for user to memorize
    for i in range(len(sequence_key)):
        if sequence_key[i] == 0: #0 is assigned to red
            redLED.setState(True)
            time.sleep(0.5)
            redLED.setState(False)            
        else: #1 is assigned to green
            greenLED.setState(True)
            time.sleep(0.5)
            greenLED.setState(False)
        time.sleep(0.5)
    
    #Reset before accepting answers
    num_events = 0
    user_answer.clear()
    
    print("Please enter your answer:")
    #Wait for user input
    while (num_events < len(sequence_key)):
        time.sleep(0.1)
    
    #Compare user answers to answer key
    for i in range(len(sequence_key)):
        if user_answer[i] != sequence_key[i]:
            print("Game Over! You reached level: " + str(num_colors-3) +"\n")
            continue_game = False  
        
    if (continue_game):
        print("Congrats! Starting next level...")
        time.sleep(2)
        num_colors += 1 #Increase difficulty for next level
  

Write code (C#)

Copy the code below into a new C# project. If you need a reminder of how to do this, revisit the Getting Started Course.

Not your programming language? Set your preferences so we can display relevant code examples

  
//Add Phidgets Library
using Phidget22;
using System.Collections;
using System.Collections.Generic;

namespace SimonSays
{
    class Program
    {
        //Track number of button events
        static int numEvents = 0;

        //Track user input and solutions
        public static List<int> sequenceKey = new List<int>();
        public static List<int> userAnswer = new List<int>();
        //public static ArrayList sequenceKey = new ArrayList();
        //public static ArrayList userAnswer = new ArrayList();

        //Define here so they can be used in events
        public static DigitalOutput redLED;
        public static DigitalOutput greenLED;

        //Event
        private static void redButton_StateChange(object sender, Phidget22.Events.DigitalInputStateChangeEventArgs e)
        {
            redLED.State = e.State;
            if (e.State)
            {
                userAnswer.Add(0);
                numEvents++;
            }
        }

        //Event
        private static void greenButton_StateChange(object sender, Phidget22.Events.DigitalInputStateChangeEventArgs e)
        {
            greenLED.State = e.State;
            if (e.State)
            {
                userAnswer.Add(1);
                numEvents++;
            }
        }

        static void Main(string[] args)
        {
            //Determine starting # of colors
            var numColors = 3;

            //Determine if game should continue looping
            bool continueGame = true; 

            //Create
            DigitalInput redButton = new DigitalInput();
            DigitalInput greenButton = new DigitalInput();
            redLED = new DigitalOutput();            
            greenLED = new DigitalOutput();

            //Address
            redButton.HubPort = 0;
            redButton.IsHubPortDevice = true;
            redLED.HubPort = 1;
            redLED.IsHubPortDevice = true;
            greenButton.HubPort = 5;
            greenButton.IsHubPortDevice = true;
            greenLED.HubPort = 4;
            greenLED.IsHubPortDevice = true;

            //Subscribe to events
            redButton.StateChange += redButton_StateChange;
            greenButton.StateChange += greenButton_StateChange;

            //Open
            redLED.Open(1000);
            greenLED.Open(1000);
            redButton.Open(1000);
            greenButton.Open(1000);            

            //Creates random number generator
            System.Random RNG = new System.Random();

            
            System.Console.WriteLine("Starting game, look at the LEDS.");
            System.Threading.Thread.Sleep(2000);

            
            //Loop that keeps game going
            while (continueGame)
            {
                //Generate answer key for this round
                sequenceKey.Clear();
                for (int i = 0; i < numColors; i++)
                {
                    int randomNumber = RNG.Next(0, 2); //randomly generate either 0 or 1
                    sequenceKey.Add(randomNumber);
                }

                //Flash the answer key for user to memorize
                for (int i = 0; i < sequenceKey.Count; i++)
                {
                    if (sequenceKey[i] == 0) //0 is assigned to red
                    {
                        redLED.State = true;
                        System.Threading.Thread.Sleep(500);
                        redLED.State = false;
                    }
                    else //1 is assigned to green
                    {
                        greenLED.State = true;
                        System.Threading.Thread.Sleep(500);
                        greenLED.State = false;
                    }
                    System.Threading.Thread.Sleep(500);
                }

                //reset before accepting answers
                numEvents = 0; 
                userAnswer.Clear();

                System.Console.WriteLine("Please enter your answer:");
                //Wait for user input
                while (numEvents < sequenceKey.Count) 
                {
                    System.Threading.Thread.Sleep(150);
                }

                //Compare user answers to key
                for (int i = 0; i < sequenceKey.Count; i++)
                {
                    if (userAnswer[i] != sequenceKey[i])
                    {                       
                        System.Console.WriteLine("Game Over! You reached level : " + (numColors-3));
                        System.Console.ReadLine();

                        continueGame = false;                      
                    }
                }

                if (continueGame) 
                {
                    System.Console.WriteLine("Congrats! Starting next level...");
                    System.Threading.Thread.Sleep(2000);
                    numColors++;
                }                
            }
        }
    }
}
  

Write code (Swift)

Copy the code below into a new Swift project. If you need a reminder of how to do this, revisit the Getting Started Course.

Not your programming language? Set your preferences so we can display relevant code examples

  
Code not available.
  

Run Your Program

After the initial LED sequence flashes, you will have to remember the sequence, and repeat it using the corresponding buttons!

Practice

  1. Play a sound effect every time an LED flashes. Hint: the RFID Sound Effects project shows how you can add audio to your code.
  2. Ask users for their name and log their scores to a file. Show a high score chart at the beginning and end of the game.

What are Phidgets?

Phidgets are programmable USB sensors. Simply plug in your sensor, write code in your favorite language and go!

Phidgets have been used by STEM professionals for over 20 years and are now available to students.

Learn more

Set your preferences

Windows

Mac OS

Raspberry Pi

Java

Python

C#

Swift

NetBeans

Processing

Eclipse

Thonny

PyCharm

PyScripter

Visual Studio

Xcode

Setting your preferred operating system, programming language and environment lets us display relevant code samples for the Getting Started Tutorial, Device Tutorials and Projects

Done