// updates the snake by checking for changes in direction before getting the direction, // and determines if the snake is colliding into something, moving or eating a fruit int Snake::updateSnake(const sf::Keyboard::Key& dir, sf::Vector2f fruitPos) { playerMove.setDirection(dir); // what's worse, creating a new temporary movementDir everytime or calling getDirection 4x? sf::Keyboard::Key movementDir = playerMove.getDirection(); if (collision()) { return 2; } Vector2f nextPos = head->shape.getPosition(); if (movementDir == sf::Keyboard::Up) { nextPos.y -= pixelSizeY; } if (movementDir == sf::Keyboard::Down) { nextPos.y += pixelSizeY; } if (movementDir == sf::Keyboard::Left) { nextPos.x -= pixelSizeX; } if (movementDir == sf::Keyboard::Right) { nextPos.x += pixelSizeX; } if (nextPos == fruitPos) { eatFruit(nextPos); return 1; } else { moveDir(nextPos); } return 0; }
void loop(uint16_t* cnt) { if (gameStage == Welcome) { displayWelcomePage(&gameStage, &snake, &fruit); } else if (gameStage == Ongoing) { checkButtonsPress( ); if (Button_Up && snake.dir != Down) { snake.dir = 1; } else if (Button_Down && snake.dir != Up) { snake.dir = 2; } else if (Button_Left && snake.dir != Right) { snake.dir = 3; } else if (Button_Right && snake.dir != Left) { snake.dir = 4; } updateSnakeLocation(&snake); eatFruit(&snake, &fruit); } else { displayGameOverPage(&gameStage); } // reset counter *cnt = 0; }