반응형

 

 

LED가 켜지는 순서대로 버튼 스위치를 눌러서 맞추는 게임입니다.

게임 시작시 파란색 LED 파도치기

정답 시 녹색LED 1회 점등
오답 시 빨간색LED 점등
게임 종료시 1번 파란색LED 점등

 

코드

#define MAX 10
int button[3] = { 11,12,13 }; // 택트 스위치 연결 핀번호
int LED_G = 5; // 녹색
int LED_R = 6; // 빨간색
int LED_B1 = 7; // 파란색1
int LED_B2 = 8; // 파란색2
int LED_B3 = 9; // 파란색3

int answer[MAX]; // 정답 기억 배열
int record[MAX]; // 사용자의 입력
int nLed = 0; // 문제 번호
int tLed = 0; // 현재 문제에서 맞추는 중인 위치
int x; // 랜덤변수
int T; // 문제 수
int tmp, cnt;
int flag; // 정답(1) 오답(0), 종료(-1)

void setup()
{
  Serial.begin(9600);
  pinMode(button[0], INPUT_PULLUP);
  pinMode(button[1], INPUT_PULLUP);
  pinMode(button[2], INPUT_PULLUP);
  pinMode(LED_G, OUTPUT);
  pinMode(LED_R, OUTPUT);
  pinMode(LED_B1, OUTPUT);
  pinMode(LED_B2, OUTPUT);
  pinMode(LED_B3, OUTPUT);

}

void loop()
{

  for(int i = 0; i < 2; i++)
  {
    for(int j = 7; j <= 9; j++)
    {
      light(j,100);
    }
  }

  delay(1000);
  
  T = MAX; // 문제수

  for(int i = 1 ; i <= T; i++)
  {
    // i번째 테스트 시작
    test(i);
    
    // 정답을 입력해주세요.
    input(i);
    
    // 비교하고 정답 체크
    // 정답 : 녹색 1회 점등
    // 오답 : 빨간색 점등
    // 게임끝 : 녹색 점등
    check(i);
    
    if(flag == 1) light(5,500); // 정답 녹색 1회 점등
    else if(flag == 0)
    {
      light(6,3000); // 오답 빨간색
      break;
    }
    if (i == T) light(7,3000);
    
  }

}

void test(int n)
{
  for(int i = 0; i < n; i++)
  {
    x = random(0,3); // 0~2까지 랜덤
    light(x+7,300); // 파란색 등은 7번부터...
    answer[i] = x;
  }
}

void input(int n)
{
  cnt = 0;
  while(cnt < n)
  {
    if(digitalRead(button[0]) == LOW)
    {
      record[cnt] = 0;
      light(7,300);
      cnt ++;
    }
    else if(digitalRead(button[1]) == LOW)
    {
      record[cnt] = 1;
      light(8,300);
      cnt ++;
    }
    else if(digitalRead(button[2]) == LOW)
    {
      record[cnt] = 2;
      light(9,300);
      cnt ++;
    }
  }
}

void check(int n)
{
  flag = 1; 
  for(int i = 0; i < n; i++)
  {
    if(answer[i] != record[i]) 
      flag = 0;
  }
}

void light(int n, int t)
{
    digitalWrite(n, HIGH);
    delay(t);
    digitalWrite(n, LOW);
    delay(t);
}

 

실행영상

 

 

반응형

+ Recent posts