| 378 | } |
| 379 | |
| 380 | void updateDirection() |
| 381 | { |
| 382 | // Simple strategy to move towards apple |
| 383 | if (snakeDirection % 2 == 0) |
| 384 | { // currently moving vertically |
| 385 | // Only change direction if snake is horizontally aligned with the apple |
| 386 | if (apple.y == snake[0].y) |
| 387 | { |
| 388 | if (apple.x > snake[0].x && snakeDirection != 3) |
| 389 | { // prevent moving left if currently moving right |
| 390 | snakeDirection = 1; // move right |
| 391 | } |
| 392 | else if (apple.x < snake[0].x && snakeDirection != 1) |
| 393 | { // prevent moving right if currently moving left |
| 394 | snakeDirection = 3; // move left |
| 395 | } |
| 396 | } |
| 397 | } |
| 398 | else |
| 399 | { // currently moving horizontally |
| 400 | // Only change direction if snake is vertically aligned with the apple |
| 401 | if (apple.x == snake[0].x) |
| 402 | { |
| 403 | if (apple.y > snake[0].y && snakeDirection != 0) |
| 404 | { // prevent moving up if currently moving down |
| 405 | snakeDirection = 2; // move down |
| 406 | } |
| 407 | else if (apple.y < snake[0].y && snakeDirection != 2) |
| 408 | { // prevent moving down if currently moving up |
| 409 | snakeDirection = 0; // move up |
| 410 | } |
| 411 | } |
| 412 | } |
| 413 | // Predict next position of snake's head |
| 414 | Point nextPos = snake[0]; |
| 415 | if (snakeDirection == 0) |
| 416 | { |
| 417 | nextPos.y--; |
| 418 | } |
| 419 | else if (snakeDirection == 1) |
| 420 | { |
| 421 | nextPos.x++; |
| 422 | } |
| 423 | else if (snakeDirection == 2) |
| 424 | { |
| 425 | nextPos.y++; |
| 426 | } |
| 427 | else if (snakeDirection == 3) |
| 428 | { |
| 429 | nextPos.x--; |
| 430 | } |
| 431 | // Check if next position will collide with snake's body |
| 432 | for (uint8_t i = 1; i < snakeLength; i++) |
| 433 | { |
| 434 | if (nextPos.x == snake[i].x && nextPos.y == snake[i].y) |
| 435 | { |
| 436 | // If snake is moving vertically, try to turn left or right |
| 437 | if (snakeDirection % 2 == 0) |
no test coverage detected