Package com.project.snakeGame
Class GamePanel
java.lang.Object
java.awt.Component
java.awt.Container
javax.swing.JComponent
javax.swing.JPanel
com.project.snakeGame.GamePanel
- All Implemented Interfaces:
ActionListener
,ImageObserver
,MenuContainer
,Serializable
,EventListener
,Accessible
The
GamePanel
class handles the gameplay logic and rendering
for the Snake Game. It manages:
- Snake movement and collision detection
- Apple generation and score tracking
- Game rendering and updating
The game can run in two modes:
EASY
mode: Slower snake speedHARD
mode: Faster snake speed
- See Also:
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic enum
Enum for game difficulty modes.class
TheMyKeyAdapter
class handles keyboard inputs to control the snake's direction.Nested classes/interfaces inherited from class javax.swing.JPanel
JPanel.AccessibleJPanel
Nested classes/interfaces inherited from class javax.swing.JComponent
JComponent.AccessibleJComponent
Nested classes/interfaces inherited from class java.awt.Container
Container.AccessibleAWTContainer
Nested classes/interfaces inherited from class java.awt.Component
Component.AccessibleAWTComponent, Component.BaselineResizeBehavior, Component.BltBufferStrategy, Component.FlipBufferStrategy
-
Field Summary
FieldsModifier and TypeFieldDescriptionprivate int
Score - number of apples eaten.private int
X and Y positions of the apple.private int
X and Y positions of the apple.private static final int
Height of the game board (rounded to fit units).private static final int
Width of the game board (rounded to fit units).private int
Initial length of the snake.private char
Current direction of the snake's movement.private static GamePanel.Mode
Current game mode (default: EASY).private boolean
Game running state.private static final int
Maximum number of units (board area divided by unit size).private Random
Random number generator for apple positioning.private Timer
Timer to control the game speed and refresh rate.private static final int
Size of each unit (square) on the game board.private final int[]
Arrays storing the snake's X and Y coordinates.private final int[]
Fields inherited from class javax.swing.JComponent
listenerList, TOOL_TIP_TEXT_KEY, ui, UNDEFINED_CONDITION, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, WHEN_FOCUSED, WHEN_IN_FOCUSED_WINDOW
Fields inherited from class java.awt.Component
accessibleContext, BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENT
Fields inherited from interface java.awt.image.ImageObserver
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH
-
Constructor Summary
ConstructorsConstructorDescriptionConstructs theGamePanel
, initializes the game settings, and starts the game. -
Method Summary
Modifier and TypeMethodDescriptionvoid
Handles the game loop by updating the snake's position, checking for collisions, and determining if the snake has eaten an apple.protected void
Checks if the snake has eaten an apple.private void
Checks for collisions with the snake itself or the game boundaries.protected void
Draws the game elements: Apple Snake body Game over message (if the game ends)private void
Displays the "Game Over" message.protected void
move()
Moves the snake in the current direction.protected void
newApple()
Spawns a new apple at a random location, ensuring it doesn't overlap with the snake's body.protected void
Handles the painting of the game board.private void
Configures the game speed based on the selected mode.protected static void
setMode
(GamePanel.Mode mode) Sets the game mode (difficulty).protected void
Starts the game by: Resetting snake length and score Setting the initial direction to 'R' Spawning the first apple Starting the game timerMethods inherited from class javax.swing.JPanel
getAccessibleContext, getUI, getUIClassID, paramString, setUI, updateUI
Methods inherited from class javax.swing.JComponent
addAncestorListener, addNotify, addVetoableChangeListener, computeVisibleRect, contains, createToolTip, disable, enable, firePropertyChange, firePropertyChange, firePropertyChange, fireVetoableChange, getActionForKeyStroke, getActionMap, getAlignmentX, getAlignmentY, getAncestorListeners, getAutoscrolls, getBaseline, getBaselineResizeBehavior, getBorder, getBounds, getClientProperty, getComponentGraphics, getComponentPopupMenu, getConditionForKeyStroke, getDebugGraphicsOptions, getDefaultLocale, getFontMetrics, getGraphics, getHeight, getInheritsPopupMenu, getInputMap, getInputMap, getInputVerifier, getInsets, getInsets, getListeners, getLocation, getMaximumSize, getMinimumSize, getNextFocusableComponent, getPopupLocation, getPreferredSize, getRegisteredKeyStrokes, getRootPane, getSize, getToolTipLocation, getToolTipText, getToolTipText, getTopLevelAncestor, getTransferHandler, getVerifyInputWhenFocusTarget, getVetoableChangeListeners, getVisibleRect, getWidth, getX, getY, grabFocus, hide, isDoubleBuffered, isLightweightComponent, isManagingFocus, isOpaque, isOptimizedDrawingEnabled, isPaintingForPrint, isPaintingOrigin, isPaintingTile, isRequestFocusEnabled, isValidateRoot, paint, paintBorder, paintChildren, paintImmediately, paintImmediately, print, printAll, printBorder, printChildren, printComponent, processComponentKeyEvent, processKeyBinding, processKeyEvent, processMouseEvent, processMouseMotionEvent, putClientProperty, registerKeyboardAction, registerKeyboardAction, removeAncestorListener, removeNotify, removeVetoableChangeListener, repaint, repaint, requestDefaultFocus, requestFocus, requestFocus, requestFocusInWindow, requestFocusInWindow, resetKeyboardActions, reshape, revalidate, scrollRectToVisible, setActionMap, setAlignmentX, setAlignmentY, setAutoscrolls, setBackground, setBorder, setComponentPopupMenu, setDebugGraphicsOptions, setDefaultLocale, setDoubleBuffered, setEnabled, setFocusTraversalKeys, setFont, setForeground, setInheritsPopupMenu, setInputMap, setInputVerifier, setMaximumSize, setMinimumSize, setNextFocusableComponent, setOpaque, setPreferredSize, setRequestFocusEnabled, setToolTipText, setTransferHandler, setUI, setVerifyInputWhenFocusTarget, setVisible, unregisterKeyboardAction, update
Methods inherited from class java.awt.Container
add, add, add, add, add, addContainerListener, addImpl, addPropertyChangeListener, addPropertyChangeListener, applyComponentOrientation, areFocusTraversalKeysSet, countComponents, deliverEvent, doLayout, findComponentAt, findComponentAt, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents, getComponentZOrder, getContainerListeners, getFocusTraversalKeys, getFocusTraversalPolicy, getLayout, getMousePosition, insets, invalidate, isAncestorOf, isFocusCycleRoot, isFocusCycleRoot, isFocusTraversalPolicyProvider, isFocusTraversalPolicySet, layout, list, list, locate, minimumSize, paintComponents, preferredSize, printComponents, processContainerEvent, processEvent, remove, remove, removeAll, removeContainerListener, setComponentZOrder, setFocusCycleRoot, setFocusTraversalPolicy, setFocusTraversalPolicyProvider, setLayout, transferFocusDownCycle, validate, validateTree
Methods inherited from class java.awt.Component
action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, bounds, checkImage, checkImage, coalesceEvents, contains, createImage, createImage, createVolatileImage, createVolatileImage, disableEvents, dispatchEvent, enable, enableEvents, enableInputMethods, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, getBackground, getBounds, getColorModel, getComponentListeners, getComponentOrientation, getCursor, getDropTarget, getFocusCycleRootAncestor, getFocusListeners, getFocusTraversalKeysEnabled, getFont, getForeground, getGraphicsConfiguration, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputContext, getInputMethodListeners, getInputMethodRequests, getKeyListeners, getLocale, getLocation, getLocationOnScreen, getMouseListeners, getMouseMotionListeners, getMousePosition, getMouseWheelListeners, getName, getParent, getPropertyChangeListeners, getPropertyChangeListeners, getSize, getToolkit, getTreeLock, gotFocus, handleEvent, hasFocus, imageUpdate, inside, isBackgroundSet, isCursorSet, isDisplayable, isEnabled, isFocusable, isFocusOwner, isFocusTraversable, isFontSet, isForegroundSet, isLightweight, isMaximumSizeSet, isMinimumSizeSet, isPreferredSizeSet, isShowing, isValid, isVisible, keyDown, keyUp, list, list, list, location, lostFocus, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paintAll, postEvent, prepareImage, prepareImage, processComponentEvent, processFocusEvent, processHierarchyBoundsEvent, processHierarchyEvent, processInputMethodEvent, processMouseWheelEvent, remove, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, removePropertyChangeListener, removePropertyChangeListener, repaint, repaint, repaint, requestFocus, requestFocus, requestFocusInWindow, resize, resize, setBounds, setBounds, setComponentOrientation, setCursor, setDropTarget, setFocusable, setFocusTraversalKeysEnabled, setIgnoreRepaint, setLocale, setLocation, setLocation, setMixingCutoutShape, setName, setSize, setSize, show, show, size, toString, transferFocus, transferFocusBackward, transferFocusUpCycle
-
Field Details
-
gameMode
Current game mode (default: EASY). -
unitSize
private static final int unitSizeSize of each unit (square) on the game board.- See Also:
-
boardWidth
private static final int boardWidthWidth of the game board (rounded to fit units).- See Also:
-
boardHeight
private static final int boardHeightHeight of the game board (rounded to fit units).- See Also:
-
maxUnits
private static final int maxUnitsMaximum number of units (board area divided by unit size).- See Also:
-
bodyParts
private int bodyPartsInitial length of the snake. -
applesEaten
private int applesEatenScore - number of apples eaten. -
appleX
private int appleXX and Y positions of the apple. -
appleY
private int appleYX and Y positions of the apple. -
direction
private char directionCurrent direction of the snake's movement. -
isRunning
private boolean isRunningGame running state. -
x
private final int[] xArrays storing the snake's X and Y coordinates. -
y
private final int[] y -
timer
Timer to control the game speed and refresh rate. -
random
Random number generator for apple positioning.
-
-
Constructor Details
-
GamePanel
GamePanel()Constructs theGamePanel
, initializes the game settings, and starts the game.
-
-
Method Details
-
setMode
Sets the game mode (difficulty).- Parameters:
mode
- The selected game mode (EASY or HARD).
-
setGameSpeed
private void setGameSpeed()Configures the game speed based on the selected mode.EASY
mode: 300ms delayHARD
mode: 150ms delay
-
startGame
protected void startGame()Starts the game by:- Resetting snake length and score
- Setting the initial direction to 'R'
- Spawning the first apple
- Starting the game timer
-
paintComponent
Handles the painting of the game board.- Overrides:
paintComponent
in classJComponent
- Parameters:
g
- TheGraphics
object used for rendering.
-
draw
Draws the game elements:- Apple
- Snake body
- Game over message (if the game ends)
- Parameters:
g
- TheGraphics
object used for rendering.
-
newApple
protected void newApple()Spawns a new apple at a random location, ensuring it doesn't overlap with the snake's body. -
move
protected void move()Moves the snake in the current direction. -
checkApple
protected void checkApple()Checks if the snake has eaten an apple. Increases the snake's length and score if true. -
checkCollisions
private void checkCollisions()Checks for collisions with the snake itself or the game boundaries. Stops the game if a collision occurs. -
gameOver
Displays the "Game Over" message.- Parameters:
g
- TheGraphics
object used for rendering.
-
actionPerformed
Handles the game loop by updating the snake's position, checking for collisions, and determining if the snake has eaten an apple. The game is repainted after each tick.- Specified by:
actionPerformed
in interfaceActionListener
- Parameters:
e
- TheActionEvent
triggered by the timer.
-