Click here to Skip to main content
15,892,839 members
Articles / Programming Languages / JScript .NET

Star Trek "Galactic Conquest" Game Contest Submission (Java)

Rate me:
Please Sign up or sign in to vote.
4.27/5 (6 votes)
6 Aug 2008CPOL3 min read 53.3K   951   25  
Star Trek "Galactic Conquest" Game Contest Submission (Java)
import java.util.ArrayList;
import java.util.Iterator;

/**
 * Galaxy Conquest. 
 *
 * @author Robert Bettinelli 
 * @version 1.0.0
 */
public class GBattleGame
{
    private int difficulty;
    private int bases = 3;
    private int planets = 6;
    private int wormHoles = 2;
    private int sun = 1;
    private boolean sunUse = false;
    private int quadSizeX = 5;
    private int quadSizeY = 5;
    private int sectSizeX = 6;
    private int sectSizeY = 6;
    private boolean LRS[][];
    private boolean jumpFlag = false; 
     
    private static final int OUTMAIN = 0; 
    private static final int OUTSTAT = 1;
    private static final int OUTAUX = 2;
    private static final int OUTMENU = 3;
    private static final int OUTTITLE = 4;
    private static final int OUTSCRN = 6;
    
    private Quadrant[][] quad;
    private Player player;
    private Util util;
    private Sound sound;
    private ArrayList<Command> commands;
    private String validCommands;
 
    /**
    * Constructor for objects of class GBattleGame
    */
    public GBattleGame()
    {
         play();         // Start Game
    }
    
    /**
    * Initialize All things Game !
    */
    private void init()                                                     // This is the Whole Kit and Ka-boodle.
    {                                                                       // ========================================
        util = new Util(5);                                                 // Initialize the Utilities Class
        util.initWindow();                                                  // Initialize GUI Window
        sound = new Sound();                                                // Initialize the Sound Class
        util.setScroll(true);                                               // Set No Scrolling
        sound.setAudio(true);                                               // Set No Audio
        initWelcome();                                                      // Welcome Notice
        LRS = new boolean[quadSizeX+1][quadSizeY+1];                        // Set LRS Size 
        initLRS();                                                          // Clear LRS
        quad = new Quadrant[quadSizeX+1][quadSizeY+1];                      // Set Galaxy Size
        commands = new ArrayList<Command>();                                // Initiate Command Space. 
        initCommands();                                                     // Initiate Menu Commands & Dmaage Control
        player = new Player("New Player","Galactica",28,40);                // Create Player Instance (Name, Ship, Baddies, # of Turns)
        createGalaxy();                                                     // Create Galaxy (Empty)
        player.setPlayerName(util.inStr("Please Enter your Name : "));      // Set Player Name
        player.setShipName(util.inStr("Ship Name : "));                     // Set Ship Name
        difficulty();                                                       // Difficulty Set
        
        populateStuffUnEven((player.getBaddie()*750)/1000,"X",0);                        // Enemy Fighter (UnEven Distribute Test)
        populateStuffUnEven((player.getBaddie()*250)/1000,"V",(util.rNumber(350)+150));  // Enemy Battleship(UnEven Distribute Test)
        
        populateStuffEven((2*(quadSizeX+1)*(quadSizeY+1)),"*");             // Stars (Even Distribute)
        populateStuffUnEven(bases,"@",0);                                   // Bases (UnEven Distribute)
        populateStuffUnEven(planets,"P",0);                                 // Planets (UnEven Distribute)
        populateStuffUnEven(wormHoles,"W",0);                               // WormHoles (UnEven Dist.)
        populateStuffUnEven(sun,"S",0);                                     // Sun (UnEven Dist.)
        populateStuffUnEven(1,"Y",0);                                       // Ship (UnEven Distribute)
    }
    
    /**
    * Create Galaxy. Init. Quadrant.
    * Quadrant will Init. Sectors. 
    */
    private void createGalaxy()
    {
        for (int x=0;x<=quadSizeX;x++)
        {
            for (int y=0;y<=quadSizeY;y++)
            {
                quad[x][y] = new Quadrant(sectSizeX,sectSizeY);             // Each quadof Quadrant Class
            }
        }
    }
    
    /**
    * Main Play Routine. 
    */
    public void play()
    {
        // Initialize Galaxy And Post Welcome. 
        init();
        // Play Loop.
        boolean finished = false;
        while (! finished)
        {
            // display Play Screen
            drawScreen();
            // Get & Process New Command. 
            String commandEntry = util.inStr("Command >> ");
            // 
            finished = processCommand(commandEntry);
        }
        // Game Quit/Done. 
        util.toScr(OUTMAIN,"\nMCP reports Simulation Terminated - End of Line. \n");
        //Play Exit Sound
        sound.playSound("EOL.wav");
        util.inStr("Hit [EXECUTE]");
        //End.
        System.exit(0);
    }
    private boolean validate(String command)
    {
        boolean valid = false;
        for(int x =0; x < validCommands.length();x++)
        {
            if (command.equals(validCommands.substring(x,x+1)))
            {
                valid = true;
            }
        }
        return valid;
    }
    
    /**
    * Generic Input Routine 
    * 
    * @param command  (From Command Processor) 
    * 
    * @return wantToQuit boolean if Done.  
    */
    private boolean processCommand(String command)
    {
        boolean wantToQuit = false;
        // No Char Check Otherwise Fill it!
        backDoorCheck(command);
        if (command.equals("")) 
        {
            command = "-";
        }
        // For Command Entry Check 1 Character only. 
        boolean validCommand = validate(command);
        if (!validCommand)
        {
            command = "-";
        }
        switch (command.charAt(0))
        {
            case 'j':                           //Quad & Sector JumpNav
                goMove(command.charAt(0));
                break;
            case 't':                           //Sector Thruster
                goMove(command.charAt(0));
                break;
            case 'f':  //Fire
                goFire();
                break;
            case 'x':  //Nuke
                goNuke();
                break;
            case 's':  //Shield
                goSheild();
                break;
            case 'r':  //SRS
                goSRS();
                break;
            case 'l':  //LRS
                goLRS();
                break;
            case 'a':  //LR Sat
                goSAT();
                break;
            case 'd':  //Damage
                systemsEval();
                break;
            case 'p':   // Planet Survey
                goPlanet();
                break;
            case 'o':  //Options
                goOptions();
                break;
            case 'h':  //Help
                util.readFileDisp("Help.txt");
                break;
            case 'q':  //Quit
                return true;
            default:
                // Bad Command if it passes all previous.
                util.sysNotice("Computer Command... Refused.");
                util.sysNotice("Review Technical Manual.");
                sound.playSound("c132.wav");
                return false;
        }
        // =================================== Win, Loose, Retaliation & Repair.   
        
        wantToQuit = check_Win(); 
        if (!wantToQuit)
        {
            goEnemy();
            wantToQuit = check_Die();
        }
        if (!wantToQuit)
        {
            repairDamage();
            systemsRepair();
        }
        return wantToQuit;
    }
    
