MCPcopy Create free account
hub / github.com/Blueforcer/awtrix3 / updateDirection

Function updateDirection

src/effects.cpp:380–461  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

378}
379
380void 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)

Callers 1

SnakeGameFunction · 0.85

Calls 1

willCollideFunction · 0.85

Tested by

no test coverage detected