Wavelength
Privacy-focused, cross-platform, and open-source communication application
Loading...
Searching...
No Matches
SnakeGameLayer Class Referencefinal

A security layer implementing a classic Snake game as a challenge. More...

#include <snake_game_layer.h>

Inheritance diagram for SnakeGameLayer:
Collaboration diagram for SnakeGameLayer:

Public Member Functions

void Initialize () override
 Initializes the layer for display. Resets the game state, initializes the game logic (snake position, apple), sets focus, ensures the layer is visible, and starts the game timer after a short delay.
 
void Reset () override
 Resets the layer to its initial state. Stops timers, resets game variables (score, game over state, snake, direction), randomizes the exit again, resets UI elements (score label, board style), and ensures full opacity.
 
 SnakeGameLayer (QWidget *parent=nullptr)
 Constructs a SnakeGameLayer. Initializes the UI elements (title, instructions, game board, score label), sets up the layout, creates timers for game updates and border animation, sets focus policy, and randomly determines the exit side and position.
 
 ~SnakeGameLayer () override
 Destructor. Stops and deletes the game and border animation timers.
 
- Public Member Functions inherited from SecurityLayer
 SecurityLayer (QWidget *parent=nullptr)
 Constructs a SecurityLayer.
 
 ~SecurityLayer () override=default
 Virtual destructor. Ensures proper cleanup for derived classes.
 

Protected Member Functions

bool eventFilter (QObject *watched, QEvent *event) override
 Filters key press events specifically for the game_board_ QLabel. Ensures that arrow key presses are captured even if the main layer doesn't have focus, as long as the game board does.
 
void keyPressEvent (QKeyEvent *event) override
 Handles key press events for controlling the snake. Passes the key code to HandleInput() and accepts the event.
 

Private Types

enum class  BorderSide { Left , Right }
 Enum representing which border (left or right) the exit will appear on. More...
 
enum class  CellType {
  Empty , Snake , SnakeHead , Apple ,
  OpenBorder
}
 Enum representing the possible types of content within a grid cell. More...
 
enum class  Direction { Up , Right , Down , Left }
 Enum representing the possible movement directions of the snake. More...
 
enum class  GameState { Playing , ExitOpen , Completed , Failed }
 Enum representing the current state of the game. More...
 

Private Slots

void FinishGame (bool success)
 Handles the end of the game (success or failure). Stops timers. On success, updates UI to green, shows a success message, and fades out the layer. On failure, briefly shows a red background and restarts the game.
 
void OpenBorder ()
 Initiates the "exit open" state after collecting 4 apples. Changes the game state, determines exit points, updates the score label, starts the border opening animation, and renders the game board with the exit.
 
void UpdateBorderAnimation ()
 Slot called periodically by border_animation_timer_ to animate the border opening. Increments the animation progress and triggers a repaint of the game board periodically.
 
void UpdateGame ()
 Slot called periodically by game_timer_ to update the game state. Calls MoveSnake() if the game is not over.
 

Private Member Functions

void GenerateApple ()
 Generates a new apple at a random empty cell on the grid.
 
void HandleInput (int key)
 Processes user input (arrow keys) to change the snake's direction. Prevents the snake from reversing a direction directly (e.g., going left immediately after going right). Updates the direction_ member variable.
 
void InitializeGame ()
 Sets up the initial state of the game board and snake. Clears the grid, places the snake in the center, sets the initial direction, generates the first apple, and renders the initial board state.
 
bool IsCollision (int x, int y) const
 Checks if the given coordinates (x, y) represent a collision. Considers collisions with walls (respecting the open exit in ExitOpen state) and collisions with the snake's own body.
 
bool IsExitPoint (int x, int y) const
 Checks if the given coordinates (x, y) correspond to the open exit location. Used only when game_state_ is ExitOpen.
 
void MoveSnake ()
 Moves the snake one step in the current direction_. Calculates the new head position, checks for collisions (walls, self), checks for apple collection, handles exiting the board in ExitOpen state, updates the snake's position in the snake_ vector and the grid_ array, and triggers a re-render.
 
void RenderGame () const
 Renders the current state of the game onto the game_board_ QLabel. Draws the grid, borders (including the animated open exit), snake, and apple.
 

Private Attributes

int animation_progress_
 Progress counter for the border opening animation.
 
QPair< int, int > apple_
 Coordinates of the current apple.
 
int apples_collected_
 The number of apples collected so far.
 
QTimer * border_animation_timer_
 Timer controlling the animation of the border opening.
 
Direction direction_
 Current direction the snake is moving.
 
QVector< QPair< int, int > > exit_points_
 Store the coordinates considered as valid exit points (just outside the border).
 
int exit_position_
 The Y-coordinate (row index) of the exit cell.
 
BorderSide exit_side_
 Which side (Left or Right) the exit is on.
 
QLabel * game_board_
 QLabel used as the canvas for rendering the game board.
 
bool game_over_
 Flag indicating if the game is over (due to collision or successful exit).
 
GameState game_state_
 Current state of the game (Playing, ExitOpen, etc.).
 
QTimer * game_timer_
 Timer controlling the main game loop (snake movement).
 