    /**
     * Backdoor! - Development System / God System. 
     */
    private void backDoorCheck(String command)
    {
        boolean commandProcessed = false;               
        if(command.equals("whatcanido"))                //Display Available Commands. 
        {
            util.sysNotice("Commands My Lord :");
            util.sysNotice("iwantenergy");
            util.sysNotice("iwantnuke");
            util.sysNotice("iwantprobe");
            util.sysNotice("godsayschangecontent");
            util.sysNotice("hammerme");
            util.sysNotice("fixallofme");
            util.sysNotice("whatcanido");
        }
        if(command.equals("iwantenergy"))               
        {
            player.storeEnergy(2000);
            commandProcessed = true;
        }
        if(command.equals("iwanttime"))
        {
            player.setCountDown((player.getCountDown()+25));
            commandProcessed = true;
        }
        if(command.equals("iwantnuke"))
        {
            player.addNuke(5);
            commandProcessed = true;
        }
        if(command.equals("iwantprobe"))
        {
            player.addProbe(2);
            commandProcessed = true;
        }
        if(command.equals("godsayschangecontent"))
        {
            util.sysNotice("How May I serve thee ? ");
            int x2 = util.inInt("Sector   [X] :",sectSizeX,0);
            int y2 = util.inInt("Sector   [Y] :",sectSizeY,0);
            String change = util.inStr("Content : X,Z,V,C,.,S,W,*,0-6 ?");
            quad[player.getPlayerQX()][player.getPlayerQY()].setSpace(x2,y2,change); // NO TEST!
            commandProcessed = true;
        }
        if(command.equals("hammerme"))
        {
            systemsDamage(100);
            commandProcessed = true;
        }
        if(command.equals("fixallofme"))
        {
            damageClear();
        }
        if (commandProcessed) 
        {
            sound.playSound("matrix.wav");
            util.sysNotice("Glitch In the Matrix. Re-Initalizing Systems.");
        }
    }
  
    /** 
     * Check for win > 1 Win Condition - have you killed everything?
     */
    private boolean check_Win()
    {
        // =================================== Check Win?       
        boolean win_Check = false;
        // Win?
        if (player.getBaddie() <= 0) 
        {
            util.sysNotice("You have beaten all the Enemies!!!!");
            util.sysNotice("        >> YOU WIN!! <<            "); 
            // Play Win Song.
            win_Check = true;
        }
        return win_Check;
    }
    
    /**
     * Check to see if your Dieing or Toast - 3 Die Conditions : Hull / Energy / CountDown.  
     */
    private boolean check_Die()
    {
        boolean die_Check = false;
         if (player.getEnergy() <= 300)
        {
            sound.playSound("ELOW.wav");
            util.sysNotice("Energy Low!!");
        }       
        // Empty Energy. 
        if (player.getEnergy() <= 0)
        {
            util.sysNotice("You are out of Energy!!");
            util.sysNotice("Enivornment systems fail."); 
            util.sysNotice("Your ship floats in Space - You Loose!");
            die_Check  = true;
        }
        
        // Ship Check 
        if (player.getHull() < 0)
        {
            util.sysNotice("The Hull Colapses!");
            util.sysNotice("Your Ship Explodes! - Your Dead!");
            die_Check  = true;
        }
        
        //Outta Time.  
        if (player.getCountDown() <= 0)
        {
           sound.playSound("OOT.wav");
           util.sysNotice("Out of Time - The  Enemy Takes Over!");
           util.sysNotice("The Federation is now Enslaved.");
           die_Check  = true; 
        }
        
         return die_Check;
    }
    
    /**
     *  Planet Recovery System. - Wheel of Fortune. 
     */
    private void goPlanet()
    {
        // Get Planet To Check. 
        util.sysNotice("Confirm Planet Location : ");
        int x2 = util.inInt("Sector   [X] :",sectSizeX,0);
        int y2 = util.inInt("Sector   [Y] :",sectSizeY,0);
        // Randomize 1) Time / 2) Energy / 3) Nuke / 4 Nothing. (1 Time Use/Planet) ( utilize Shield unit for flag)
        // 1st a Planet Check 
        String planetType = quad[player.getPlayerQX()][player.getPlayerQY()].getSpace(x2,y2);
        // Set Initial Planet Value. 
        int planetValue = -1;
        try
        {
            planetValue = Integer.valueOf(planetType).intValue();
        }
        catch(NumberFormatException e)
        {
        }
        // If PlanetValue wasn't Changed then no Valid Planet.  
        if (planetValue > -1)
        {
        // Check if Already Searched.
        if (quad[player.getPlayerQX()][player.getPlayerQY()].getSheild(x2,y2) > 0)
        {
            // Determine Which Reward (if Any)
            int reward = util.rNumber(4)+1;
            switch (reward)
            {
                case 1:         // Add Days.
                    int days = util.rNumber(3);
                    util.sysNotice("Temporal Anomoly Unit Found Add ["+days+"]!");
                    player.setCountDown((player.getCountDown()+days));
                    break;
                case 2:         // Add Energy
                    int energy = util.rNumber(750)+250;         // Recover energy used + Random if found. 
                    util.sysNotice("Crystal Storage Compartment contains ["+energy+"]!");
                    player.storeEnergy(energy);
                    break;
                case 3:         // Add Nukes
                    int nuke = util.rNumber(3);
                    util.sysNotice("Unused nuke Casings found! Salvaged ["+nuke+"] units!");
                    player.addNuke(nuke);
                    break;
                case 4:         // Add Probe
                    util.sysNotice("Unused probe Casings found! Salvaged [1] unit!");
                    player.addProbe(1);
                    break;
                case 5:         // NOTHING!!!
                    util.sysNotice("Nothing Found!");
                    break;
            }    
            // Set Conditions & usage. 
            quad[player.getPlayerQX()][player.getPlayerQY()].hitSheild(x2,y2,75);;      // Remove preset of 75.
            player.yearPass();                                                          // Costs a Day.
            player.useEnergy(250);                                                      // Costs 250 Energy. 
        }
        else
        {
            util.sysNotice("Planet has already been searched.");
        }
        }
        else
        {
            util.sysNotice("No Planet @ That Location.");
        }
    }
   
