Here’s a simple shoot-’em-up game in Java that you can run on OnlineGDB. Since OnlineGDB supports text-based Java programs and does not have graphical support, the game will be console-based.
The player controls a spaceship (^) that can move left and right while shooting (|) at incoming enemies (X). The game ends when an enemy reaches the bottom:
The game is displayed on a 10×20 grid.
The player can move left (a) and right (d) and shoot (w).
Enemies (X) fall from the top.
The game ends when an enemy reaches the bottom or the player shoots all enemies.
import java.util.Scanner;
import java.util.Random;
public class Main {
static final int WIDTH = 20;
static final int HEIGHT = 10;
static char[][] grid = new char[HEIGHT][WIDTH];
static int playerX = WIDTH / 2;
static int bulletY = -1;
static int bulletX = -1;
static int enemyX;
static int enemyY = 0;
static boolean gameOver = false;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Random random = new Random();
enemyX = random.nextInt(WIDTH);
while (!gameOver) {
updateGrid();
printGrid();
System.out.print(“Move (a/d) or Shoot (w): “);
char move = scanner.next().charAt(0);
handleInput(move);
moveEnemy();
checkCollision();
}
System.out.println(“Game Over!”);
}
static void updateGrid() {
for (int i = 0; i < HEIGHT; i++)
for (int j = 0; j < WIDTH; j++)
grid[i][j] = ‘ ‘;
if (bulletY >= 0) grid[bulletY][bulletX] = ‘|’;
grid[enemyY][enemyX] = ‘X’;
grid[HEIGHT – 1][playerX] = ‘^’;
}
static void printGrid() {
for (char[] row : grid) {
for (char cell : row) System.out.print(cell);
System.out.println();
}
}
static void handleInput(char move) {
if (move == ‘a’ && playerX > 0) playerX–;
if (move == ‘d’ && playerX < WIDTH – 1) playerX++;
if (move == ‘w’ && bulletY == -1) {
bulletX = playerX;
bulletY = HEIGHT – 2;
}
moveBullet();
}
static void moveBullet() {
if (bulletY >= 0) bulletY–;
if (bulletY < 0) bulletX = -1;
}
static void moveEnemy() {
enemyY++;
if (enemyY >= HEIGHT – 1) gameOver = true;
}
static void checkCollision() {
if (bulletY == enemyY && bulletX == enemyX) {
System.out.println(“Enemy Hit!”);
enemyY = 0;
enemyX = new Random().nextInt(WIDTH);
bulletY = -1;
}
}
}