Hello,
I am trying to code a simple game. I have a 20x4 lcd display and 3 buttons. The screen is working correctly and the buttons too (I've done some tests) so I think my problem is not hardware.
I'm trying to move a spaceship by pressing one button (up or down) But it doesn't work, at start the spaceship goes to line 1 row 2 (I don't know how this is possible because, my lcd.setCursor() are only in row 0) and if I press the up button, it goes to row 0 line 0. Nothing happens if I press the down button.
I tried several things but nothing worked.
// Asteroids
// goal is to avoid asteroids
// 1 button to move up, 1 button to move down, 1 button to start/stop the game
// include lcd library
#include <LiquidCrystal.h>
// lcd interface pin
LiquidCrystal lcd(2, 3, 4, 5, 6, 7);
// button interface
const int up = 12;
const int down = 13;
const int start = 11;
// graphics
byte spaceShip[8] = {
B10000,
B11000,
B00100,
B01111,
B01111,
B00100,
B11000,
B10000
};
// spaceship position
int spaceShipPosition = 0;
void setup() {
// set up the LCD's number of columns and rows:
lcd.begin(20,4);
// set buttons as input
pinMode(up, INPUT);
pinMode(down, INPUT);
pinMode(start, INPUT);
digitalWrite(up, HIGH);
digitalWrite(down, HIGH);
digitalWrite(start, HIGH);
// set graphics
lcd.createChar(0, spaceShip);
lcd.setCursor(0, spaceShipPosition);
lcd.write(0);
}
void loop() {
// move up
if(digitalRead(up) == LOW) {
MoveUp();
}
// move down
else if(digitalRead(down) == LOW) {
MoveDown();
}
}
void MoveUp() {
if(spaceShipPosition > 0) {
lcd.clear();
spaceShipPosition = spaceShipPosition - 1;
lcd.setCursor(0,spaceShipPosition);
lcd.write(0);
}
}
void MoveDown() {
if(spaceShipPosition < 4) {
lcd.clear();
spaceShipPosition = spaceShipPosition + 1;
lcd.setCursor(0,spaceShipPosition);
lcd.write(0);
}
}
Do you think I can write a Move class to move the spaceship up and down and to move the asteroids ? (for exemple, I call Move(u) to move up, Move(a) to move the asteroids...)
For the asteroid moving, I think I'm going to use a list of lists which contains coords of asteroids. Is it a good idea ?