    /**
     *  Long Range Sensors LRS
     */
    private void goLRS()
    {
        // Long Range Scan Text Information.
        util.toScr(OUTMAIN," < Long Range Sensor > \n");
        util.toScr(OUTMAIN," ===============================================\n");
        boolean scrollSet = util.getScroll();
        util.setScroll(true);
        sound.playSound("SCAN.wav");
        util.toScr(OUTMAIN,"Scanning .......................................\n");
        util.setScroll(scrollSet);
        util.toScr(OUTMAIN," * Scan in Format of : \n");
        util.toScr(OUTMAIN,"  /------- Stars\n");
        util.toScr(OUTMAIN,"  |/------ Bases\n");
        util.toScr(OUTMAIN,"  ||/----- Planets\n");
        util.toScr(OUTMAIN,"  |||/---- Enemies\n");
        util.toScr(OUTMAIN,"  |||| \n");
        util.toScr(OUTMAIN,"  ???? <- Quadrant Details - See Main Screen.\n");
        util.toScr(OUTMAIN," ===============================================\n");
        activateLRS(player.getPlayerQX(),player.getPlayerQY());
        // Galaxy Display based on LRS Array. (NEW Display to Graphic Screen
        String collectQuad = "";
        collectQuad += "     | -----------======== Y ========--------- |$";
        collectQuad += "  X  | - 0- | - 1- | - 2- | - 3- | - 4- | - 5- |$";
        collectQuad += "---- | ---- | ---- | ---- | ---- | ---- | ---- |$";
        //Cycle Quadrant
         for(int x = 0; x <= quadSizeX;x++)
         {
            String lrsLineOut = "- "+x+"- ";
            String sepLineOut = "---- ";
            for (int y = 0; y <=quadSizeY;y++)
            {
                if(LRS[x][y] == true)
                {
                   if ((x == player.getPlayerQX()) && (y == player.getPlayerQY()))
                   {
                       lrsLineOut +=  "|>"+quad[x][y].getQuadDetails()+"<";
                   }
                   else
                   {
                       lrsLineOut += "| "+quad[x][y].getQuadDetails()+" ";
                   }
                }
                else
                {
                   lrsLineOut += "| ???? "; 
                }
                sepLineOut += "| ---- ";
            }
            collectQuad += lrsLineOut+"|$";
            collectQuad += sepLineOut+"|$";
        }
        // Display Graphic
        util.toScr(OUTSCRN,collectQuad);
        // Display Till Hit Button.
        util.inStr("Hit [EXECUTE] to Continue.");
        // Yes - the scan took time. 
        player.yearPass();
    }
    
    
    /**
     * Short Range Sensors SRS
     */
    private void goSRS()
    {
        sound.playSound("SCAN.wav");
        // Just a collection of Quadrant information.
        String QuadDetails = quad[player.getPlayerQX()][player.getPlayerQY()].getQuadDetails();
        // Display Info Collected. 
        int totalLocs = (sectSizeX+1)* (sectSizeY+1);
        util.toScr(OUTMAIN," \n\n");
        util.toScr(OUTMAIN," ---=[Short Range Scan Report]=------------------------------\n");
        util.toScr(OUTMAIN,"  Total Quadrant Units : " + totalLocs+"\n");
        util.toScr(OUTMAIN,"           No of Stars : " + QuadDetails.substring(0,1)+"\n");
        util.toScr(OUTMAIN,"           No of Bases : " + QuadDetails.substring(1,2)+"\n");
        util.toScr(OUTMAIN,"         No of Planets : " + QuadDetails.substring(2,3)+"\n");
        util.toScr(OUTMAIN,"         No of Enemies : " + QuadDetails.substring(3,4)+"\n");
        util.toScr(OUTMAIN," ------------------------------------------------------------\n");
        // Display Each Enemy Info. 
        if (quad[player.getPlayerQX()][player.getPlayerQY()].countEnemeyInQuad() > 0)
        {
            for (int x=0;x<=sectSizeX;x++)
            {
                for (int y=0;y<=sectSizeY;y++)
                {
                    if (quad[player.getPlayerQX()][player.getPlayerQY()].getSpace(x,y) == "X")
                    {
                        util.toScr(OUTMAIN," >> Enemy @ ["+x+"],["+y+"] Sheild @ ["+quad[player.getPlayerQX()][player.getPlayerQY()].getSheild(x,y)+"]\n");  
                    }
                }
            }
        }
        else
        {
            util.toScr(OUTMAIN," No Enemies to Scan in Quadrant.\n");
        }
       util.toScr(OUTMAIN," ------------------------------------------------------------\n");
       util.inStr("Hit [EXECUTE] to Continue.");
       // This also takes 1 time unit.
       player.yearPass();
    }
    /**
     * Options Menu 
     */
    private void goOptions()
    {
        boolean exitOptionsMenu = false;
        while (exitOptionsMenu == false)
        { 
            String optionMenu = " < System Options Function > Scrolling : ["+ util.getScroll()+"] / Audio : ["+ sound.getAudio() +"]\n";
            optionMenu += " [1] - (Toggle) Scrolling\n [2] - (Toggle) Sound\n [3] - Return to Main System Command Functions";
            util.toScr(OUTMENU,optionMenu);
            int sSelect = util.inInt("Options Sub-system Command >> ",3,1);
            if (sSelect == 1) 
            {
                util.toggleScrollStatus();
            }
            if (sSelect == 2)
            {
               sound.toggleAudioStatus();
            }      
            if (sSelect == 3) 
            {
                exitOptionsMenu = true;
            }
        }
    }
    /**
     * Enemy Turn. Included, Flight or Fight and Damage Evaluation.
     */  
    private void goEnemy()
    {
        // Enemy in Quad. Then (75%-Shoot or 25%-Move) (1 or the other not Both.)
        String shipType; 
        for (int x=0; x<=sectSizeX; x++)
        {
            for(int y=0; y<=sectSizeY; y++)
            {
                // If Enemy Exists in Quadrant
                shipType = quad[player.getPlayerQX()][player.getPlayerQY()].getSpace(x,y);
                if ((shipType.equals("X"))||(shipType.equals("V")))
                {
                    int shuckJive = util.rNumber(100);
                    // Flight! 75 - 100 Fear takes over and they move somewhere in quad. 
                    if (shuckJive >= 75)
                    {
                        // If Flight Then Plot New Location for ship.
                        quad[player.getPlayerQX()][player.getPlayerQY()].plotEnemy(x,y);
                    }
                    else
                    {
                        // Fight! 0 - 74 - Then Hit with something.
                        if (!jumpFlag)
                        {
                            int returnFire = 75+util.rNumber(100);
                            if (shipType.equals("V"))
                            {
                                // Bigger Ship Bigger Shot. 
                                returnFire = 75+util.rNumber(300);
                            }
                            sound.playSound("L2.wav");
                            util.shot(x,y,player.getPlayerSX(),player.getPlayerSY());
                            util.toScr(OUTAUX,"Enemy @ ["+x+"]"+",["+y+"] yeilds ["+returnFire+"] pulse!\n");
                            if (player.getStatus() == "DOCKED")
                            {
                                util.sysNotice( "Damage Diverted while Docked.");
                            }
                            else
                            {
                                if (player.getSheildStauts().equals("UP")) 
                                {
                                    // If Sheild is UP then Hit Sheilds and take them down if possible.
                                    player.hitSheild(returnFire);
                                    if (player.getSheild() < 0)
                                    {
                                        player.sheildDown();
                                    }
                                }
                                else
                                {
                                    // Randomize Hull Hit. 
                                    int hullDamage = util.rNumber(25);
                                    player.hitHull(hullDamage);
                                    if (player.getHull() > 0) util.toScr(OUTAUX,"HULL HIT!-Down to ["+player.getHull()+"]%\n");
                                }
                                systemsDamage(10);  // If Hit Ship then Maybe Systems Damage
                            }
                        }
                    }
                }
            }
        }
        // Execute all Enemy Jumps at Once. & Display
        util.toScr(OUTAUX,quad[player.getPlayerQX()][player.getPlayerQY()].jumpEnemy());
        jumpFlag = false;
    }
    
