Class Arkanoid
- All Implemented Interfaces:
ActionListener, ImageObserver, MenuContainer, Serializable, EventListener, Accessible
This implementation features a professional physics engine for ball-paddle collisions, responsive keyboard and mouse controls, MIDI sound synthesis for 8-bit retro audio, particle systems, and multiple power-up items (multiball, wider paddle, and fireball).
It integrates a HierarchyListener to automatically clean up resources
(stopping timers, closing synthesizers) when the panel is closed or removed from the screen.
- Author:
- anahata
- See Also:
-
Nested Class Summary
Nested classes/interfaces inherited from class JPanel
JPanel.AccessibleJPanelNested classes/interfaces inherited from class JComponent
JComponent.AccessibleJComponentNested classes/interfaces inherited from class Container
Container.AccessibleAWTContainerNested classes/interfaces inherited from class Component
Component.AccessibleAWTComponent, Component.BaselineResizeBehavior, Component.BltBufferStrategy, Component.FlipBufferStrategy -
Field Summary
FieldsModifier and TypeFieldDescriptionActive balls in the game field.Active bricks in the level.private MidiChannelMIDI channel dedicated to game sound effects.private booleanFlag indicating if the fireball power-up is active.private intTimer for fireball power-up duration.private final intThe height of the game arena in pixels.private intThe current game difficulty level.private intThe player's remaining lives.private final doubleThe height of the paddle in pixels.private doubleThe current width of the paddle, which changes with power-ups.private doubleThe actual X-coordinate of the paddle's left edge.private final doubleThe fixed Y-coordinate position of the paddle.Visual particle effects.Active dropping power-up items.private intThe player's current score (Gols).private intThe active game state.private final intGame state: Game over / lost.private final intGame state: Main menu screen.private final intGame state: Paused.private final intGame state: Currently playing.private final intGame state: Victory / level cleared.private SynthesizerMIDI Synthesizer used for retro sound generation.private booleanFlag indicating if MIDI system has been initialized.private doubleThe target X-coordinate of the paddle's left edge for smooth interpolation.private TimerThe high-frequency game loop timer.private intTimer for wide-paddle power-up duration.private final intThe width of the game arena in pixels.Fields inherited from class JComponent
listenerList, TOOL_TIP_TEXT_KEY, ui, UNDEFINED_CONDITION, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, WHEN_FOCUSED, WHEN_IN_FOCUSED_WINDOWFields inherited from class Component
accessibleContext, BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENTFields inherited from interface ImageObserver
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionvoidprivate voidactivatePowerUp(int type) Activates a captured power-up.voidcleanup()Cleans up running loops, timers, and MIDI synthesizer resources to prevent memory leaks.private voiddrawBackground(Graphics2D g2, int w, int h) Draws the stadium background.private voiddrawBrick(Graphics2D g2, Brick brick) Draws a Barça flag themed brick with proper highlight shine.private voiddrawFootball(Graphics2D g2, double x, double y, double r) Draws a football vector graphics ball.private voiddrawPaddle(Graphics2D g2, double x, double y, double w, double h) Draws the striped Barça player paddle.private voiddrawPowerUp(Graphics2D g2, PowerUp pu) Draws floating power-up symbols.private voiddrawSplashOverlay(Graphics2D g2, String title, String sub, String action) Renders overlays for splash, victory, or gameover states.private voidHandles key press inputs based on the current game state.private voidInitializes the brick and ball layouts for the current level.private voidInitializes the MIDI sound system asynchronously.private voidReleases resting balls from the paddle.static voidStandalone main launcher for the Arkanoid game.protected voidprivate voidplayMelody(int[] notes, int[] delays, int[] durations) Plays a sequence melody asynchronously.private voidplaySound(int note, int duration) Plays an 8-bit sound note on a separate thread.private voidPlays victory fanfare and generates celebration particles.private voidResets score, lives, levels, and initializes the first stage.Methods inherited from class JPanel
getAccessibleContext, getUI, getUIClassID, paramString, setUI, updateUIMethods inherited from class 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, updateMethods inherited from class 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, validateTreeMethods inherited from class 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
-
width
private final int widthThe width of the game arena in pixels.- See Also:
-
height
private final int heightThe height of the game arena in pixels.- See Also:
-
paddleY
private final double paddleYThe fixed Y-coordinate position of the paddle.- See Also:
-
paddleHeight
private final double paddleHeightThe height of the paddle in pixels.- See Also:
-
stateMenu
private final int stateMenuGame state: Main menu screen.- See Also:
-
statePlaying
private final int statePlayingGame state: Currently playing.- See Also:
-
statePaused
private final int statePausedGame state: Paused.- See Also:
-
stateGameover
private final int stateGameoverGame state: Game over / lost.- See Also:
-
stateVictory
private final int stateVictoryGame state: Victory / level cleared.- See Also:
-
state
private int stateThe active game state. -
score
private int scoreThe player's current score (Gols). -
lives
private int livesThe player's remaining lives. -
level
private int levelThe current game difficulty level. -
paddleX
private double paddleXThe actual X-coordinate of the paddle's left edge. -
targetPaddleX
private double targetPaddleXThe target X-coordinate of the paddle's left edge for smooth interpolation. -
paddleWidth
private double paddleWidthThe current width of the paddle, which changes with power-ups. -
balls
-
bricks
-
powerUps
-
particles
-
widePaddleTimer
private int widePaddleTimerTimer for wide-paddle power-up duration. -
fireballTimer
private int fireballTimerTimer for fireball power-up duration. -
fireballActive
private boolean fireballActiveFlag indicating if the fireball power-up is active. -
synth
MIDI Synthesizer used for retro sound generation. -
channel
MIDI channel dedicated to game sound effects. -
synthInitialized
private boolean synthInitializedFlag indicating if MIDI system has been initialized. -
timer
The high-frequency game loop timer.
-
-
Constructor Details
-
Arkanoid
public Arkanoid()Constructs a new Arkanoid game panel and registers listeners.
-
-
Method Details
-
initSynth
private void initSynth()Initializes the MIDI sound system asynchronously.Synthesizer is acquired from MidiSystem and loaded with lead Square Lead program. Runs on an autonomous thread to avoid blocking the Event Dispatch Thread during startup.
-
playSound
private void playSound(int note, int duration) Plays an 8-bit sound note on a separate thread.Runs asynchronously using an individual short-lived thread to preserve fluid game physics execution and UI performance.
- Parameters:
note- The MIDI note to play (0-127).duration- The duration in milliseconds.
-
playMelody
private void playMelody(int[] notes, int[] delays, int[] durations) Plays a sequence melody asynchronously.Plays multiple MIDI note events sequentially separated by duration delays.
- Parameters:
notes- Array of MIDI notes.delays- Array of delays between notes.durations- Array of note play durations.
-
initLevel
private void initLevel()Initializes the brick and ball layouts for the current level.Arranges the game bricks to represent a beautiful FCB layout: - The "F" and "B" letters are colored in deep Grana (Type 2), requiring 2 hits. - The "C" letter is colored in rich Azul/Blue (Type 3), requiring 3 hits. - The empty background space is filled with warm Light Yellow bricks (Type 1), requiring 1 hit.
-
resetFullGame
private void resetFullGame()Resets score, lives, levels, and initializes the first stage. -
cleanup
public void cleanup()Cleans up running loops, timers, and MIDI synthesizer resources to prevent memory leaks. -
handleKeyPress
Handles key press inputs based on the current game state.- Parameters:
e- The key event.
-
launchBalls
private void launchBalls()Releases resting balls from the paddle. -
activatePowerUp
private void activatePowerUp(int type) Activates a captured power-up.- Parameters:
type- The power-up type.
-
playVictoryFanfare
private void playVictoryFanfare()Plays victory fanfare and generates celebration particles. -
actionPerformed
Runs the high-frequency animation tick, updating positions, handling physics, checking wall, brick, and paddle collisions, and evaluating win/loss conditions.
- Specified by:
actionPerformedin interfaceActionListener
-
paintComponent
Draws the background arena, scoreboard, paddle, football, bricks, and overlays.
- Overrides:
paintComponentin classJComponent
-
drawBackground
Draws the stadium background.- Parameters:
g2- The graphics context.w- The viewport width.h- The viewport height.
-
drawPaddle
Draws the striped Barça player paddle.- Parameters:
g2- The graphics context.x- The paddle X position.y- The paddle Y position.w- The width of the paddle.h- The height of the paddle.
-
drawFootball
Draws a football vector graphics ball.- Parameters:
g2- The graphics context.x- The ball's center X coordinate.y- The ball's center Y coordinate.r- The radius of the ball.
-
drawBrick
Draws a Barça flag themed brick with proper highlight shine.Renders cracks on damaged bricks based on remaining hit points: - Azul/Blue bricks (Type 3) require 3 hits and show cracks on the 1st and 2nd hits. - Grana bricks (Type 2) require 2 hits and show cracks on the 1st hit. - Light Yellow background bricks (Type 1) require 1 hit and break instantly.
- Parameters:
g2- The graphics context.brick- The brick to render.
-
drawPowerUp
Draws floating power-up symbols.- Parameters:
g2- The graphics context.pu- The power-up object to draw.
-
drawSplashOverlay
Renders overlays for splash, victory, or gameover states.- Parameters:
g2- The graphics context.title- The primary overlay title.sub- The secondary subtitle text.action- The call-to-action prompt.
-
main
Standalone main launcher for the Arkanoid game.- Parameters:
args- Command line arguments.
-

