Here you will find the source code for the space game, as described in the upcoming book Graphic Guide to Java

Copyright 2025 Antony Lees

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
// ship direction
int xDirection = 0;
int yDirection = 0;
// coordinates of the ship
int shipX = 0;
int shipY = 0;

int score = 0;

void setup() {
// screen size
size(600,400);
// black background
background(0);
// white lines
stroke(255);
initialiseShip();
}

void initialiseShip() {
// choose random direction
xDirection = (int) random(-2, 2);
yDirection = (int) random(-2, 2);
// start in the middle of the screen
shipX = width/2;
shipY = height/2;
}

void draw() {
// redraw the background
background(0);

// display near the top of the screen
String scoreString = String.format("Score: %1s", score);
text(scoreString, width/2, 10);

// draw the targeting lines so that they leave a space around the mouse pointer
line(0, 0, mouseX - 20, mouseY- 20);
line(width, 0, mouseX + 20, mouseY - 20);
line(0, height, mouseX - 20, mouseY + 20);
line(width, height, mouseX + 20, mouseY + 20);
//display the current mouse coordinates
String coords = String.format("(%1s,%2s)",mouseX, mouseY);
text(coords, mouseX, mouseY);

// draw the ship
rectMode(CENTER);
rect(shipX, shipY, 5, 5);
// left wing
line(shipX - 10, shipY - 10, shipX - 10, shipY + 10);
line(shipX, shipY, shipX - 10, shipY);
// right wing
line(shipX + 10, shipY - 10, shipX + 10, shipY + 10);
line(shipX, shipY, shipX + 10, shipY);
// update coordinates for next time
shipX = shipX + xDirection;
shipY = shipY + yDirection;

// if current coordinates mean the ship has left the screen
if (shipX < 0 || shipX > width || shipY < 0 || shipY > height) {
// new ship
initialiseShip();
}
}

void mouseClicked() {
// if the left mouse button was clicked
if (mouseButton == LEFT) {
// fire!
stroke(0, 255, 0);
strokeWeight(3);
line(0, height/2, mouseX, mouseY);
line(width, height/2, mouseX, mouseY);
// reset colour
stroke(255);
strokeWeight(1);
// if the button was pressed in the region of the ship
if (mouseX > (shipX - 10) && mouseX < (shipX + 10)) {
// add 1 to the score
score += 1;
initialiseShip();
}
}
}