    /**
     * systems Damage - Determine if it occurs, which system and how long. 
     */
    private void systemsDamage(int damageChance)
    {
        // ** Random system Damage
        int chance = util.rNumber(100);                             // Damage?
        int damageType = util.rNumber(commands.size()-5);           // What Type (-4 To Remove all unwanted)
        int damageUnits = util.rNumber(3)+2;                        // How many turns? (0-3) ( But eliminate 0 & 1)
        if (chance <= damageChance)                                 // Damage occurs X% of time!!!
        {
            // Adds the Damage to List
            sound.playSound("DAM.wav");
            Command com = (Command) commands.get(damageType);
            com.setDamage(damageUnits);
            com.setActive(false);
            // Tells captain.
            util.sysNotice("System Damage >"+com.getDesc()+" ["+damageUnits+"] Units");
            //command.get(damageType).setActive(false);
        }
    }
    /**
     * system Repair - Fix systems damage 
     */
    private void systemsRepair()
    {
       // Iterate through all. 
       Iterator<Command> iter = commands.iterator();
       while(iter.hasNext()) 
        {
           Command command = iter.next();
           if (command.damageStatus() > 0) 
           {
                command.fixUnit();                    // Fix One Unit.
                if (command.damageStatus() == 0)      // Is Fixed?
                {
                    util.sysNotice(command.getDesc()+" Repaired!"); 
                    command.setActive(true);
                }
                else
                {
                    util.sysNotice(command.getDesc()+" Repair in Progress.");
                }
            }
        }
    }
     /**
     * system Clear! - Force Fix of All Damage
     */
    private void damageClear()
    {
       // Iterate through all. 
       Iterator<Command> iter = commands.iterator();
       while(iter.hasNext()) 
        {
           Command command = iter.next();
           if (command.damageStatus() > 0) 
           {
                command.clearDamage();   
                command.setActive(true);
            }
        }
    }
    
     /**
     * system Eval. - Remind Current Status. 
     */
    private void systemsEval()
    {
        int damagedUnits = 0; 
        int damageStatusCheck = 0;
        sound.playSound("DSTAT.wav");
        Iterator<Command> iter = commands.iterator();
        while(iter.hasNext()) 
        {
           Command command = iter.next();
           damageStatusCheck = command.damageStatus();
           if (damageStatusCheck > 0)
           {
                damagedUnits += 1;
                util.sysNotice(damagedUnits+") "+command.getDesc()+" Still Damaged for ["+damageStatusCheck+"] day units.");
            }
        }      
        if (damagedUnits == 0)
        {
            util.sysNotice(" Systems Check Reports : No Damage.");
        }
        player.yearPass(); // Force Day Unit for full system Diagnostic. 
    }
    
    /**
    * Repair Damage To Hull. 
    *
    **/
    private void repairDamage()
    {
        if (player.getHull() < 100)
        {
             // Repair up to 15 units of Hull. 
             int hullRepair = util.rNumber(15);
             if (player.getHull() + hullRepair > 100)
             {
                 player.setHull(100);
                 util.sysNotice( "Hull Damage - Fully Repaired!");
             }
             else
             {
                 player.hitRepair(hullRepair);
                 util.sysNotice( "Hull Damage > ["+hullRepair+"] untis repaired!");
             }
         }
    }
    
