/ LcdGame.cpp - Joona Viertola 11.4.2012 // GPLv2 #include <LiquidCrystal.h> LiquidCrystal lcd(8,9,4,5,6,7); boolean ON = true; int blocks [5][2] = {{2, 0},{5, 1},{7, 0},{10, 1},{14, 0}}; int goal[2] = {15, 0}; int adc_key_val[5] ={20, 270, 520, 690, 880}; int x = 0; int y = 0; char pla_char = '!'; char goa_char = '?'; char blo_char = '#'; int NUM_KEYS = 5; int adc_key_in; unsigned long startTime; unsigned long time; void setup() { lcd.begin(16, 2); lcd.setCursor(0,0); lcd.print("Get to the goal!"); delay(3000); lcd.clear(); startTime = millis(); lcd.setCursor(x,y); lcd.print(pla_char); // Let's draw blocks for (int i = 0; i < 5; i++) { lcd.setCursor(blocks[i][0], blocks[i][1]); lcd.print(blo_char); } lcd.setCursor(goal[0], goal[1]); lcd.print(goa_char); } void loop() { if (ON) { adc_key_in = analogRead(0); int key = get_key(adc_key_in); if (key == 0) { // Reset } else if (key == 1) { // Right move(x + 1, y); } else if (key == 2) { // Up move(x, y - 1); } else if (key == 3) { // Down move(x, y + 1); } else if (key == 4) { // Left move(x- 1, y); } check_goal(x, y); delay(250); } else { return; } } // Move to next point boolean move(int nx, int ny) { if (!check_walls(nx, ny) && !check_blocks(nx, ny)) { lcd.setCursor(x,y); lcd.print(' '); lcd.setCursor(nx,ny); lcd.print(pla_char); x = nx; y = ny; return true; } return false; } // Checks for blocks boolean check_blocks(int x, int y) { for (int i = 0; i < 5; i++) { if (blocks[i][0] == x && blocks[i][1] == y) return true; } return false; } // Checks for walls boolean check_walls(int x, int y) { if (x < 0 || x > 15 || y < 0 || y > 1) return true; else return false; } // Checks for goal boolean check_goal(int x, int y) { if (x == goal[0] && y == goal[1]) { time = millis() - startTime; time = time / 1000; lcd.clear(); lcd.setCursor(0, 0); lcd.print("You won!"); lcd.setCursor(0, 1); lcd.print(time); ON = false; } } // For cheking which key is pressed int get_key(unsigned int input) { int k; for (k = 0; k < NUM_KEYS; k++) { if (input < adc_key_val[k]) { return k; } } if (k >= NUM_KEYS) { k = -1; // No valid key pressed } return k; }