Class AgiKart
java.lang.Object
java.awt.Component
java.awt.Container
javax.swing.JComponent
javax.swing.JPanel
uno.anahata.asi.swing.games.AgiKart
- All Implemented Interfaces:
ActionListener, ImageObserver, MenuContainer, Serializable, EventListener, Accessible
AgiKart is a high-performance pseudo-3D retro kart racing game in Java Swing.
Utilizing a Mode 7 style perspective ground projection algorithm, depth-sorted 3D billboard rendering for sprites (trees, item boxes, karts, and obstacles), responsive drift-and-slide kart physics, and waypoint-following AI opponents, it provides a highly polished, authentic classic 16-bit racing experience. It also features procedural audio synthesis using Java's built-in MIDI Synthesizer.
- Author:
- anahata
- See Also:
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionprivate static classData object model for spawning item boxes.private static classData object model for tracking karts.private static classWorld particle model for drift sparks and boost trails.private static classData object model for placing Pine Trees.private static classData object model for banana slip obstacles.private static interfaceFunctional Interface defining custom sprite-drawing instructions.private static classDTO containing projected coordinates and scales for drawing billboarded entities.private static classData object model for traveling tracking shells.private static classData object model for spawning collectible mushrooms on the track.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 TypeFieldDescriptionprivate final List<AgiKart.PlacedBanana> List of bananas placed on the track.private doubleprivate final doubleHeight of the camera above the ground plane.private intThe starting countdown timer frames.private longprivate MidiChannelContinuous MIDI channel for engine humming sound.private booleanWarning triggered when the player enters the final lap.private doubleField of View perspective scaling factor.private booleanFlag indicating if the player has finished all laps.private intGlobal frame tick counter.private final intHorizon row index on the low-res screen buffer.private static final double[][]Center coordinates for item box spawners.private final List<AgiKart.ItemBox> List of active item boxes in the world.private booleanBraking / Reverse flag.private booleanSteering flag (turning left).private booleanSteering flag (turning right).private booleanAcceleration flag.private doubleprivate MidiChannelThe main MIDI channel for lead synthesizers.private static final double[][]Coordinates for stationary roadside Oil Slicks that trigger spinouts.private final List<AgiKart.KartEntity> The list of AI competitor entities.private final List<AgiKart.Particle> private AgiKart.KartEntityThe human player entity.private booleanFlag indicating if the race has started (after countdown).private longprivate static final intThe logical screen height for the Mode 7 low-res rendering buffer.private static final intThe logical screen width for the Mode 7 low-res rendering buffer.private BufferedImageLow-resolution rendering canvas.private int[]Direct pointer to the low-resolution canvas pixels.private intCamera screen shake intensity timer.private final List<AgiKart.ThrownShell> List of active red shells traveling on the track.private intDirect blaster shell fire cooldown.private final ExecutorServiceSingle-threaded pool for non-blocking procedural sound playbacks.private SynthesizerMIDI Synthesizer interface.private TimerHigh-frequency game loop timer.private static final double[][]Coordinates representing the center loop of the race track.private final List<AgiKart.TrackMushroom> List of active roadside collectible Super Mushrooms.private int[]Direct pointer to the track texture map pixels.private BufferedImageHigh-resolution, off-screen track texture map.private final List<AgiKart.PineTree> List of static tree coordinates placed alongside the road borders.private static final intThe actual display height of the game window.private static final intThe actual display width of the game window.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
ConstructorsConstructorDescriptionAgiKart()Constructs a new AgiKart game panel and triggers resources initialization. -
Method Summary
Modifier and TypeMethodDescriptionvoidprivate intCalculates the player's real-time position rank compared to other karts.private voidCalculates bumping/colliding bouncing interactions between karts.private voidEvaluates item pickup boxes and obstacle collisions on the track.voidcleanup()Shuts down background threads and releases MIDI Synthesizer resources.private voiddrawItemBox(Graphics2D g, double sx, double sy, double scale) Vector draws a hovering, glowing item box spawner.private voiddrawItemIcon(Graphics2D g, int cx, int cy, int size, String itemType) Vector draws stunning retro-quality HUD item icons.private voiddrawPineTree(Graphics2D g, double sx, double sy, double scale) Vector draws a beautiful pine tree billboard sprite.private voiddrawPlacedBanana(Graphics2D g, double sx, double sy, double scale) Vector draws a placed banana peel on the road.private voiddrawThrownShell(Graphics2D g, double sx, double sy, double scale) Vector draws a traveling homing red shell on the road.private voiddrawTrackMushroom(Graphics2D g, double sx, double sy, double scale) Vector draws a gorgeous 3D billboard mushroom standing on the ground.private voiddrawWorldKart(Graphics2D g, double sx, double sy, double scale, Color color, String name, double angle, int spinTimer) Vector draws a gorgeous detailed kart competitor with chassis, wheels, driver, and nametag.private voidGenerates a beautiful 1024x1024 track texture procedurally in memory.private voidBinds keyboard controls to manage player movement and item triggers.private voidProgrammatically populates environment details, including curbside pine trees and item boxes.private voidInitializes karts, setting up a starting grid behind the start-finish line.private voidInitializes the Java MIDI Synthesizer and configures instrument patching.static voidStandalone executable entry-point.protected voidprivate voidPlays an 8-bit retro melodic fanfare of the classic Barça Anthem.private voidPlays a sweeping pitch sound during a mushroom boost.private voidPlays a descending pitch sound when a kart spins out.private voidPlays a high-intensity warning fanfare when entering the final lap.private voidPlays a high-pitched ding sound when picking up items.private voidPlays a grand championship lap completed fanfare.private voidplayNoteAsync(int note, int velocity, int durationMs) Dispatches a musical note command asynchronously to prevent blocking the game thread.private AgiKart.SpriteProjectionprojectWorldPoint(double wx, double wy, double wz, double camX, double camY, double cos, double sin) Projects a 3D world coordinate onto the low-resolution screen canvas relative to the camera.private voidGathers, depth-sorts, and draws all 3D projected billboard sprites on the screen.private voidRenders background mountain sceneries scrolling smoothly as the player turns.private voidRenders a highly-polished high-resolution HUD, featuring real-time minimaps and race positions.private voidImplements a fast, hardware-friendly Mode 7 ground perspective floor caster.private voidResets the entire race standings and parameters to begin anew.private voidFires a green shell directly in front of the player's kart with a cooldown.private voidSorts the racing competitors based on lap counts and next waypoint progress.private voidExecutes AI item activation decisions based on current item held.private voidTriggers the player's active item and manages world placements.private voidUpdates an AI competitor's intelligence, steering vectors, and waypoint progress.private voidUpdates active traveling red shells on track checkpoints towards targets.private voidUpdates waypoints checklist and lap completions for karts.private voidUpdates the player's kart speed, angles, drift sliding, and coordinate bounds.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
-
SCREEN_WIDTH
private static final int SCREEN_WIDTHThe logical screen width for the Mode 7 low-res rendering buffer.- See Also:
-
SCREEN_HEIGHT
private static final int SCREEN_HEIGHTThe logical screen height for the Mode 7 low-res rendering buffer.- See Also:
-
WINDOW_WIDTH
private static final int WINDOW_WIDTHThe actual display width of the game window.- See Also:
-
WINDOW_HEIGHT
private static final int WINDOW_HEIGHTThe actual display height of the game window.- See Also:
-
TRACK_POINTS
private static final double[][] TRACK_POINTSCoordinates representing the center loop of the race track. -
ITEM_BOX_LOCATIONS
private static final double[][] ITEM_BOX_LOCATIONSCenter coordinates for item box spawners. -
trees
List of static tree coordinates placed alongside the road borders. -
itemBoxes
List of active item boxes in the world. -
bananas
List of bananas placed on the track. -
shells
List of active red shells traveling on the track. -
trackMushrooms
List of active roadside collectible Super Mushrooms. -
player
The human player entity. -
opponents
The list of AI competitor entities. -
cameraHeight
private final double cameraHeightHeight of the camera above the ground plane.- See Also:
-
fov
private double fovField of View perspective scaling factor. -
horizon
private final int horizonHorizon row index on the low-res screen buffer.- See Also:
-
screenBuffer
Low-resolution rendering canvas. -
screenPixels
private int[] screenPixelsDirect pointer to the low-resolution canvas pixels. -
trackTexture
High-resolution, off-screen track texture map. -
trackPixels
private int[] trackPixelsDirect pointer to the track texture map pixels. -
timer
High-frequency game loop timer. -
keyLeft
private boolean keyLeftSteering flag (turning left). -
keyRight
private boolean keyRightSteering flag (turning right). -
keyUp
private boolean keyUpAcceleration flag. -
keyDown
private boolean keyDownBraking / Reverse flag. -
raceStarted
private boolean raceStartedFlag indicating if the race has started (after countdown). -
countdownFrames
private int countdownFramesThe starting countdown timer frames. -
gameOver
private boolean gameOverFlag indicating if the player has finished all laps. -
gameTicks
private int gameTicksGlobal frame tick counter. -
shootCooldown
private int shootCooldownDirect blaster shell fire cooldown. -
finalLapWarningPlayed
private boolean finalLapWarningPlayedWarning triggered when the player enters the final lap. -
screenShake
private int screenShakeCamera screen shake intensity timer. -
OIL_SLICKS
private static final double[][] OIL_SLICKSCoordinates for stationary roadside Oil Slicks that trigger spinouts. -
soundPool
Single-threaded pool for non-blocking procedural sound playbacks. -
synth
MIDI Synthesizer interface. -
midiChannel
The main MIDI channel for lead synthesizers. -
engineChannel
Continuous MIDI channel for engine humming sound. -
raceStartTime
private long raceStartTime -
currentLapStartTime
private long currentLapStartTime -
bestLapTime
private double bestLapTime -
lastLapTime
private double lastLapTime -
particles
-
-
Constructor Details
-
AgiKart
public AgiKart()Constructs a new AgiKart game panel and triggers resources initialization.
-
-
Method Details
-
playNoteAsync
private void playNoteAsync(int note, int velocity, int durationMs) Dispatches a musical note command asynchronously to prevent blocking the game thread. -
playItemPickupSound
private void playItemPickupSound()Plays a high-pitched ding sound when picking up items. -
playBoostSound
private void playBoostSound()Plays a sweeping pitch sound during a mushroom boost. -
playCrashSound
private void playCrashSound()Plays a descending pitch sound when a kart spins out. -
playFinalLapSound
private void playFinalLapSound()Plays a high-intensity warning fanfare when entering the final lap. -
playLapCompletedSound
private void playLapCompletedSound()Plays a grand championship lap completed fanfare. -
initSound
private void initSound()Initializes the Java MIDI Synthesizer and configures instrument patching. -
generateTrackTexture
private void generateTrackTexture()Generates a beautiful 1024x1024 track texture procedurally in memory.Renders a forest green background grid, draws a custom winding race course, overlays red-and-white striped curb borders, and stamps a checkered finish line.
-
initEnvironment
private void initEnvironment()Programmatically populates environment details, including curbside pine trees and item boxes. -
initKarts
private void initKarts()Initializes karts, setting up a starting grid behind the start-finish line. -
initControls
private void initControls()Binds keyboard controls to manage player movement and item triggers. -
triggerPlayerItem
private void triggerPlayerItem()Triggers the player's active item and manages world placements. -
shootGreenShellDirect
private void shootGreenShellDirect()Fires a green shell directly in front of the player's kart with a cooldown. -
resetGame
private void resetGame()Resets the entire race standings and parameters to begin anew. -
cleanup
public void cleanup()Shuts down background threads and releases MIDI Synthesizer resources. -
paintComponent
Processes the 3D projection, depth-sorted blitting, and HUD rendering overlays.
- Overrides:
paintComponentin classJComponent
-
renderMode7
private void renderMode7()Implements a fast, hardware-friendly Mode 7 ground perspective floor caster. -
renderBackgroundSceneries
Renders background mountain sceneries scrolling smoothly as the player turns. -
render3DSprites
Gathers, depth-sorts, and draws all 3D projected billboard sprites on the screen. -
projectWorldPoint
private AgiKart.SpriteProjection projectWorldPoint(double wx, double wy, double wz, double camX, double camY, double cos, double sin) Projects a 3D world coordinate onto the low-resolution screen canvas relative to the camera. -
drawPineTree
Vector draws a beautiful pine tree billboard sprite. -
drawItemBox
Vector draws a hovering, glowing item box spawner. -
drawPlacedBanana
Vector draws a placed banana peel on the road. -
drawTrackMushroom
Vector draws a gorgeous 3D billboard mushroom standing on the ground. -
drawThrownShell
Vector draws a traveling homing red shell on the road. -
drawWorldKart
private void drawWorldKart(Graphics2D g, double sx, double sy, double scale, Color color, String name, double angle, int spinTimer) Vector draws a gorgeous detailed kart competitor with chassis, wheels, driver, and nametag. -
renderHUD
Renders a highly-polished high-resolution HUD, featuring real-time minimaps and race positions. -
drawItemIcon
Vector draws stunning retro-quality HUD item icons. -
calculatePlayerPosition
private int calculatePlayerPosition()Calculates the player's real-time position rank compared to other karts. -
sortCompetitors
Sorts the racing competitors based on lap counts and next waypoint progress. -
actionPerformed
Executes the primary high-frequency physics tick, collisions, and state transitions.
- Specified by:
actionPerformedin interfaceActionListener
-
updatePlayerPhysics
private void updatePlayerPhysics()Updates the player's kart speed, angles, drift sliding, and coordinate bounds. -
updateAICompetitor
Updates an AI competitor's intelligence, steering vectors, and waypoint progress. -
triggerAIItem
Executes AI item activation decisions based on current item held. -
updateKartWaypoint
Updates waypoints checklist and lap completions for karts. -
updateHomingShells
private void updateHomingShells()Updates active traveling red shells on track checkpoints towards targets. -
checkBumpingCollisions
private void checkBumpingCollisions()Calculates bumping/colliding bouncing interactions between karts. -
checkItemOverlaps
private void checkItemOverlaps()Evaluates item pickup boxes and obstacle collisions on the track. -
main
Standalone executable entry-point. -
playBarsaAnthem
private void playBarsaAnthem()Plays an 8-bit retro melodic fanfare of the classic Barça Anthem.
-