    /**
     * Fire Shot
     */
    private void goFire()
    {
        // Get Quadrant For Shot. 
        util.sysNotice("Tacticle Request Shot Location : ");
        int x2 = util.inInt("Sector   [X] :",sectSizeX,0);
        int y2 = util.inInt("Sector   [Y] :",sectSizeY,0);
        //Allow shot only if a enemy holds the position.
        String spaceContent = quad[player.getPlayerQX()][player.getPlayerQY()].getSpace(x2,y2);
        if ((spaceContent.equals("X"))||(spaceContent.equals("V")))
        {
              // Determine Energy for Shot. 
              int setEnergyTest = 0;
              if (player.getEnergy() > 200) setEnergyTest = 200;
              if (player.getEnergy() <= 200) setEnergyTest = player.getEnergy();
              int sEnergySelect = util.inInt("Set Pulse Canon [1-"+setEnergyTest+"] available. >> ",setEnergyTest,1); 
              int setEnergy = executeCommand("Fire",sEnergySelect);
              // If Energy in shot then fire. 
              if (setEnergy > 0) 
              {
                    // Fire Pulse
                    sound.playSound("L1.wav");
                    util.shot(player.getPlayerSX(),player.getPlayerSY(),x2,y2);
                    // Randomize Actual Hit or Miss. (10%?)
                    int hitOdds  = util.rNumber(10);
                    if (hitOdds > 1)
                    {
                        // 75% Hits - Balance is random.
                        int hitShip75percent  = (setEnergy * 75)/100;
                        int hitShip25random  = (setEnergy *25)/100;
                        int hitShip = util.rNumber(hitShip25random) + hitShip75percent;
                        quad[player.getPlayerQX()][player.getPlayerQY()].hitSheild(x2,y2,hitShip);
                        util.sysNotice("Enemy @ ["+x2+"],["+y2+"] - Hit with ["+hitShip+"] units"); 
                        // Sheilds Gone. Ship is toast.
                        if ( quad[player.getPlayerQX()][player.getPlayerQY()].getSheild(x2,y2) < 1) 
                        {
                           sound.playSound("EXPL.wav");
                           util.sysNotice("Enemy Destroyed @ ["+x2+"],["+y2+"]!!"); 
                           if (spaceContent.equals("X"))
                           {
                                player.incScore(5);
                                quad[player.getPlayerQX()][player.getPlayerQY()].setSpace(x2,y2,"Z");
                           }
                           if (spaceContent.equals("V"))
                           {
                                player.incScore(7);
                                quad[player.getPlayerQX()][player.getPlayerQY()].setSpace(x2,y2,"C");
                           }
                           player.killBaddie(1);
                        }
                        else
                        {
                            // Enemy Still Alive - How much defense left?
                            util.sysNotice("Enemy hit @ ["+x2+"],["+y2+"] - Sheilds Down to : "+quad[player.getPlayerQX()][player.getPlayerQY()].getSheild(x2,y2)); 
                        }
                    }
                    else
                    {
                        util.sysNotice("Shot Missed!! ");  
                    }
                    player.useEnergy(setEnergy);
                    // Only take a time unit. 
                    player.yearPass();
              }
        }
        else
        {
            // No Ship there. 
            util.sysNotice("Unable to aquire target.");   
        }
    }
    
    /**
     * Execute command routine
     * 
     * @param commandReq String of request to confirm
     * @param eProposal Energy require to execute request.
     * 
     * @return eProposal - Check if user wants to use Amount Required. 
     */
    private int executeCommand(String commandReq,int eProposal)
    {
        // Loop until valid entry.
        boolean xLoop = false;
        String xCheck;
        while (xLoop == false)
        {
            xCheck = util.inStr("Energy Required : ["+ eProposal +"] Execute "+commandReq+" order? (y/n) > ");
                if (xCheck.equals("y")) 
                {
                    xLoop = true;
                }
                if (xCheck.equals("n")) 
                {
                    xLoop = true;
                    eProposal = 0;
                }
         }  
         return eProposal;
    }
    
    /**
    * Probe Sat
    */
    private void goSAT()
    {
        // Check to see if there are any in stock
        if (player.getProbe() > 0)
        {
            util.sysNotice("Probe Command Sequence Started!!!");
            int x1 = util.inInt("Quadrant [X]  :",quadSizeX,0);
            int y1 = util.inInt("Quadrant [Y]  :",quadSizeY,0);
            // 400 For 1st Probe and then 200 more for each next. 
            int eUsedTest = 400 + (200 * player.getProbeFiredCount());
            int eUsed = 0;
            eUsed = executeCommand("Probe" , eUsedTest);
            if (eUsed >0) 
            {
                // Play scan Sound. 
                sound.playSound("SCAN.wav");
                // Scan 3x3 Probe Area. 
                activateLRS(x1,y1);
                // use One Probe from stock
                player.useProbe(1);
                // Subtract energy requirement.
                player.useEnergy(eUsed);
                // Only take a day away if you launched the Probe. 
                player.yearPass();
                util.sysNotice("Updated Data Now on LRS Scan.");
            }
        }
        else
        {
            util.sysNotice("!!No Probes Left!!");
        }
    }
    
