<%@ EnableSessionState=true %> <% Option Explicit dim thisurl thisURL=Request.ServerVariables("PATH_INFO") & "?" & Request.ServerVariables("QUERY_STRING") const title="Java Games tutorial #3" %>
Current area: HOME -> Java Games tutorial #3

Java Games tutorial #3

BattleshipApp.java:

/**
* The basic framework for a battleship game.
* 
* @author Mark Kreitler
* @version 0.1
*/

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class BattleshipApp extends JFrame implements MouseListener
{
    private static final int GAME_STATE_INTRO = 0;
    private static final int GAME_STATE_SETUP = 1;
    private static final int GAME_STATE_PLAYING = 2;
    private static final int GAME_STATE_GAMEOVER = 3;

    private static final int GAME_WIDTH = 600;
    private static final int GAME_HEIGHT = 500;
    private static final int TITLE_X = 260;
    private static final int TITLE_Y = 225;
    private static final int MOUSE_MSG_X = 228;
    private static final int MOUSE_MSG_Y = 275;
    private static final int RED_GRID_X = 5;
    private static final int RED_GRID_Y = 5;
    private static final int BLUE_GRID_X = 255;
    private static final int BLUE_GRID_Y = 5;
    
    // instance variables
    private Board redBoard;
    private Board blueBoard;
    private FriendlyPlayer friendlyPlayer;
    private EnemyPlayer enemyPlayer;
    private int gameState;

    /**
     * Entry point for code execution.
     */
    public static void main(String[] args) {
    new BattleshipApp();
    }

    /**
     * Constructor for objects of class BattleshipApp
     */
    public BattleshipApp()
    {
        this.setSize(GAME_WIDTH, GAME_HEIGHT);
        this.show();
        this.addMouseListener(this);
        this.gameState = GAME_STATE_INTRO;

        // Initialize the game boards.
        this.redBoard = new Board();
        this.blueBoard = new Board();
    }

    /**
     * Draws the game window.
     */
    public void paint(Graphics gfx) {
        if (this.gameState == GAME_STATE_INTRO) {
            this.drawTitleScreen();
        }
        else if (this.gameState == GAME_STATE_SETUP) {
            this.drawGrids();
        }
    }

    /**
     * Draws the 'Welcome to Battleship' screen.
     */
    private void drawTitleScreen() {
        // Get an object representing the area within the window borders.
        Container clientArea = this.getContentPane();

        // Get the Graphics object associated with the client area.
        Graphics gfx = clientArea.getGraphics();

        // Get the size of the client area.
        int width = clientArea.getWidth();
        int height = clientArea.getHeight();

        gfx.setColor(Color.black);
        gfx.fillRect(0, 0, width, height);

        gfx.setColor(Color.green);
        gfx.drawString("BATTLESHIP", TITLE_X, TITLE_Y);
        gfx.setColor(Color.gray);
        gfx.drawString("(click mouse to continue)", MOUSE_MSG_X, MOUSE_MSG_Y);
    }

    /**
     * Draw the game grids.
     */
    private void drawGrids() {
        // Get an object representing the area within the window borders.
        Container clientArea = this.getContentPane();

        // Get the Graphics object associated with the client area.
        Graphics gfx = clientArea.getGraphics();

        // Get the size of the client area.
        int width = clientArea.getWidth();
        int height = clientArea.getHeight();

        // Fill the background with black.
        gfx.setColor(Color.black);
        gfx.fillRect(0, 0, width, height);

        // Draw the two grids.
        this.redBoard.drawGrid(gfx, Color.red, RED_GRID_X, RED_GRID_Y);
        this.blueBoard.drawGrid(gfx, Color.blue, BLUE_GRID_X, BLUE_GRID_Y);
        
        // Draw the ships on the grids.
        this.redBoard.drawShips(gfx, Color.gray, RED_GRID_X, RED_GRID_Y);
        this.blueBoard.drawShips(gfx, Color.gray, BLUE_GRID_X, BLUE_GRID_Y);
    }

    /**
     * MouseListener methods.
     */
    public void mouseClicked(MouseEvent event) {}

    public void mouseEntered(MouseEvent event) {}

    public void mouseExited(MouseEvent event) {}

    public void mousePressed(MouseEvent event) {}

    public void mouseReleased(MouseEvent event) {
        if (this.gameState == GAME_STATE_INTRO) {
            this.gameState = GAME_STATE_SETUP;
            this.blueBoard.placeComputerShips();
            this.repaint();
        }
    }
}