CellType grid_ [kGridSize][kGridSize]
 2D array representing the game board state.
 
Direction last_processed_direction_
 Direction the snake was moving in the last processed game tick (used to prevent 180 turns).
 
int parts_exited_
 Counter for how many snake segments have successfully exited the board.
 
QLabel * score_label_
 QLabel displaying the current score (apples collected).
 
QVector< QPair< int, int > > snake_
 Vector storing the coordinates of each segment of the snake (head is first).
 
TranslationManagertranslator_
 Pointer to the translation manager for handling UI translations.
 

Static Private Attributes

static constexpr int kCellSize = 20
 Size of each cell in pixels.
 
static constexpr int kGridSize = 12
 Size of the game grid (width and height in cells).
 

Additional Inherited Members

- Signals inherited from SecurityLayer
void layerCompleted ()
 Emitted when the user successfully completes the security challenge presented by this layer.
 
void layerFailed ()
 Emitted when the user fails the security challenge (e.g., incorrect code, timeout, collision). Note: Not all layers currently implement failure conditions that emit this signal.
 

Detailed Description

A security layer implementing a classic Snake game as a challenge.

This layer presents a Snake game where the user controls a snake using arrow keys. The goal is to collect 4 apples. After collecting the apples, an exit opens on either the left or right border of the game board. The user must then guide the entire snake out through the exit. Collision with the walls (except the exit) or the snake's own body results in a game over and restart. Successful completion triggers the layerCompleted() signal.

Member Enumeration Documentation

◆ BorderSide

enum class SnakeGameLayer::BorderSide
strongprivate

Enum representing which border (left or right) the exit will appear on.

Enumerator
Left 
Right 

◆ CellType

enum class SnakeGameLayer::CellType
strongprivate

Enum representing the possible types of content within a grid cell.

Enumerator
Empty 

Empty cell.

Snake 

Part of the snake's body.

SnakeHead 

The head of the snake.

Apple 

An apple to be collected.

OpenBorder 

Represents the open exit area (not directly used in grid).

◆ Direction

enum class SnakeGameLayer::Direction
strongprivate

Enum representing the possible movement directions of the snake.

Enumerator
Up 
Right 
Down 
Left 

◆ GameState

enum class SnakeGameLayer::GameState
strongprivate

Enum representing the current state of the game.

Enumerator
Playing 

Normal gameplay, collecting apples.

ExitOpen 

Apples collected, exit is open, snake needs to leave.

Completed 

Snake successfully exited the board.

Failed 

Snake collided, game over.

Constructor & Destructor Documentation

◆ SnakeGameLayer()

SnakeGameLayer::SnakeGameLayer ( QWidget * parent = nullptr)
explicit

Constructs a SnakeGameLayer. Initializes the UI elements (title, instructions, game board, score label), sets up the layout, creates timers for game updates and border animation, sets focus policy, and randomly determines the exit side and position.

Parameters
parentOptional parent widget.
Here is the call graph for this function:

◆ ~SnakeGameLayer()

SnakeGameLayer::~SnakeGameLayer ( )
override

Destructor. Stops and deletes the game and border animation timers.

Member Function Documentation

◆ eventFilter()

bool SnakeGameLayer::eventFilter ( QObject * watched,
QEvent * event )
overrideprotected

Filters key press events specifically for the game_board_ QLabel. Ensures that arrow key presses are captured even if the main layer doesn't have focus, as long as the game board does.

Parameters
watchedThe object being watched.
eventThe event being processed.
Returns
True if the event was handled (key press on game board), false otherwise.
Here is the call graph for this function:

◆ FinishGame

void SnakeGameLayer::FinishGame ( bool success)
privateslot

Handles the end of the game (success or failure). Stops timers. On success, updates UI to green, shows a success message, and fades out the layer. On failure, briefly shows a red background and restarts the game.

Parameters
successTrue if the game was completed successfully, false otherwise.
Here is the call graph for this function:
Here is the caller graph for this function:

◆ GenerateApple()

void SnakeGameLayer::GenerateApple ( )
private

Generates a new apple at a random empty cell on the grid.

Here is the caller graph for this function:

◆ HandleInput()

void SnakeGameLayer::HandleInput ( int key)
private

Processes user input (arrow keys) to change the snake's direction. Prevents the snake from reversing a direction directly (e.g., going left immediately after going right). Updates the direction_ member variable.

Parameters
keyThe Qt::Key code pressed by the user.
Here is the caller graph for this function:

◆ Initialize()

void SnakeGameLayer::Initialize ( )
overridevirtual

Initializes the layer for display. Resets the game state, initializes the game logic (snake position, apple), sets focus, ensures the layer is visible, and starts the game timer after a short delay.

Implements SecurityLayer.

Here is the call graph for this function:

◆ InitializeGame()

void SnakeGameLayer::InitializeGame ( )
private

Sets up the initial state of the game board and snake. Clears the grid, places the snake in the center, sets the initial direction, generates the first apple, and renders the initial board state.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ IsCollision()

bool SnakeGameLayer::IsCollision ( int x,
int y ) const
private

