arduino贪吃蛇代码
时间: 2023-07-03 07:21:14 浏览: 111
贪吃蛇的代码
3星 · 编辑精心推荐
以下是一个简单的Arduino贪吃蛇代码,需要连接一个8x8的LED矩阵和一个Joystick模块:
```
#include <Adafruit_GFX.h>
#include <Adafruit_NeoMatrix.h>
#include <Adafruit_NeoPixel.h>
#define PIN 6
Adafruit_NeoMatrix matrix = Adafruit_NeoMatrix(8, 8, PIN,
NEO_MATRIX_TOP + NEO_MATRIX_LEFT +
NEO_MATRIX_ROWS + NEO_MATRIX_PROGRESSIVE,
NEO_GRB + NEO_KHZ800);
const int joystick_x = A0;
const int joystick_y = A1;
int snake_x[64];
int snake_y[64];
int snake_length = 4;
int snake_dir = 0;
int snake_speed = 200;
int food_x = 0;
int food_y = 0;
void setup() {
matrix.begin();
matrix.setTextWrap(false);
matrix.setBrightness(40);
matrix.setTextColor(matrix.Color(255, 0, 0));
randomSeed(analogRead(0));
for(int i = 0; i < snake_length; i++) {
snake_x[i] = 3 + i;
snake_y[i] = 3;
}
spawn_food();
}
void loop() {
int joystick_x_val = analogRead(joystick_x);
int joystick_y_val = analogRead(joystick_y);
if(joystick_x_val < 100) {
snake_dir = 2;
} else if(joystick_x_val > 900) {
snake_dir = 0;
} else if(joystick_y_val < 100) {
snake_dir = 3;
} else if(joystick_y_val > 900) {
snake_dir = 1;
}
move_snake();
delay(snake_speed);
}
void move_snake() {
int new_x = snake_x[0];
int new_y = snake_y[0];
if(snake_dir == 0) {
new_x++;
} else if(snake_dir == 1) {
new_y++;
} else if(snake_dir == 2) {
new_x--;
} else if(snake_dir == 3) {
new_y--;
}
if(new_x < 0) {
new_x = 7;
} else if(new_x > 7) {
new_x = 0;
}
if(new_y < 0) {
new_y = 7;
} else if(new_y > 7) {
new_y = 0;
}
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] = new_x;
snake_y[0] = new_y;
matrix.clear();
for(int i = 0; i < snake_length; i++) {
matrix.drawPixel(snake_x[i], snake_y[i], matrix.Color(0, 255, 0));
}
if(snake_x[0] == food_x && snake_y[0] == food_y) {
snake_length++;
spawn_food();
}
matrix.drawPixel(food_x, food_y, matrix.Color(255, 0, 0));
matrix.show();
}
void spawn_food() {
food_x = random(0, 8);
food_y = random(0, 8);
}
```
注意:这个代码可能需要根据你的硬件配置进行修改,例如PIN号和模块引脚。
阅读全文