Board.java:
/**
* Represents a player's board.
* 
* @author Mark Kreitler
* @version 0.1
*/

import java.awt.*;
import java.util.*;

public class Board
{
    // Class variables.
    private static final int ROW_COUNT = 10;
    private static final int COLUMN_COUNT = 10;
    private static final int ROW_PIXEL_HEIGHT = 20;
    private static final int COLUMN_PIXEL_WIDTH = 20;
    private static final int SHIPS_PER_FLEET = 5;

    // Instance variables.
    private RedPeg[] hitMarkers;
    private WhitePeg[] missMarkers;
    private Ship[] fleet;
    private int[][] gridCells;

    // Methods.
    /**
     * Constructor for objects of class Board
     */
    public Board()
    {
        // Initialize the arrays used to store ship info.
        this.fleet = new Ship[SHIPS_PER_FLEET];
        this.gridCells = new int[ROW_COUNT][COLUMN_COUNT];
        
        // Fill the grid cells with empty spaces.
        int i = 0;
        while (i < ROW_COUNT) {
            int j = 0;
            while (j < COLUMN_COUNT) {
                this.gridCells[i][j] = Ship.TYPE_NONE;
                j++;
            }
            
            i++;
        }
    }
    
    /**
     *  Add a ship to the grid.
     */
    public void addShip(Ship newShip) {
        int row = newShip.getRow();
        int col = newShip.getColumn();
        int orientation = newShip.getOrientation();
        int i = 0;
        
        // Add the ship to the fleet array.
        this.fleet[newShip.getType()] = newShip;
        
        if (orientation == Ship.ORIENTATION_UP) {
            while (i < newShip.getSize()) {
                this.gridCells[row - i][col] = newShip.getType();
                i++;
            }
        }
        else if (orientation == Ship.ORIENTATION_RIGHT) {
            while (i < newShip.getSize()) {
                this.gridCells[row][col + i] = newShip.getType();
                i++;
            }
        }
        else if (orientation == Ship.ORIENTATION_DOWN) {
            while (i < newShip.getSize()) {
                this.gridCells[row + i][col] = newShip.getType();
                i++;
            }
        }
        else {
            // Orientation must be LEFT.
            while (i < newShip.getSize()) {
                this.gridCells[row][col - i] = newShip.getType();
                i++;
            }
        }
    }
    
