Nota

Ciao, benvenuto nella community SunFounder Raspberry Pi & Arduino & ESP32 Enthusiasts su Facebook! Approfondisci Raspberry Pi, Arduino ed ESP32 con altri appassionati.

Perché unirsi?

  • Supporto Esperto: Risolvi problemi post-vendita e sfide tecniche con l’aiuto della nostra community e del nostro team.

  • Impara & Condividi: Scambia consigli e tutorial per migliorare le tue competenze.

  • Anteprime Esclusive: Ottieni l’accesso anticipato agli annunci di nuovi prodotti e anteprime esclusive.

  • Sconti Speciali: Goditi sconti esclusivi sui nostri prodotti più recenti.

  • Promozioni e Concorsi Festivi: Partecipa a concorsi e promozioni festive.

👉 Pronto a esplorare e creare con noi? Clicca [Qui] e unisciti oggi stesso!

GIOCO - Snake

Questo esempio implementa il classico gioco Snake su una matrice LED 8x12 utilizzando la scheda R4 Wifi. I giocatori controllano la direzione del serpente utilizzando un joystick a doppio asse.

Componenti Necessari

In questo progetto, abbiamo bisogno dei seguenti componenti.

È sicuramente conveniente acquistare un kit completo, ecco il link:

Nome

ELEMENTI IN QUESTO KIT

LINK

Elite Explorer Kit

300+

Elite Explorer Kit

Puoi anche acquistarli separatamente dai link sottostanti.

INTRODUZIONE COMPONENTI

LINK ACQUISTO

Arduino Uno R4 WiFi

-

Cavi Jumper

ACQUISTA

Modulo Joystick

ACQUISTA

Collegamenti

../_images/13_snake_bb.png

Schema Elettrico

../_images/13_snake_schematic.png

Codice

Nota

  • Puoi aprire il file 13_snake.ino nel percorso elite-explorer-kit-main\fun_project\13_snake direttamente.

  • Oppure copia questo codice nell’Arduino IDE.

13_snake.ino
  1/*
  2  This code implements a simple Snake game using an Arduino Uno R4 and a 
  3  Joystick Module. The Snake moves based on joystick input, and the 
  4  objective is to eat randomly generated food without colliding with 
  5  the snake's body. The game ends if the snake collides with itself.
  6
  7  Board: Arduino Uno R4 
  8  Component: Joystick Module
  9*/
 10
 11
 12#include "Arduino_LED_Matrix.h"
 13
 14ArduinoLEDMatrix matrix;
 15byte frame[8][12];
 16byte flatFrame[8 * 12];  // Flattened frame for matrix.loadPixels()
 17
 18// Snake variables
 19struct Point {
 20  byte x;
 21  byte y;
 22};
 23
 24Point snake[100];
 25int snakeLength = 3;
 26Point food;
 27int direction = 0;  // 0=up, 1=right, 2=down, 3=left
 28
 29void setup() {
 30  pinMode(A0, INPUT);  // joystick X-axis
 31  pinMode(A1, INPUT);  // joystick Y-axis
 32
 33  // Initialize LED matrix
 34  matrix.begin();
 35
 36  // Initialize snake at middle of screen
 37  snake[0] = { 6, 4 };
 38  snake[1] = { 6, 5 };
 39  snake[2] = { 6, 6 };
 40
 41  // Generate initial food
 42  generateFood();
 43}
 44
 45void loop() {
 46  // Read joystick input
 47  int x = analogRead(A0);
 48  int y = analogRead(A1);
 49
 50  // Determine new direction based on joystick
 51  if (x > 600 && direction != 3) direction = 1;
 52  else if (x < 400 && direction != 1) direction = 3;
 53  else if (y > 600 && direction != 0) direction = 2;
 54  else if (y < 400 && direction != 2) direction = 0;
 55
 56  // Move snake
 57  moveSnake();
 58
 59  // Check for collision with food
 60  if (snake[0].x == food.x && snake[0].y == food.y) {
 61    snake[snakeLength] = snake[snakeLength - 1];  // Initialize the new segment
 62    snakeLength++;
 63    generateFood();
 64  }
 65
 66  // Check for collision with self
 67  for (int i = 1; i < snakeLength; i++) {
 68    if (snake[0].x == snake[i].x && snake[0].y == snake[i].y) {
 69      // Reset game (or end game)
 70      snakeLength = 3;
 71      snake[0] = { 6, 4 };
 72      snake[1] = { 6, 5 };
 73      snake[2] = { 6, 6 };
 74      direction = 0;
 75      generateFood();
 76    }
 77  }
 78
 79  // Draw to LED matrix
 80  drawFrame();
 81
 82  // Delay to control speed
 83  delay(200);
 84}
 85
 86void moveSnake() {
 87  for (int i = snakeLength - 1; i > 0; i--) {
 88    snake[i] = snake[i - 1];
 89  }
 90
 91  // Move the head of the snake based on the direction
 92  switch (direction) {
 93    case 0:
 94      snake[0].y = (snake[0].y - 1 + 8) % 8;  // Wrap around at the top and bottom edges
 95      break;
 96    case 1:
 97      snake[0].x = (snake[0].x + 1) % 12;  // Wrap around at the right and left edges
 98      break;
 99    case 2:
100      snake[0].y = (snake[0].y + 1) % 8;  // Wrap around at the bottom and top edges
101      break;
102    case 3:
103      snake[0].x = (snake[0].x - 1 + 12) % 12;  // Wrap around at the left and right edges
104      break;
105  }
106}
107
108void generateFood() {
109  Point possibleLocations[8 * 12];
110  int idx = 0;
111
112  // Generate all possible locations for the food
113  for (int y = 0; y < 8; y++) {
114    for (int x = 0; x < 12; x++) {
115      bool overlap = false;
116
117      // Check for overlap with the snake
118      for (int i = 0; i < snakeLength; i++) {
119        if (snake[i].x == x && snake[i].y == y) {
120          overlap = true;
121          break;
122        }
123      }
124
125      if (!overlap) {
126        possibleLocations[idx++] = { x, y };
127      }
128    }
129  }
130
131  // Randomly choose a location for the food from the possible locations
132  int choice = random(0, idx);
133  food = possibleLocations[choice];
134}
135
136void drawFrame() {
137  // Clear frame
138  for (int y = 0; y < 8; y++) {
139    for (int x = 0; x < 12; x++) {
140      frame[y][x] = 0;
141    }
142  }
143
144  // Draw snake
145  for (int i = 0; i < snakeLength; i++) {
146    frame[snake[i].y][snake[i].x] = 1;
147  }
148
149  // Draw food
150  frame[food.y][food.x] = 1;
151
152  // Flatten frame array and load into LED matrix
153  int idx = 0;
154  for (int y = 0; y < 8; y++) {
155    for (int x = 0; x < 12; x++) {
156      flatFrame[idx++] = frame[y][x];
157    }
158  }
159  matrix.loadPixels(flatFrame, 8 * 12);
160  matrix.renderFrame(0);
161}

Come funziona?

Ecco una spiegazione dettagliata del codice:

  1. Definizione e Inizializzazione delle Variabili

    Importa la libreria Arduino_LED_Matrix per le operazioni sulla matrice LED. matrix è un’istanza della matrice LED. frame e flatFrame sono array utilizzati per memorizzare e processare le informazioni dei pixel sullo schermo. Il serpente è rappresentato come un array di strutture Point, dove ogni punto ha una coordinata x e y. food rappresenta la posizione del cibo. direction è la direzione di movimento corrente del serpente.

  2. setup()

    Inizializza gli assi X e Y del joystick come input. Avvia la matrice LED. Inizializza la posizione iniziale del serpente al centro dello schermo. Genera casualmente la posizione iniziale del cibo.

  3. loop()

    Determina la direzione del serpente in base alle letture del joystick. Muove il serpente. Controlla se la testa del serpente collide con il cibo. Se lo fa, il serpente cresce e viene generato nuovo cibo in una nuova posizione. Controlla se il serpente collide con sé stesso. Se lo fa, resetta il gioco. Disegna lo stato attuale del gioco (posizioni del serpente e del cibo) sulla matrice LED. Aggiunge un ritardo per controllare la velocità del gioco.

  4. moveSnake()

    Muove ogni parte del serpente nella posizione della parte precedente, iniziando dalla coda e andando verso la testa. Muove la testa del serpente in base alla sua direzione.

  5. generateFood()

    Genera tutte le possibili posizioni del cibo. Controlla se ogni posizione si sovrappone a una parte del serpente. Se non si sovrappone, la posizione è considerata una possibile posizione del cibo. Seleziona casualmente una posizione possibile del cibo.

  6. drawFrame()

    Cancella il frame corrente. Disegna il serpente e il cibo sul frame. Appiattisce l’array frame bidimensionale in un array unidimensionale (flatFrame) e lo carica sulla matrice LED.