    /**
    * Nuke Quad.
    */
    private void goNuke()
    {
        // Check to see if there are any in stock
        if (player.getNuke() > 0)
        {
            util.sysNotice("Nuke Command Sequence Started!!!");
            // 400 For 1st nuke and then 200 more for each next. 
            int eUsedTest = 400 + (200 * player.getNukeFiredCount());
            int eUsed = 0;
            eUsed = executeCommand("Nuke" , eUsedTest);
            if (eUsed >0) 
            {
                //Kill Enemy based on contents of quad.
                player.killBaddie(quad[player.getPlayerQX()][player.getPlayerQY()].wipeEnemeyInQuad());
                // use One Nuke from stock
                player.useNuke(1);
                // Subtract energy requirement.
                player.useEnergy(eUsed);
                // Only take a day away if you launched the nuke. 
                player.yearPass();
                util.sysNotice("Nuke Wipes Sector!!!");
                sound.playSound("EXPL.wav");
            }
        }
        else
        {
            util.sysNotice("!!No Nukes Left!!");
        }
    }
    /**
    * Move Ship through Galaxy.
    */
    private void goMove(char jumpType)
    {   
        jumpFlag = false;
        // Move Class Instance.
        Move move;
        move = new Move(); 
        // Get Jump Location.
        int x1 = 0;
        int y1 = 0;
        if (jumpType=='j')
        {
            x1 = util.inInt("Quadrant [X]  :",quadSizeX,0);
            y1 = util.inInt("Quadrant [Y]  :",quadSizeY,0);
        }
        else
        {
            x1 = player.getPlayerQX();
            y1 = player.getPlayerQY();
        }
        int x2 = util.inInt("Sector   [X]  :",sectSizeX,0);
        int y2 = util.inInt("Sector   [Y]  :",sectSizeY,0);
        // What is @ Jump Location 
        String somethingAtLocation = quad[x1][y1].getSpace(x2,y2);
        // Test location for Nothing or Worm. 
        if ((somethingAtLocation.equals(".")) || (somethingAtLocation.equals("W")) || ((somethingAtLocation.equals("S"))&&(sunUse == false)))
        {
            // Set all jump Vectors
            if (somethingAtLocation.equals("."))
            {
                move.jumpVarSet(player.getPlayerQX(),player.getPlayerQY(),player.getPlayerSX(),player.getPlayerSY(),x1,y1,x2,y2);
                // Spend Energy on Jump.
                int energyUsed = executeCommand("move",move.jump(player.getSheildStauts()));
                if (energyUsed > 0) 
                {
                    // Void Old Spot.
                    quad[player.getPlayerQX()][player.getPlayerQY()].setSpace(player.getPlayerSX(),player.getPlayerSY(),".");
                    // Occupy New. 
                    quad[x1][y1].setSpace(x2,y2,"Y");
                    player.setPlayerLoc(x1,y1,x2,y2);
                    // Use Energy.
                    player.useEnergy(energyUsed);
                    jumpFlag = true;
                }
                // Time clicks on. 
                player.yearPass();
            }
            else if(somethingAtLocation.equals("W"))
            {
               quad[player.getPlayerQX()][player.getPlayerQY()].setSpace(player.getPlayerSX(),player.getPlayerSY(),"."); 
               populateStuffUnEven(1,"Y",0);
               util.sysNotice("Hit a Worm Hole - Free Random Transport!" );
               jumpFlag = true;
            }
            else if((somethingAtLocation.equals("S"))&&(sunUse == false))
            {
               quad[player.getPlayerQX()][player.getPlayerQY()].setSpace(player.getPlayerSX(),player.getPlayerSY(),"."); 
               populateStuffUnEven(1,"Y",0);
               util.sysNotice("Slingshot around Sun - You Gained 3 day units." );
               player.setCountDown((player.getCountDown()+3));
               sunUse = true;
               jumpFlag = true;
            }
         }
         else 
         {
               // Something in the way.
               sound.playSound("AD.wav");
               util.sysNotice("!Cant Compute Jump to Occupied Space!" );
               util.sysNotice("There is something @ Quad:["+x1+"]["+y1+"] Sector:["+x2+"]["+y2+"]." );
         } 
    }
    
    /**
    * Shield Controls. 
    */
    private void goSheild()
    {
        boolean exitSheildMenu = false;
        while (exitSheildMenu == false)
        { 
            if (player.getSheildStauts() == "DOWN") util.sysNotice("WARNING SHIELDS DOWN!!");
            util.toScr(OUTMENU," < Shield Command Function >\n [1] - (Toggle) Raise or Lower Shields.\n [2] - Set Sheild Energy.\n [3] - Return to Main System Command Functions");
            int sSelect = util.inInt("Shield Sub-system Command >> ",3,1);
            if (sSelect == 1) 
            {
                boolean done = false;
                if (player.getSheildStauts() == "DOWN" ) 
                {
                    player.sheildUp();
                    if(player.getSheild() == 0)
                    {
                        util.sysNotice("Sheild is [UP]!");
                        util.sysNotice("But NO shield energy is assigned.");
                    }
                    done = true;
                }  
                if ((player.getSheildStauts() == "UP") && (done != true)) 
                {
                    player.sheildDown();
                    int eSheild = player.getSheild();
                    player.setSheild(0);
                    util.sysNotice("Shields are now [DOWN]!");
                    util.sysNotice("["+ eSheild + "] units back to Crystal Chamber.");
                    player.returnEnergy(eSheild);
                }
            }
            if (sSelect == 2)
            {
              // Reset Shield and Return Energy for Energy available Balance.
              int eSheild = player.getSheild();
              player.setSheild(0);
              player.returnEnergy(eSheild);
              // User Now resets energy. 
              int setEnergy = 0;
              if (player.getEnergy() > 2000) setEnergy = 2000;
              if (player.getEnergy() <= 2000) setEnergy = player.getEnergy();
              int sEnergy = util.inInt("Set Energy to Shield [1-"+setEnergy+"] available. >> ",setEnergy,1); 
              player.setSheild(sEnergy);
              player.useEnergy(sEnergy);
              player.sheildUp();
              util.sysNotice("Shield is now set to : ["+ sEnergy +"] units.");
            }      
            if (sSelect == 3) exitSheildMenu = true;
        }
    }
    
    
    /**
     * Welcome Notice.
     */
    private void initWelcome()
    {
        util.setScroll(true);
        util.setSpeed(30);
        util.toScr(OUTMAIN,"\n\n> MCP Request access to Galactic Conquest....");
        util.toScr(OUTMAIN,"\n Level 7 password : flynn.\n");
        util.toScr(OUTMAIN,"< ............. Access Granted .........\n");
        util.toScr(OUTMAIN,"Simulation now on Game Grid.\n");
        sound.playSound("GG.wav");
        util.setSpeed(5);
        util.setScroll(true);
        util.readFileDisp("Welcome.txt");
        util.toScr(OUTMAIN,"Galaxy Scan Complete... \n");
        util.toScr(OUTMAIN,"Transfering to Command Console.\n");
        util.toScr(OUTAUX,"WARNING - You Are At WAR!!\n");
        util.toScr(OUTAUX,"Rasing Sheild is recommended.\n");
    }
    