Checks if the given coordinates (x, y) represent a collision. Considers collisions with walls (respecting the open exit in ExitOpen state) and collisions with the snake's own body.

Parameters
xThe x-coordinate to check.
yThe y-coordinate to check.
Returns
True if a collision occurs at (x, y), false otherwise.
Here is the caller graph for this function:

◆ IsExitPoint()

bool SnakeGameLayer::IsExitPoint ( int x,
int y ) const
private

Checks if the given coordinates (x, y) correspond to the open exit location. Used only when game_state_ is ExitOpen.

Parameters
xThe x-coordinate to check.
yThe y-coordinate to check.
Returns
True if (x, y) is the exit point, false otherwise.
Here is the caller graph for this function:

◆ keyPressEvent()

void SnakeGameLayer::keyPressEvent ( QKeyEvent * event)
overrideprotected

Handles key press events for controlling the snake. Passes the key code to HandleInput() and accepts the event.

Parameters
eventThe key event.
Here is the call graph for this function:

◆ MoveSnake()

void SnakeGameLayer::MoveSnake ( )
private

Moves the snake one step in the current direction_. Calculates the new head position, checks for collisions (walls, self), checks for apple collection, handles exiting the board in ExitOpen state, updates the snake's position in the snake_ vector and the grid_ array, and triggers a re-render.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ OpenBorder

void SnakeGameLayer::OpenBorder ( )
privateslot

Initiates the "exit open" state after collecting 4 apples. Changes the game state, determines exit points, updates the score label, starts the border opening animation, and renders the game board with the exit.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ RenderGame()

void SnakeGameLayer::RenderGame ( ) const
private

Renders the current state of the game onto the game_board_ QLabel. Draws the grid, borders (including the animated open exit), snake, and apple.

Here is the caller graph for this function:

◆ Reset()

void SnakeGameLayer::Reset ( )
overridevirtual

Resets the layer to its initial state. Stops timers, resets game variables (score, game over state, snake, direction), randomizes the exit again, resets UI elements (score label, board style), and ensures full opacity.

Implements SecurityLayer.

Here is the caller graph for this function:

◆ UpdateBorderAnimation

void SnakeGameLayer::UpdateBorderAnimation ( )
privateslot

Slot called periodically by border_animation_timer_ to animate the border opening. Increments the animation progress and triggers a repaint of the game board periodically.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ UpdateGame

void SnakeGameLayer::UpdateGame ( )
privateslot

Slot called periodically by game_timer_ to update the game state. Calls MoveSnake() if the game is not over.

Here is the call graph for this function:
Here is the caller graph for this function:

Member Data Documentation

◆ animation_progress_

int SnakeGameLayer::animation_progress_
private

Progress counter for the border opening animation.

◆ apple_

QPair<int, int> SnakeGameLayer::apple_
private

Coordinates of the current apple.

◆ apples_collected_

int SnakeGameLayer::apples_collected_
private

The number of apples collected so far.

◆ border_animation_timer_

QTimer* SnakeGameLayer::border_animation_timer_
private

Timer controlling the animation of the border opening.

◆ direction_

Direction SnakeGameLayer::direction_
private

Current direction the snake is moving.

◆ exit_points_

QVector<QPair<int, int> > SnakeGameLayer::exit_points_
private

Store the coordinates considered as valid exit points (just outside the border).

◆ exit_position_

int SnakeGameLayer::exit_position_
private

The Y-coordinate (row index) of the exit cell.

◆ exit_side_

BorderSide SnakeGameLayer::exit_side_
private

Which side (Left or Right) the exit is on.

◆ game_board_

QLabel* SnakeGameLayer::game_board_
private

QLabel used as the canvas for rendering the game board.

◆ game_over_

bool SnakeGameLayer::game_over_
private

Flag indicating if the game is over (due to collision or successful exit).

◆ game_state_

GameState SnakeGameLayer::game_state_
private

Current state of the game (Playing, ExitOpen, etc.).

◆ game_timer_

QTimer* SnakeGameLayer::game_timer_
private

Timer controlling the main game loop (snake movement).

◆ grid_

CellType SnakeGameLayer::grid_[kGridSize][kGridSize]
private

2D array representing the game board state.

◆ kCellSize

int SnakeGameLayer::kCellSize = 20
staticconstexprprivate

Size of each cell in pixels.

◆ kGridSize

int SnakeGameLayer::kGridSize = 12
staticconstexprprivate

Size of the game grid (width and height in cells).

◆ last_processed_direction_

Direction SnakeGameLayer::last_processed_direction_
private

Direction the snake was moving in the last processed game tick (used to prevent 180 turns).

◆ parts_exited_

int SnakeGameLayer::parts_exited_
private

Counter for how many snake segments have successfully exited the board.

◆ score_label_

QLabel* SnakeGameLayer::score_label_
private

QLabel displaying the current score (apples collected).

◆ snake_

QVector<QPair<int, int> > SnakeGameLayer::snake_
private

Vector storing the coordinates of each segment of the snake (head is first).

◆ translator_

TranslationManager* SnakeGameLayer::translator_
private

Pointer to the translation manager for handling UI translations.


The documentation for this class was generated from the following files: