/*
This is a simple display of an Arduino Uno and ILI9341 touch
that works as a small game console and runs a simple game
where you squash dots that appear on the screen.
*/
#include <Adafruit_GFX.h>
#include <Adafruit_ILI9341.h>
#include <Adafruit_FT6206.h>
// Defining pins
#define TFT_CS 10
#define TFT_DC 9
#define TFT_RST 8
#define TFT_MOSI 11
#define TFT_CLK 13
#define TFT_MISO 12
// Instances of ILI9341 and FT6206 classes
Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC, TFT_MOSI, TFT_CLK, TFT_RST, TFT_MISO);
Adafruit_FT6206 ts = Adafruit_FT6206();
// variables to store coordinates and couting dots pressed
uint16_t touchX, touchY;
uint8_t squashed = 0;
// millis() returns unsigned long where gameTime and prevTime
// calculates the time and rectTime is the interval of "spawn"
unsigned long gameTime = 0, prevTime = 0, rectTime = 2000;
// Class to handle the rectangles
// The getters and setters and previous variables
// are there to scale for continious spawning of rectangles
// but not used in the current format
class Dots{
private:
uint16_t prev_x = 0, prev_y = 0;
public:
bool rectActive = false;
uint16_t x, y, w = 15, h = 15;
// Getters and setters
void setPrev_x(uint16_t *x){
prev_x = *x;
}
int getPrev_x(){
return prev_x;
}
void setPrev_y(uint16_t *y){
prev_y = *y;
}
int getPrev_y(){
return prev_y;
}
};
// Instance of rectangle class
Dots dotsObj;
void newRect(){
// Calling draw function with generated coordinates
tft.fillRect(dotsObj.x, dotsObj.y, dotsObj.w, dotsObj.h, ILI9341_WHITE);
dotsObj.rectActive = true;
}
void removeRect(){
// If a new rectangle is drawn the old one is removed
tft.fillRect(dotsObj.x, dotsObj.y, dotsObj.w, dotsObj.h, ILI9341_BLACK);
dotsObj.rectActive = false;
}
void setup() {
Serial.begin(9600);
tft.begin();
tft.setRotation(1);
tft.setTextColor(ILI9341_RED);
tft.setTextSize(5);
tft.setCursor(40, 100);
// Checking if touch is active or not and stopping execution if not
if(!ts.begin(40)){
Serial.println("Touch screen not active!");
exit(1);
}else{
Serial.println("Touch screen active!");
}
}
void loop() {
// Program runs for 30sec then shuts off
// (simulation in wokwi will continue without looping code)
gameTime = millis();
if(gameTime > 30000){
tft.print("Dots: ");
tft.println(squashed);
exit(0);
}
// Calculating the coordinates for the presses on the touch
if(ts.touched()){
TS_Point p = ts.getPoint();
p.x = map(p.x, 0, 240, 240, 0);
p.y = map(p.y, 0, 320, 320, 0);
touchY = p.x;
touchX = tft.width() - p.y;
}
// Draw new rectangle if none is present
if(!dotsObj.rectActive){
dotsObj.x = random(15, 305);
dotsObj.y = random(15, 225);
newRect();
}
// Deleting past rect every 2 seconds
if(gameTime - prevTime >= rectTime){
removeRect();
prevTime = gameTime;
}
// "Collision detection" for touch presses and rectangle
if((touchX >= dotsObj.x && touchX <= dotsObj.x + dotsObj.w) &&
(touchY >= dotsObj.y && touchY <= dotsObj.y + dotsObj.h)){
removeRect();
squashed++;
}
}