    /**
     *  Init Long Range Scan.
     */
    private void initLRS()
    {
        for(int x = 0; x <= quadSizeX;x++)
        {
            for (int y = 0; y <=quadSizeY;y++)
            {
                LRS[x][y] = false;                      // Set Fog of War for all Quads. 
            }
        }
    }
   
    /*
     * Initiate Commands For Main Menu.
     */
    private void initCommands()
    {
        // Add Valid Commands. 
        commands.add(new Command("j","HyperNav "));
        commands.add(new Command("t","Thruster ")); 
        commands.add(new Command("f","Fire     "));
        commands.add(new Command("x","Nuke     "));
        commands.add(new Command("s","Shield   "));
        commands.add(new Command("r","SRS      "));
        commands.add(new Command("l","LRS      "));
        commands.add(new Command("a","LR Probe "));
        commands.add(new Command("d","Damage   "));
        commands.add(new Command("p","Planet!  "));
        commands.add(new Command("o","Options  "));
        commands.add(new Command("h","Help     "));
        commands.add(new Command("q","Quit     "));
    }
    
    /**
     * menuDisplay - Compile Menu From Selections. Send to GUI
     */
    private void menuDisplay()
    {
         validCommands = "";
         String CmdTemp = "";
         int i = 0;
         for(Command com : commands )
         {                
             if (com.getActive())
             { 
                if (!com.getCmd().equals("p"))
                { 
                    CmdTemp += "  ["+com.getCmd()+"]-"+com.getDesc();
                    validCommands += com.getCmd();
                }
                else
                {
                    if (checkPlanetActivate())
                    {
                        CmdTemp += "  ["+com.getCmd()+"]-"+com.getDesc();
                        validCommands += com.getCmd();   
                    }
                }
            }
            else
            {
                CmdTemp += "  ["+com.getCmd()+"]-OFFLINE!";
            }
            if (((i%6)==0) && (i > 0)) 
            {
                CmdTemp += "\n";
            }
            i +=1;
         }
         util.toScr(OUTMENU, CmdTemp );
    }
    
    /**
     * checkPlanetActivate - Check to see if planet in Quadrant. 
     * 
     * @return planetAvailable - Return True is planet available. 
     */
    private boolean checkPlanetActivate()
    {
        boolean planetAvailable = true;
        String planetTest = quad[player.getPlayerQX()][player.getPlayerQY()].getQuadDetails().substring(2,3);
        if (planetTest.equals("0"))
        {
            planetAvailable = false;
        }
        return planetAvailable;
    }
    
    /**
    * Difficulty level set. 
    */
    private void difficulty()
    {
        // Difficulty Level Section / Changes # of Enemies & # of bases.
        difficulty = util.inInt("Difficulty : (1)Ensign (2)Commander (3)Admiral :",3,1);
        int badQty = 0;
        // Reset Default Values for Difficult levels.
        switch(difficulty)
        {
            case 1:                         // Easy
                badQty = 20;
                bases = 3;
                break;
            case 2:                         // Medium
                badQty = 25;
                bases = 4;
                break;
            case 3:                         // Hard
                badQty = 30;
                bases = 4;
                break;
        }
        player.setBaddie(badQty);
    }
   
    /**
    * Populate Stuff UnEvenly Throughout Galaxy. 
    * 
    * @param qty How Many to distribute Randomly
    * @param unit What the Unit Looks Like.  
    */
    private void populateStuffUnEven(int qty, String unit, int sheildValue)
    {
        String planetCheck = "";
        int quadX=0;
        int quadY=0;
        int locX=0;
        int locY=0;
        // Seed for # Required
        for (int i=0; i< qty; i++)
        {
            // If Planet then Choose Planet from 6 Types. 
            if (unit.equals("P"))
            {
                planetCheck = "P";
                int planetType = (util.rNumber(6)-1);
                unit = ""+planetType;
            }
            // Placement Check 
            boolean placeOk = false;
            while (placeOk == false)
            {
                // Randomize X & Y Loc of Ememies. 
                quadX = (util.rNumber(quadSizeX)-1);
                quadY = (util.rNumber(quadSizeY)-1);
                locX = (util.rNumber(sectSizeX)-1);
                locY = (util.rNumber(sectSizeY)-1);
                //If Spot Not Occupied Then Place it. 
                if (quad[quadX][quadY].getSpace(locX,locY).equals(".")) 
                {
                    if (sheildValue > 0)
                    {
                        quad[quadX][quadY].setSheild(locX,locY,sheildValue);
                    }
                    quad[quadX][quadY].setSpace(locX,locY,unit);
                    if (unit.equals("Y"))
                    {
                        player.setPlayerLoc(quadX, quadY, locX,locY);
                    }
                    placeOk = true;
                } 
            }
            if (planetCheck.equals("P"))
            {
                unit = "P";
            }
         
        }   
    }
    /**
    * Populate Stuff Evenly Throughout Galaxy. 
    * 
    * @param qty How Many to distribute evenly
    * @param unit What the Unit Looks Like.  
    */
    private void populateStuffEven(int qty, String unit)
    {
        // Seed.
        // Number of Quads
        int spreadinSize = (quadSizeX+1)*(quadSizeY+1);
        // Number of Enemy / Quad
        int spreadinQuad = qty / spreadinSize;
        // For each quad. 
        for (int quadX=0; quadX<=quadSizeX; quadX++)
        {
            for (int quadY=0; quadY<=quadSizeY; quadY++)
            {
                for (int i=1; i<=spreadinQuad; i++)
                {
                    // Create Placement check
                    boolean placeOk = false;
                    while (placeOk == false)
                    {
                        // Randomize X & Y Loc of Ememies. 
                        int locX = (util.rNumber(sectSizeX)-1);
                        int locY = (util.rNumber(sectSizeY)-1);
                        // If Unoccupied then place it. 
                        if (quad[quadX][quadY].getSpace(locX,locY).equals(".")) 
                        {
                            quad[quadX][quadY].setSpace(locX,locY,unit);
                            placeOk = true;
                        }
                    }
                }
            }
        }   
    }
    
