Apple Component (Snakes's Food) - UQcsse3200/2024-studio-2 GitHub Wiki
Overview
The snake mini-game has an Apple
class which represents the food item that the snake consumes to increase it's size and grow longer.
This Apple
class plays a crucial role in handling the spawning of the apple on the game grid, ensuring it appears in a random, unoccupied cell each time. The player's goal in this mini-game is to guide the snake character to this apple to score points and increase the snake's length.
Apple
Class: Package
package com.csse3200.game.components.minigame.snake;
Imports
import com.csse3200.game.components.minigame.Grid;
import java.util.Random;
Description
The Apple
class is responsible for:
- Generating the apple at a random location on the game grid
- Making sure it does overlap with the snake's current position
- Checking if the snake's head is in the same position as the apple (this will trigger the snake to consume the apple)
Constructor
Apple(Grid grid)
- Parameters:
Grid grid
: The grid on which the apple is placed.
- Description:
- Creates an apple associated with a specific grid. Upon creation, the apple is automatically placed at a random, unoccupied position on the grid.
Methods
void spawn()
- Description:
- Randomly spawns the apple at an unoccupied position on the grid.
- Uses a
Random
object to determine the x and y coordinates, ensuring the apple doesn't appear on an occupied cell (where the snake is currently located).
boolean isTouchingSnakeHead(Snake snake)
- Parameters:
Snake snake
: The snake character in the snake mini-game.
- Returns:
boolean
:true
if the snake's head is at the same coordinates as the apple,false
otherwise.
- Description:
- Checks if the snake's head is in the same position as the apple, this will indicate that the apple has been consumed.
int getX()
and int getY()
- Returns:
int
: x-coordinate/ y-coordinate of the apple's position.
- Description:
- Retrieves the x-coordinate/ y-coordinate where the apple is currently located on the grid.