arduino贪吃蛇代码
时间: 2023-10-03 22:08:33 浏览: 112
贪吃蛇的代码
5星 · 资源好评率100%
这是一个简单的Arduino贪吃蛇游戏代码,需要连接一个OLED显示屏和一个Joystick。
```c++
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <Adafruit_SSD1306.h>
#include <Adafruit_GFX.h>
#include <Wire.h>
#include <SPI.h>
#define OLED_RESET 4
Adafruit_SSD1306 display(OLED_RESET);
#define JOY_VERT_ANALOG 0
#define JOY_HORIZ_ANALOG 1
#define JOY_SEL 9
int x, y;
int direction = 0;
int score = 0;
int food_x, food_y;
int snake_x[100] = {64, 63, 62, 61, 60};
int snake_y[100] = {32, 32, 32, 32, 32};
int snake_length = 5;
bool game_over = false;
void setup() {
Serial.begin(9600);
display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
display.clearDisplay();
display.display();
randomSeed(analogRead(0));
food_x = random(0, 128);
food_y = random(0, 64);
}
void loop() {
x = analogRead(JOY_HORIZ_ANALOG);
y = analogRead(JOY_VERT_ANALOG);
if (x < 470) {
direction = 1;
} else if (x > 550) {
direction = 2;
} else if (y > 550) {
direction = 3;
} else if (y < 470) {
direction = 4;
}
switch (direction) {
case 1:
move_left();
break;
case 2:
move_right();
break;
case 3:
move_down();
break;
case 4:
move_up();
break;
}
if (snake_x[0] == food_x && snake_y[0] == food_y) {
score++;
snake_length++;
food_x = random(0, 128);
food_y = random(0, 64);
}
display.clearDisplay();
display.drawPixel(food_x, food_y, WHITE);
for (int i = 0; i < snake_length; i++) {
display.drawPixel(snake_x[i], snake_y[i], WHITE);
}
display.display();
delay(100);
}
void move_left() {
for (int i = snake_length - 1; i > 0; i--) {
snake_x[i] = snake_x[i - 1];
snake_y[i] = snake_y[i - 1];
}
snake_x[0]--;
if (snake_x[0] < 0) {
game_over = true;
}
check_collision();
}
void move_right() {
for (int i = snake_length - 1; i > 0; i--) {
snake_x[i] = snake_x[i - 1];
snake_y[i] = snake_y[i - 1];
}
snake_x[0]++;
if (snake_x[0] > 127) {
game_over = true;
}
check_collision();
}
void move_down() {
for (int i = snake_length - 1; i > 0; i--) {
snake_x[i] = snake_x[i - 1];
snake_y[i] = snake_y[i - 1];
}
snake_y[0]++;
if (snake_y[0] > 63) {
game_over = true;
}
check_collision();
}
void move_up() {
for (int i = snake_length - 1; i > 0; i--) {
snake_x[i] = snake_x[i - 1];
snake_y[i] = snake_y[i - 1];
}
snake_y[0]--;
if (snake_y[0] < 0) {
game_over = true;
}
check_collision();
}
void check_collision() {
for (int i = 1; i < snake_length; i++) {
if (snake_x[0] == snake_x[i] && snake_y[0] == snake_y[i]) {
game_over = true;
}
}
if (game_over == true) {
display.clearDisplay();
display.setCursor(20, 20);
display.print("GAME OVER");
display.display();
while (true) {}
}
}
```
注意:此代码仅为示例,您需要根据您的硬件和需求进行修改。
阅读全文