    /**
    * Draw Screen Displays Game "Console"  
    */
    private void drawScreen()
    {
        // LRS - Unveil the Fog of War for Current Quadrant. 
        LRS[player.getPlayerQX()][player.getPlayerQY()] = true;
        // Determine Status. 
        statusCheck();
        // Set Top Title To New General Status.  
        util.toScr(OUTTITLE,"   >> "+player.getPlayerName()+ " commanding >> " + player.getShipName() + " [TURN # "+player.getTurn()+"]  SCORE: ["+player.playerScore()+"]\n");
        // Populate Upper left window with with Ship Stats 
        String statDisp =" Ship @ > Quadrant : "+player.quadLoc()+"\n";
        statDisp +=      "            Sector : "+player.sectLoc()+"\n";
        statDisp +=      " Status            : ["+player.getStatus()+"]\n";
        statDisp +=      " Sheild            : ["+player.getSheildStauts()+"]\n";
        statDisp +=      " Hull              : ["+player.getHull()+"]%\n";
        statDisp +=      " Crystal(s)        : ["+player.getEnergy()+"] units\n"; 
        statDisp +=      " Sheild            : ["+player.getSheild()+"] units\n"; 
        statDisp +=      " Nukes             : ["+player.getNuke()+"] units / LR Probes : ["+player.getProbe()+"] units \n";
        statDisp +=      " -----------------------------------------------------\n";
        statDisp +=      " Your Mission : Kill all Ememies : ["+ player.getBaddie()+"]\n";
        statDisp +=      "                    in day units : ["+player.getCountDown()+"]";
        util.toScr(OUTSTAT, "Clr");
        util.toScr(OUTSTAT, statDisp);
        // Populate Notice (or Aux Screen) with current turn reminder. 
        util.sysNotice("---===[Turn :"+player.getTurn()+"]===---");
        // Populate Main Display with Quadrant Scan.
        util.quadDraw(quadGraphicDisplay(),sectSizeX,sectSizeY);  // <---==== NEW GRAPHIC FORMAT.
        // util.toScr(OUTMAIN, quadScreenDisplay());  <----=== Old Text Only Version 
        // Update Menu
        menuDisplay();
    }
       
    /**
     * quadGraphicDisplay Combines the Quadrant into one Compressed Data Stream
     * in order to pass the info to the Graphic Parser (then display the galaxy
     * graphically.
     * 
     * @return Compressed Current Quadrant String
     */
    private String quadGraphicDisplay()
    {
        // Initiate Empty String
        String quadLine = "";
        // Iterate Quadrant lines
        for (int y = 0; y <= sectSizeY;y++)
        {
            // Append lines together
            quadLine += quad[player.getPlayerQX()][player.getPlayerQY()].showQuadLine(y,false);
        }
        return quadLine;
    }
    
    /**
     * Long Range Sensor Sweep
     * Scan all sectors adjacent to ship
     */
    private void activateLRS(int scanQuadX, int scanQuadY)
    {
        //player.getPlayerQX()
        //player.getPlayerQY()
        // Set Upper Left Quad Start Point for Scan
        int x1 = scanQuadX-1;
        int y1 = scanQuadY-1;
        // Set Lower Right Quad End Point for Scan
        int x2 = scanQuadX+1; 
        int y2 = scanQuadY+1;
        // Iterate From Start to End. 
        for (int x=x1;x<=x2;x++)
        {
            for (int y=y1;y<=y2;y++)
            {
               // Array out of range bypass when scan is outside allowed block. 
               try
               {
                   // Fog of war opens. 
                   LRS[x][y] = true;
                } 
                catch(Exception ie)
                {
                    // Ignore any Array errors if not a valid Array value. 
                }
            }
        } 
    }
    
    /**
     * Change ship Status based on Galactic Environment
     * 
     * Green = All is Good
     * Docked = Space Station.
     * Yellow = Low Energy
     * Red = Enemy Around. 
     */
    private void statusCheck()
    {
        //Default to "GREEN" - Means All is good."
        String statusChange = "GREEN";
        // Docked Check & Notice.
        if (quad[player.getPlayerQX()][player.getPlayerQY()].isDocked(player.getPlayerSX(),player.getPlayerSY())) 
        {
            player.incScore(1);
            statusChange = "DOCKED";
            player.sheildDown();
            player.setHull(100);
            util.sysNotice("!!!DOCKED!!!");
            util.sysNotice("=========================");
            util.sysNotice("Reminder : Your sheids must be down to remain docked.");
            util.sysNotice("You will not be damaged by hostile fire.");
            util.sysNotice("Your Energy will be replenished if required.");
            util.sysNotice("Any Damage to your hull will be repaired.");
            // Fill Up Ship Energy.        
            if (player.getEnergy() < 8000)
            {
                if ((player.getEnergy() + 150) > 8000)
                {
                    util.sysNotice("System Energy at FULL.");
                    player.setEnergy(8000);
                }
                else
                {
                    player.storeEnergy(150);
                    util.sysNotice("System Energy while docked\nreplenished by [250].");
                }
             }
         }
        // AWAY Party. 
        // If Your energy is low then "YELLOW"
        if (player.getEnergy() < 1000) statusChange = "YELLOW";
        // When a Enemy is in the Quad "RED" condition.
        if(quad[player.getPlayerQX()][player.getPlayerQY()].countEnemeyInQuad() >0)
        {
            statusChange = "RED"; 
            //sound.playSound("RED.wav"); // This is annoying. 
        }
        // Set Status Change. 
        player.setStatus(statusChange);
    }

}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer Nottawasaga Valley Conservation Authority
Canada Canada
I have background in programming(many languages), web design, hardware and software. Currently I hold a lead database programming position for the Nottawasaga Valley Conservation Authority... Programming in vb.net and java comes 2nd nature to me and of course I do this for fun. I also used to design in cobol and pascal and run a BBS(anyone remember what this was?). Anyways, drop me a line maybe I can help you.

Comments and Discussions