    /**
     *  Places the computer's ships on the board.
     */
    public void placeComputerShips() {
        long seed = System.currentTimeMillis();
        Random randomizer = new Random(seed);
        
        int [] shipType = {Ship.TYPE_AIRCRAFT_CARRIER,
                           Ship.TYPE_BATTLESHIP,
                           Ship.TYPE_CRUISER,
                           Ship.TYPE_SUBMARINE,
                           Ship.TYPE_PT_BOAT};
        int[] shipLength = {5, 4, 3, 3, 2};
        
        int i = 0;
        do {
            int row;
            int col;
            int orientation;
            
            // Randomly generate a row, column, and
            // orientation.
            row = randomizer.nextInt(ROW_COUNT);
            col = randomizer.nextInt(COLUMN_COUNT);
            orientation = randomizer.nextInt(4);
                
            // Check to see if the ship fits on the
            // board at the given row and column.
            boolean bFitsOnBoard = false;
            int testLength = shipLength[i] - 1;
                
            if (orientation == Ship.ORIENTATION_UP) {
                if (row >= testLength) {
                    bFitsOnBoard = true;
                }
            }
            else if (orientation == Ship.ORIENTATION_RIGHT) {
                if (COLUMN_COUNT - col > testLength) {
                    bFitsOnBoard = true;
                }
            }
            else if (orientation == Ship.ORIENTATION_DOWN) {
                if (ROW_COUNT - row > testLength) {
                    bFitsOnBoard = true;
                }
            }
            else if (orientation == Ship.ORIENTATION_LEFT) {
                if (col >= testLength) {
                    bFitsOnBoard = true;
                }
            }
                
            boolean bHitsOtherShips = false;
            // Check to see if the ship hits any
            // other ships on the board.
    
            if (bFitsOnBoard == true) {
                int j;
                if (orientation == Ship.ORIENTATION_UP) {
                    j = 0;
                    while (j < shipLength[i]) {
                        if (this.gridCells[row - j][col] !=
                            Ship.TYPE_NONE) {
                            bHitsOtherShips = true;
                            break;
                        }
                            
                        j++;
                    }
                }
                else if (orientation == Ship.ORIENTATION_RIGHT) {
                    j = 0;
                    while (j < shipLength[i]) {
                        if (this.gridCells[row][col + j] !=
                            Ship.TYPE_NONE) {
                            bHitsOtherShips = true;
                            break;
                        }
                            
                        j++;
                    }
                }
                else if (orientation == Ship.ORIENTATION_DOWN) {
                    j = 0;
                    while (j < shipLength[i]) {
                        if (this.gridCells[row + j][col] !=
                            Ship.TYPE_NONE) {
                            bHitsOtherShips = true;
                            break;
                        }
                            
                        j++;
                    }
                }
                else if (orientation == Ship.ORIENTATION_LEFT) {
                    j = 0;
                    while (j < shipLength[i]) {
                        if (this.gridCells[row][col - j] !=
                            Ship.TYPE_NONE) {
                            bHitsOtherShips = true;
                            break;
                        }
                            
                        j++;
                    }
                }
            }
                    
            if (bFitsOnBoard && !bHitsOtherShips) {
                // Place this ship on the board.
                Ship newShip = new Ship(shipType[i],
                                        orientation,
                                        row,
                                        col,
                                        shipLength[i]);
                this.addShip(newShip);
                    
                // Go on to the next ship.
                i++;
            }
                
        } while (i < SHIPS_PER_FLEET);
    }
    
    /**
     *  Draws the ships to the grid.
     */
    public void drawShips(Graphics gfx, Color shipColor, int startX, int startY) {
        // Set the draw color.
        gfx.setColor(shipColor);
        
        int row = 0;    // Start at the first row.
        do {
            
            int col = 0;// Start at the first column.
            do {

                // Is the cell empty?
                if (this.gridCells[row][col] != Ship.TYPE_NONE) {
                    // No--the cell contains part of a ship.
                    
                    // Calculate the starting position of the cell.
                    int x = startX + col * COLUMN_PIXEL_WIDTH;
                    int y = startY + row * ROW_PIXEL_HEIGHT;

                    // Draw in a box that's smaller than the cell.
                    gfx.fillRect(x + 2, y + 2,
                                 COLUMN_PIXEL_WIDTH - 3,
                                 ROW_PIXEL_HEIGHT - 3);
                }
                
                col++;  // Move on to the next column.
            } while (col < COLUMN_COUNT); 
            
            row++;      // Move on to the next row.
        } while (row < ROW_COUNT);
    }
    
    /**
     * Draws a grid on the screen.
     */
    public void drawGrid(Graphics gfx, Color gridColor, int startX, int startY) {
        // Set the line color.
        gfx.setColor(gridColor);

        // Draw the horizontal lines.
        int lineCounter = 1;
        int x = startX;
        int y = startY;
        while (lineCounter <= 11) {
            gfx.drawLine(x, y, x + COLUMN_PIXEL_WIDTH * COLUMN_COUNT, y);
            y = y + ROW_PIXEL_HEIGHT;
            lineCounter++;
        }

        // Draw the vertical lines.
        lineCounter = 1;
        x = startX;
        y = startY;
        while (lineCounter <= 11) {
            gfx.drawLine(x, y, x, y + ROW_PIXEL_HEIGHT * ROW_COUNT);
            x = x + COLUMN_PIXEL_WIDTH;
            lineCounter++;
        }
    }
}