Функциональность оригинальной версии. Текст программы. Описание программы. Java-documentation

Страницы работы

56 страниц (Word-файл)

Фрагмент текста работы

Оглавление.

1. Задание…………………………………………………………………………..………………………………………………………………….2

2. Текст программы….…………………………………………………………………..……………………………………………………….3

3. Описание программы……………………….……………………………………………………………………………………………..32

3.1. Диаграмма классов……..……………………………………………………………………………………………………………….32

3.2. Java-documentation………………………………..…………………………………………………………………………………….33

4. Испытание программы……………….…………………………………………………………………………………………………..54

6. Выводы…………………………………………………………………………………………………………………………………………….56

Задание.

По предмету «Теория и технологии программирования» необходимо было выбрать курсовой проект. Тема свободная.  После выполнения проекта «Визуальный Морской бой», был выбран проект – аркадную игру «Башенки».

Примечание. Суть игры заключается в том, чтобы строя башенки, не дать пролететь кораблям до финальной точки. При этом у игрока для строительства башенок есть некоторое количество ресурсов, которое пополняется за счет уничтожение вражеских юнитов. Каждая башенка может быть усилена за счет тех же ресурсов. 

На сегодняшний день существует  огромное количество разных вариаций на эту тему.  За основу, я взял проект «Tap Defense» написанный для платформы iPhoneOS.  

Функциональность оригинальной версии:

- установка башенок;

- усиливание каждой из башенок;

- просмотр статов каждого из игровых элементов;

Так же, данный проект предполагает  следущие изменения:

-  3 ресурса: деньги, камень, железо;

-  новые типы башен;

-  режим стратегии;

-  возможность получение ресурсов из убитых кораблей.

В начальную версию программы было решено включить следующие игровые объекты:

-  5 кораблей:  Short Wagon, Black Pirates, Hard Flier, Speed Walker, The Boss;

-  3 типа башен:  Laser Tower, Stone Protos, Big Gravity.

Для игры были разработаны  логотип и название.

Текст программы.

Листинг 1. Файл Main.java

/*

* Main.java

*/

package myrequest;

import javax.swing.SwingUtilities;

/**

* First class

* @author Belyaev Alex

*/

public class Main {

/**

* Create general thread

*/

public static void main(String[] args) {

SwingUtilities.invokeLater(new Runnable(){

public void run(){

new MyWindow();

}

});

}

}

Листинг 2. Файл ActionList.java

/*

* ActionList.java

*/

package myrequest;

/**

* Container for global variable

* @author ALex

*/

public class ActionList { // class which save all glabal variable

static final int MaxLevel=10; // How many levels in game

static final int Loos=20; // How many ships player can loose

static final int CellSize=40; // Cell size

static public boolean FatalErr=false; // Indicator of fatal error

static public int DrawOnCells=0; //Indicator of starting build mode

static public int loos=Loos; // How many loosed ships

static private char pause='p'; // Save pause indicator

static public int LevelNum=0; // What level now

static public int StartNewLvl=0; // If this variable=1 game go into next level

static public int LoosGame=0; // If this variable=1, game end

static public int WinGame=0; // If this variable=1, game win

static public int NewGame=0; // If this variable=1, start new game

static public char build = 'n'; // This variable say us what type of tower build

///////////////////////////////////////////////////////////////////////////////

/**

* ControlGame

* @param act  'p'-pause, 's'-start

*/

public void ControlGame(char act){

pause=act;

}

///////////////////////////////////////////////////////////////////////////////

/**

* Function that return valume of pause variable

* @param null

* @return valume of pause variable

*/

public char GetPauseInfo(){

return pause;

}

///////////////////////////////////////////////////////////////////////////////

/**

* Function that do necessary operation if game end

* @param f фигура

*/

public void GameInd(){

if (loos==0){

LoosGame=1;

pause='p';

loos=Loos;

LevelNum=0;

NewGame=1;

}

else if (LevelNum==(MaxLevel+1)){

pause='p';

WinGame=1;

loos=Loos;

LevelNum=0;

NewGame=1;

}

}

///////////////////////////////////////////////////////////////////////////////  

}

Листинг 3. Файл MyWindow.java

/*

* MyWindow.java

*/

package myrequest;

import javax.swing.*;

import java.awt.*;

import java.awt.Toolkit;

/**

* General frame of application

* @author Belyaev Alex

*/

public class MyWindow extends JFrame{

JToolBar toolbar;

MyDrawPanel myDP = new MyDrawPanel();

MyControlPanel myCP = new MyControlPanel();

MyWindow(){

Image icn =  Toolkit.getDefaultToolkit().getImage("MyRequest.gif");

setIconImage(icn);

setSize(800, 600);

setTitle("MyRequest Game | Version 1.0 (beta)");

setResizable(false);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

myDP.setMinimumSize(new Dimension(800, 400));

myCP.setMinimumSize(new Dimension(800, 200));

add(myDP);

add(myCP);

JSplitPane jsp = new JSplitPane(JSplitPane.VERTICAL_SPLIT, myDP, myCP);

add(jsp);

setVisible(true);

}

}

Листинг 4. Файл MyDrawPanel.java

/*

* MyDrawPanel.java

*/

package myrequest;

import java.awt.event.MouseEvent;

import javax.swing.*;

import java.awt.*;

import java.awt.Graphics2D.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.awt.event.MouseListener;

import java.awt.event.MouseMotionListener;

import java.awt.image.ImageObserver;

/**

* This class draw all game object, map, biuld mode

* @author Belyaev Alex

*/

public class MyDrawPanel extends JPanel implements PrepareWorld{

private int lastx=0, lasty=0, ext=0; // last value of mouse actions

JLabel backgd = new JLabel();

ActionList al = new ActionList();

ImageObserver imageobs;

public Timer timer;

private MouseListener mouseListener;

private MouseMotionListener mouseMotionListener;

///////////////////////////////////////////////////////////////////////////

/**

* Function that return valume of pause variable

* @param wht write what type of actions was

* @param x x coord

* @param y y coord

*/

private void PrintCoord(String wht,int x, int y){

System.out.println(wht+" coords: "+x+"_"+y);

}

///////////////////////////////////////////////////////////////////////////

/**

* Initialization of mouse listners

*

*/

private void initMouseListeners() {

mouseListener = new MouseListener() {

public void mouseClicked(MouseEvent e) {

if (ActionList.build!='n'){onStand(e.getX(), e.getY());} //tower build

else{SelectUnit(e.getX(), e.getY());} // select object

}

public void mousePressed(MouseEvent e) {

if (ActionList.build!='n'){onStand(e.getX(), e.getY());} //tower build

else{SelectUnit(e.getX(), e.getY());} // select object

}

public void mouseReleased(MouseEvent e){}

public void mouseEntered(MouseEvent e) {}

public void mouseExited(MouseEvent e)  {ext=1;} // mouse exit from panel

};

addMouseListener(mouseListener);

}

///////////////////////////////////////////////////////////////////////////

private void initMouseMotionListeners() {

mouseMotionListener = new MouseMotionListener() {

public void mouseDragged(MouseEvent e) {

if (ActionList.build!='n'){}else{SelectUnit(e.getX(), e.getY());}

}

public void mouseMoved(MouseEvent e)   {

ext=0; lastx=e.getX(); lasty=e.getY(); // set mouse how entered, save last coords

}

};

addMouseMotionListener(mouseMotionListener);

}

///////////////////////////////////////////////////////////////////////////

/**

* Invoke function from class world to select unit

* @param x x coord

* @param y y coord

*/

private void SelectUnit(int x, int y){

mw.Select(x, y);

}

///////////////////////////////////////////////////////////////////////////

/**

* Stand tower on coords if it perhaps

* @param x x coord

* @param y y coord

*/

private void onStand(int x, int y) {

if (MyMap.Map[x/ActionList.CellSize][y/ActionList.CellSize]==1){

StandTower(x, y);

}

}

///////////////////////////////////////////////////////////////////////////

/**

* Print message about error

*/

public void Err(){

String[] vars = { "EXIT" };

int result = JOptionPane.showOptionDialog(this, "GAME FOUND FATAL ERR!",

"", JOptionPane.OK_OPTION, JOptionPane.ERROR_MESSAGE,

null, vars, "EXIT");

if (result==JOptionPane.OK_OPTION)

System.exit(0);

}

///////////////////////////////////////////////////////////////////////////

/**

* Build choosen tower if it possible and set cell as busy

* @param x x coord

* @param y y coord

*/

private boolean StandTower(int x, int y){

x=x/ActionList.CellSize; y=y/ActionList.CellSize;

int wht=0;

if (ActionList.build=='l'){wht=MyProtection.Laser;}

else if (ActionList.build=='s'){wht=MyProtection.Stone;}

else if (ActionList.build=='g'){wht=MyProtection.Gravity;}

if (mw.AddTower(x, y, wht)==false){

String[] vars = { "OK" };

int result = JOptionPane.showOptionDialog(this, "You don't have enough resourses!",

"", JOptionPane.OK_OPTION, JOptionPane.ERROR_MESSAGE,

null, vars, "OK");

if (result==JOptionPane.OK_OPTION)

return false;

}

if (MyMap.Map[x][y]==1){MyMap.Map[x][y]=0;}

return true;

}

///////////////////////////////////////////////////////////////////////////

/**

* constructor

*/

MyDrawPanel(){

ImageIcon map = new ImageIcon("pictures/map.png");

setBackground(Color.BLACK);

backgd.setIcon(map);

backgd.setSize(800, 400);

add(backgd);

initMouseListeners();

initMouseMotionListeners();

ActionListener timerListener = new ActionListener() {

int threadstart=0;

public void actionPerformed(ActionEvent e) { // timer that make tower and enemy step

if (al.GetPauseInfo()=='s'){

mw.StepEnemy(MyDrawPanel.this.getGraphics());

if (threadstart==0){ // if not started

mw.StepProtection(MyDrawPanel.this.getGraphics());

threadstart=1;

}

}

else {threadstart=0;}

repaint();

al.GameInd();//end listner

if (ActionList.FatalErr==true)Err();

}

};

timer = new Timer(79, timerListener);

timer.start();

}

///////////////////////////////////////////////////////////////////////////

/**

* Function that paint/repaint all object

* @param g - Graphics object

*

*/

@Override

public void paint(Graphics g) {

super.paint(g);

mw.paint(g);

if (ActionList.build!='n' && ext==0){mw.DrawTowerBuild(lastx, lasty, g);}

}

///////////////////////////////////////////////////////////////////////////

}

Листинг 5. Файл MyControlPanel.java

/*

* MyControlPanel.java

*/

package myrequest;

import java.awt.Graphics;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import javax.swing.JOptionPane;

import javax.swing.JPanel;

import javax.swing.Timer;

/**

* Visualisation of control panel

* @author Belyaev Alex

*/

public class MyControlPanel extends JPanel implements PrepareWorld{

ActionList al = new ActionList();

///////////////////////////////////////////////////////////////////////////////

public MyControlPanel() {

initComponents();

LoadGameBut.setVisible(false);

SaveGameBut.setVisible(false);

TowerToolBar.setVisible(false);

ActionListener timerListener = new ActionListener() { // Timer for refresh data in labels

// and work with buttons

public void actionPerformed(ActionEvent e) {

repaint();

}

};

Timer time = new Timer(100, timerListener);

time.start();

}

@SuppressWarnings("unchecked")

// <editor-fold defaultstate="collapsed" desc="Generated Code">                                 ... ... ... ... //NetBeans generated code

</editor-fold>  

private void ControlButActionPerformed(java.awt.event.ActionEvent evt) {                                          

if (al.GetPauseInfo()=='s'){ al.ControlGame('p');}

else if (al.GetPauseInfo()=='p'){

if (ActionList.NewGame==1){ ActionList.LoosGame=0;  ActionList.WinGame=0; }

al.ControlGame('s');

ActionList.NewGame=0;

}

}                                         

private void BuildButActionPerformed(java.awt.event.ActionEvent evt) {                                        

if (ActionList.DrawOnCells==0){

ActionList.DrawOnCells=1;

BuildBut.setText("Disable build");

al.ControlGame('p');

TowerToolBar.setVisible(true);

ControlBut.setEnabled(false);

}

else if (ActionList.DrawOnCells==1){

ActionList.DrawOnCells=0;

BuildBut.setText("Enable build");

//al.ControlGame('s');

TowerToolBar.setVisible(false);

ControlBut.setEnabled(true);

}

ActionList.NewGame=0;

ActionList.build='n';

}                                       

private void GravityButActionPerformed(java.awt.event.ActionEvent evt) {                                           

ActionList.build='g';

}                                         

private void StoneButActionPerformed(java.awt.event.ActionEvent evt) {                                        

ActionList.build='s';

}                                       

private void LaserButActionPerformed(java.awt.event.ActionEvent evt) {                                        

ActionList.build='l';

}                                       

private void NewGameButActionPerformed(java.awt.event.ActionEvent evt) {                                          

//ActionList.LoosGame=1;

ActionList.NewGame=1;

ActionList.LevelNum=0;

ActionList.loos=ActionList.Loos;

al.ControlGame('p');

}                                         

private void SaveGameButActionPerformed(java.awt.event.ActionEvent evt) {                                           

// TODO add your handling code here:

}                                           

private void UpgradeTowerButActionPerformed(java.awt.event.ActionEvent evt) {                                               

MyWorld.activeTower.UpGrade();

MyResourses.money-=MyWorld.activeTower.money;

MyResourses.stone-=MyWorld.activeTower.stone;

MyResourses.iron-=MyWorld.activeTower.iron;

}                                              

private void SellTowerButActionPerformed(java.awt.event.ActionEvent evt) {                                             

String[] vars = { "Yes", "No" };

int result = JOptionPane.showOptionDialog(this, "Are you sure?",

"", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE,

null, vars, "Yes");

if (result==JOptionPane.YES_OPTION){  mw.SellTower(); }

}                                           

private void LoadGameButActionPerformed(java.awt.event.ActionEvent evt) {                                            

// TODO add your handling code here:

}                                          

///////////////////////////////////////////////////////////////////////////

/**

* Function that paint/repaint all object

* @param g - Graphics object

*

*/

@Override

public void paint(Graphics g) {

super.paint(g);

RefreshInfo();

}

///////////////////////////////////////////////////////////////////////////

/**

* Setup all object in control panel

* @param null

*

*/

public void RefreshInfo(){

LevelLab.setText(ActionList.LevelNum+1+"");

LoosLab.setText(ActionList.loos+"");

MoneyLab.setText(MyResourses.money+"");

StoneLab.setText(MyResourses.stone+"");

IronLab.setText(MyResourses.iron+"");

ChangeIndicators();

ChangeBuildPanel();

ChangeInfoPanel();

ChangeActionPanel();

if (ActionList.build=='l'){

CostPanel.setVisible(true);

MyProtection tower = new LaserTower();

ChangeCostPanel(tower);

}

else if (ActionList.build=='s'){

CostPanel.setVisible(true);

MyProtection tower = new StoneProtos();

ChangeCostPanel(tower);

}

else if (ActionList.build=='g'){

CostPanel.setVisible(true);

MyProtection tower = new BigGravity();

ChangeCostPanel(tower);

}

else {CostPanel.setVisible(false);}

}

///////////////////////////////////////////////////////////////////////////

private void ChangeCostPanel(MyProtection tower){

TowerMoneyCostLab.setText(tower.money+"");

TowerStoneCostLab.setText(tower.stone+"");

TowerIronCostLab.setText(tower.iron+"");

TowerSetForceLab.setText(tower.force+"");

TowerSetFreezeLab.setText(tower.freeze+"");

TowerSetCritLab.setText(tower.crit+"");

TowerSetSpeedLab.setText(tower.speed+"");

}

///////////////////////////////////////////////////////////////////////////

private void ChangeBuildPanel(){

if (ActionList.build=='n'){

StoneBut.setSelected(false);

LaserBut.setSelected(false);

GravityBut.setSelected(false);

}

else if (ActionList.build=='s'){

StoneBut.setSelected(true);

LaserBut.setSelected(false);

GravityBut.setSelected(false);

}

else if (ActionList.build=='l'){

StoneBut.setSelected(false);

LaserBut.setSelected(true);

GravityBut.setSelected(false);

}

else if (ActionList.build=='g'){

StoneBut.setSelected(false);

LaserBut.setSelected(false);

GravityBut.setSelected(true);

}

}

///////////////////////////////////////////////////////////////////////////

private void ChangeInfoPanel(){

if (MyWorld.activeShip!=null && MyWorld.activeShip.visible==1){

ShipInfoPanel.setVisible(true);

ShipPictLab.setIcon(MyWorld.activeShip.shipIcon);

ShipNameLab.setText(MyWorld.activeShip.name);

ShipSpeedLab.setText(MyWorld.activeShip.speed+"");

ShipHealthLab.setText(MyWorld.activeShip.health+"");

ShipArmorLab.setText(MyWorld.activeShip.armor+"");

ShipMoneyLab.setText(MyWorld.activeShip.getMoney+"");

ShipIronLab.setText(MyWorld.activeShip.getIron+"");

ShipStoneLab.setText(MyWorld.activeShip.getStone+"");

} else {ShipInfoPanel.setVisible(false);}

if (MyWorld.activeTower!=null){

ShipInfoPanel1.setVisible(true);

ShipPictLab1.setIcon(MyWorld.activeTower.icn);

ShipNameLab1.setText(MyWorld.activeTower.name);

TowerSpeedLab.setText(MyWorld.activeTower.speed+"");

TowerRadiusLab.setText(MyWorld.activeTower.radius+"");

TowerForceLab.setText(MyWorld.activeTower.force+"");

TowerCritLab.setText(MyWorld.activeTower.crit+"");

TowerFreezeLab.setText(MyWorld.activeTower.freeze+"");

TowerLevelLab.setText(MyWorld.activeTower.level+"");

} else {ShipInfoPanel1.setVisible(false);}

}

///////////////////////////////////////////////////////////////////////////

private void ChangeIndicators(){

if (al.GetPauseInfo()=='p'){PauseIndLab.setVisible(true);}

else {PauseIndLab.setVisible(false);}

if (ActionList.WinGame==1){GameResLab.setText("YOU WIN"); GameResLab.setVisible(true);}

else if (ActionList.LoosGame==1){GameResLab.setText("YOU LOOSE"); GameResLab.setVisible(true);}

else {GameResLab.setVisible(false);}

if (al.GetPauseInfo()=='p'){ControlBut.setText("Start");}

else if (al.GetPauseInfo()=='s') {ControlBut.setText("Pause");}

}

///////////////////////////////////////////////////////////////////////////

private void ChangeActionPanel(){

if (MyWorld.activeTower!=null){

TowerActionPanel.setVisible(true);

MyProtection tower = null;

if (MyWorld.activeTower.name.equals("Laser Tower")){tower = new LaserTower();}

else if (MyWorld.activeTower.name.equals("Big Gravity")){tower = new BigGravity();}

else if (MyWorld.activeTower.name.equals("Stone Protos")){tower = new StoneProtos();}

for (int i=1; i<=MyWorld.activeTower.level; i++){ tower.UpGrade();}

TowerUpMoneyLab.setText(tower.money+"");

TowerUpStoneLab.setText(tower.stone+"");

TowerUpIronLab.setText(tower.iron+"");

int minMoney = (int) (MyWorld.activeTower.money * MyResourses.monper);

int minStone = (int) (MyWorld.activeTower.stone * MyResourses.stper);

int minIron = (int) (MyWorld.activeTower.iron * MyResourses.irper);

TowerSellMoneyLab.setText(minMoney+"");

TowerSellStoneLab.setText(minStone+"");

TowerSellIronLab.setText(minIron+"");

if (tower.money<MyResourses.money && tower.stone<MyResourses.stone

&& tower.iron<MyResourses.iron && MyWorld.activeTower.level<5)

{UpgradeTowerBut.setEnabled(true);}

else {UpgradeTowerBut.setEnabled(false);}

}

else {TowerActionPanel.setVisible(false);}

}

// Variables declaration

... ... ... ... ... ...

// End of variables declaration                  

}

Листинг 6. Файл MyWorld.java

/*

* MyWorld.java

*/

package myrequest;

import java.awt.Color;

import java.awt.Graphics;

import java.awt.Image;

import java.awt.Toolkit;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.awt.image.ImageObserver;

import java.util.Collection;

import java.util.Vector;

import javax.swing.Timer;

/**

* Interface for DrawPanel and ControlPanel classes

* @author Belyaev Alex

*/

interface PrepareWorld { //

MyWorld mw = new MyWorld();

}

//--//////////////////////////////////////////////////////////////////////////

//--//////////////////////////////////////////////////////////////////////////

/**

* General class of game, in this class making all

* game objects and control it

* @author Belyaev Alex

*/

public class MyWorld {

final static int up=1, right=2, down=3, left=4, start=5, end=6;

int startx=0, starty=0; // x and y coords of enter on map

ActionList al = new ActionList();

MyMap mymap  = new MyMap();

MyLevel ml = new MyLevel();

MyResourses mr;

ImageObserver imageobs;

static MyEnemy activeShip = null; // selected ship

static MyProtection activeTower = null; // selected tower

// Collection of enemy ships

protected Collection<MyEnemy> enemy = new Vector<MyEnemy>();

// Collection of towers

protected Collection<MyProtection> towers = new Vector<MyProtection>();   //

/**

* constructor

*/

MyWorld(){

mymap.MakeWay();

mr = new MyResourses();

int coord[] = new int [2];

coord = mymap.GetStartCoord();

startx=(coord[0])*ActionList.CellSize; starty=(coord[1])*ActionList.CellSize;

ArmyMaker();

}

///////////////////////////////////////////////////////////////////////////

/**

* Step of each ship

* @param g Graphics object

*/

public void StepEnemy(Graphics g){ //

for (MyEnemy ship: enemy) {

for (int i=0; i<ship.speed; i++){

if (ship.visible==1){EnemyStep(ship);}

ship.paint(g);

}

}

SortShips();

EndLevel();

}

///////////////////////////////////////////////////////////////////////////

/**

* Making thread for each tower

* @param g Graphics object

*/

public void StepProtection(Graphics g){ //

for (MyProtection tower: towers) {

MyTowerThread mtt = new MyTowerThread(enemy, tower, g);

Thread thread = new Thread(mtt);

thread.start();

}

}

///////////////////////////////////////////////////////////////////////////

/**

* Listen when level will be end

*/

public void EndLevel(){ //

int i=0;

for (MyEnemy ship: enemy) {

if (ship.visible==1){i++;}

}

if (i==0 && !enemy.isEmpty()){

enemy.clear(); System.out.println("-Cleared");

ActionList.LevelNum++;

al.ControlGame('p');

ActionList.StartNewLvl=1;

}

}

///////////////////////////////////////////////////////////////////////////

/**

* Set all object as NULL

*/

public void EndGame(){ //

mr = new MyResourses();

mymap = new MyMap();

mymap.MakeWay();

enemy.clear();

towers.clear();

activeTower = null;

activeShip = null;

System.out.println("-Ended.");

}

///////////////////////////////////////////////////////////////////////////

/**

* Move ship by way

* @param ship that do step now

*/

private void EnemyStep(MyEnemy ship){ //

int airx=ship.coordX; int airy=ship.coordY;

int x=airx/ActionList.CellSize, y=airy/ActionList.CellSize;

//System.out.println(airx+"_"+airy+" "+x+"_"+y+" = "+mymap.Way[x][y]);

if (mymap.Way[x][y]==start){

try {if (mymap.Way[x][y-1]==up){airy--;}}catch (Exception e){}

try {if (mymap.Way[x+1][y]==right){airx++;}}catch (Exception e){}

try {if (mymap.Way[x][y+1]==down){airy++;}}catch (Exception e){}

try {if (mymap.Way[x-1][y]==left){airx--;}}catch (Exception e){}

}

if (mymap.Way[x][(airy-1)/ActionList.CellSize]==up){airy--; ship.ChangeCorner(1);}

try {

if (airy%ActionList.CellSize==0 && mymap.Way[x+1][y]==right){airx++; ship.ChangeCorner(2);}

} catch (Exception e){}

try {

if (airx%ActionList.CellSize==0 && mymap.Way[x][y+1]==down){airy++; ship.ChangeCorner(3);}

} catch (Exception e){}

try {

if (airy%ActionList.CellSize==0 && mymap.Way[x-1][y]==left){airx--; ship.ChangeCorner(4);}

} catch (Exception e){}

try{

if (mymap.Way[x+1][y]==end || mymap.Way[x-1][y]==end ||

mymap.Way[x][y+1]==end || mymap.Way[x][y-1]==end){

ship.visible=0;

System.out.println("DELETED");

ActionList.loos--;

}

}catch (Exception e){}

ship.SaveCood(airx, airy);

}

///////////////////////////////////////////////////////////////////////////

/**

* Sorted ships by way, set ID

*/

protected void SortShips(){ //

int airx=startx, airy=starty;

int x=0; int y=0;

int num=0;

for(MyEnemy ship:enemy){

if (ship.visible==1){num++;}

}

while (num>0){

x=airx/ActionList.CellSize; y=airy/ActionList.CellSize;

if (mymap.Way[x][y]==start){

try {if (mymap.Way[x][y-1]==up){airy--;}}catch (Exception e){}

try {if (mymap.Way[x+1][y]==right){airx++;}}catch (Exception e){}

try {if (mymap.Way[x][y+1]==down){airy++;}}catch (Exception e){}

try {if (mymap.Way[x-1][y]==left){airx--;}}catch (Exception e){}

}

if (mymap.Way[x][(airy-1)/ActionList.CellSize]==up){airy--;}

try {

if (airy%ActionList.CellSize==0 && mymap.Way[x+1][y]==right){airx++;}

} catch (Exception e){}

try {

if (airx%ActionList.CellSize==0 && mymap.Way[x][y+1]==down){airy++;}

} catch (Exception e){}

try {

if (airy%ActionList.CellSize==0 && mymap.Way[x-1][y]==left){airx--;}

} catch (Exception e){}

//

for(MyEnemy ship:enemy){

if (ship.coordX==airx && ship.coordY==airy && ship.visible==1){ship.num=num; num--; System.out.println(ship.name+" #"+num);}

}

}

}

///////////////////////////////////////////////////////////////////////////

/**

* Create ships by level into collection

*/

private void ArmyMaker(){ //

ActionListener timerListener = new ActionListener(){

int x=0, sh=0, ln=0, fin=0;

public void actionPerformed(ActionEvent e) {

if (ActionList.StartNewLvl==1){ActionList.StartNewLvl=0; x=0; sh=0; ln=0; fin=0;}

if (ActionList.NewGame==1){EndGame(); x=0; sh=0; ln=0; fin=0;}

MyEnemy ship = null;

sh=ml.LevelArmy[ln][x];

ln=ActionList.LevelNum;

try{

if (fin==0 && al.GetPauseInfo()=='s' && sh!=0){

if (sh==MyEnemy.swg){ship=new ShortWagon();}

else if (sh==MyEnemy.bp){ship=new BlackPirate();}

else if (sh==MyEnemy.hf){ship=new HardFlier();}

else if (sh==MyEnemy.swl){ship=new SpeedWalker();}

else if (sh==MyEnemy.tb){ship=new Boss();}

ship.SaveCood(startx, starty);

ship.num=x;

ship.armor+=ActionList.LevelNum*2;

ship.armor+=ActionList.LevelNum;

enemy.add(ship);

x++;

System.out.println("KorAblik="+x);

}

else if (sh==0){x++;}

} catch(Exception exc) {fin=1;}

}

};

Timer time = new Timer(2400, timerListener);

time.start();

}

///////////////////////////////////////////////////////////////////////////

/**

* Stand new tower on map

* @param x x coord

* @param y y coord

* @param wht what tower player add

* @return if tower add return true else return false

*/

public boolean AddTower(int x, int y, int wht){ //

MyProtection tower = null;

if (wht==MyProtection.Laser){tower = new LaserTower();}

else if (wht==MyProtection.Gravity){tower = new BigGravity();}

else if (wht==MyProtection.Stone){tower = new StoneProtos();}

if (MyResourses.money>=tower.money && MyResourses.iron>=tower.iron && MyResourses.stone>=tower.stone){

mr.SpendMoney(tower.money);

mr.SpendIron(tower.iron);

mr.SpendStone(tower.stone);

tower.SaveCoord(x*ActionList.CellSize, y*ActionList.CellSize);

towers.add(tower);

System.out.println("ToWeR aDD: "+tower.coordX+"_"+tower.coordY+" from:"+x+"_"+y);

}

else {return false;}

return true;

}

///////////////////////////////////////////////////////////////////////////

/**

* Sell tower and send resourses

*/

public void SellTower(){ //

mr.SendMoney((int) (activeTower.money * MyResourses.monper));

mr.SendStone((int) (activeTower.stone * MyResourses.stper));

mr.SendIron((int) (activeTower.iron * MyResourses.irper));

MyMap.Map[activeTower.coordX/ActionList.CellSize][activeTower.coordY/ActionList.CellSize]=1;

towers.remove(activeTower);

activeTower = null;

}

///////////////////////////////////////////////////////////////////////////

/**

* Select game object

* @param x x coord

* @param y y coord

* @return yes or no

*/

public int Select(int x, int y){ //

for (MyProtection tower: towers) {

if (tower.coordX==(x/ActionList.CellSize)*ActionList.CellSize && tower.coordY==(y/ActionList.CellSize)*ActionList.CellSize){

activeTower=tower; activeShip=null; return 1;

}

}

for (MyEnemy ship: enemy){

if (ship.coordX<=x && ship.coordY<=y && ship.coordX>x-41 && ship.coordY>y-41 && ship.visible==1){

activeShip=ship; activeTower=null; return 2;

}

}

activeShip=null; activeTower=null;

return 0;

}

///////////////////////////////////////////////////////////////////////////

/**

* Draw Build mode

* @param g Graphics object

*/

private void DrawActiveCells(Graphics g){

Image fon =  Toolkit.getDefaultToolkit().getImage("pictures/fon1.png");

int x=0, y=0;

while(y<10){

while (x<20){

if (mymap.MapValue(x, y)==1){ g.drawImage(fon, x*ActionList.CellSize, y*ActionList.CellSize, imageobs);}

x++;

}

x=0; y++;

}

}

///////////////////////////////////////////////////////////////////////////

private void DrawRoot(Graphics g){

Image fon = Toolkit.getDefaultToolkit().getImage("pictures/root.png");

Image fon2 = Toolkit.getDefaultToolkit().getImage("pictures/enter_exit.png");

for (int y=0; y<10; y++){

for (int x=0; x<20; x++){

if (mymap.MapValue(x, y)==9){

g.drawImage(fon, x*ActionList.CellSize, y*ActionList.CellSize, imageobs);

}

else if (mymap.MapValue(x, y)==7 || mymap.MapValue(x, y)==8){

g.drawImage(fon2, x*ActionList.CellSize, y*ActionList.CellSize, imageobs);

}

}

}

}

///////////////////////////////////////////////////////////////////////////

public void DrawTowerBuild(int x, int y, Graphics g){

x=x/ActionList.CellSize; y=y/ActionList.CellSize;

Image fon_g = Toolkit.getDefaultToolkit().getImage("pictures/fon3.png");

Image fon_r = Toolkit.getDefaultToolkit().getImage("pictures/fon2.png");

Image pict = null;

MyProtection tower = null;

if (ActionList.build=='l'){

pict=Toolkit.getDefaultToolkit().getImage("pictures/lasertower_m.png");

tower = new LaserTower();

}

if (ActionList.build=='s'){

pict=Toolkit.getDefaultToolkit().getImage("pictures/stoneprotos_m.png");

tower = new StoneProtos();

}

if (ActionList.build=='g'){

pict=Toolkit.getDefaultToolkit().getImage("pictures/biggravity_m.png");

tower = new BigGravity();

}

int ovalX = x*ActionList.CellSize-tower.radius+20;

int ovalY = y*ActionList.CellSize-tower.radius+20;

if (MyMap.Map[x][y]==1){

g.setColor(Color.GREEN);

g.drawOval(ovalX, ovalY, tower.radius*2, tower.radius*2);

g.drawImage(fon_g, x*ActionList.CellSize, y*ActionList.CellSize, imageobs);

g.drawImage(pict, x*ActionList.CellSize+10, y*ActionList.CellSize+10, imageobs);

}

else {g.drawImage(fon_r, x*ActionList.CellSize, y*ActionList.CellSize, imageobs);}

}

///////////////////////////////////////////////////////////////////////////

private void DrawSelectedUnit(Graphics g){

Image fon = Toolkit.getDefaultToolkit().getImage("pictures/fon4.png");

if (activeShip!=null && activeShip.visible==1){

g.drawImage(fon, activeShip.coordX, activeShip.coordY, imageobs);

}

else if (activeTower!=null){

g.setColor(Color.WHITE);

int ovalX = activeTower.coordX/ActionList.CellSize*ActionList.CellSize-activeTower.radius+20;

int ovalY = activeTower.coordY/ActionList.CellSize*ActionList.CellSize-activeTower.radius+20;

g.drawOval(ovalX, ovalY, activeTower.radius*2, activeTower.radius*2);

g.drawImage(fon, activeTower.coordX, activeTower.coordY, imageobs);

}

if (ActionList.build!='n'){activeTower=null; activeShip=null;}

}

///////////////////////////////////////////////////////////////////////////

public void paint(Graphics g) {

DrawRoot(g);

if (ActionList.DrawOnCells==1){DrawActiveCells(g);}

DrawSelectedUnit(g);

for (MyProtection tower: towers) {tower.paint(g);}

for (MyEnemy ship: enemy) {ship.paint(g);}

}

///////////////////////////////////////////////////////////////////////////

}

Листинг 7. Файл MyMap.java

/*

* MyMap.java

*/

package myrequest;

import java.io.*;

/**

* This class make map and way for ships

* @author Alex Belyaev

*/

public class MyMap { //

static int Map[][] = new int[20][10]; // static map of game

public int Way[][] = new int[20][10]; // way for the ships

/**

* constructor

*/

MyMap(){

MakeMap();

}

///////////////////////////////////////////////////////////////////////////////

/**

* Create map of game by txt document

*/

private void MakeMap(){

int x=0, y=0;

String znach;

BufferedReader in;

try {

in = new BufferedReader(new InputStreamReader(new FileInputStream("resourses/map.txt")));

while (in.ready()) {

String s = in.readLine();

while (x<20){

znach=s.substring(x, x+1);

if (znach.equals("0")){SaveToMap(0, x, y); }

else if (znach.equals("1")){SaveToMap(1, x, y);}

else if (znach.equals("2")){SaveToMap(2, x, y);}

else if (znach.equals("3")){SaveToMap(3, x, y);}

else if (znach.equals("4")){SaveToMap(4, x, y);}

else if (znach.equals("9")){SaveToMap(9, x, y);}

else if (znach.equals("8")){SaveToMap(8, x, y);}

else if (znach.equals("7")){SaveToMap(7, x, y);}

else {SaveToMap(0, x, y);}

x++;

}

y++; x=0;

}

} catch (IOException e) {  }

}

///////////////////////////////////////////////////////////////////////////////

/**

* Search start cell and save coords

* @return int[] coords x and y in massive

*/

public int[] GetStartCoord(){ //

int s[]=new int[2];

for (int j=0; j<10; j++){

for (int i=0; i<20; i++){

if (Way[i][j]==5){ s[0]=i; s[1]=j;}

}

}

return s;

}

///////////////////////////////////////////////////////////////////////////////

/**

* Create way for ships, if don't have end set FatalError

*

*/

public void MakeWay(){ // Create way

int x=0, y=0;

int good=0;

char stage='a';

while (y<10){ while(x<20){ Way[x][y]=0; x++; }  x=0; y++; }

x=0; y=0;

for (int j=0; j<10; j++){

for (int i=0; i<20; i++){

if (MapValue(i, j)==7){ Way[i][j]=MyWorld.start; x=i; y=j;}

}

}

if (y!=0) {if (Map[x][y-1]==9){stage='u';}}

if (x!=19){if (Map[x+1][y]==9){stage='l';}}

if (y!=9) {if (Map[x][y+1]==9){stage='d';}}

if (x!=0) {if (Map[x-1][y]==9){stage='r';}}

int k=0;

while (k<201){

if (stage=='u'){

if (Map[x][y-1]!=9){

if (Map[x+1][y]==9){Way[x][y]=MyWorld.up; stage='r'; }

else if (Map[x-1][y]==9){Way[x][y]=MyWorld.up; stage='l';}

}

else { y--; Way[x][y]=MyWorld.up; }

}

else if (stage=='r'){

if (Map[x+1][y]!=9){

if (Map[x][y-1]==9){Way[x][y]=MyWorld.right; stage='u';}

else if (Map[x][y+1]==9){Way[x][y]=MyWorld.right; stage='d';}

}

else { x++; Way[x][y]=MyWorld.right; }

}

else if (stage=='d'){

if (Map[x][y+1]!=9){

if (Map[x+1][y]==9){Way[x][y]=MyWorld.down; stage='r';}

else if (Map[x-1][y]==9){Way[x][y]=MyWorld.down; stage='l';}

}

else { y++; Way[x][y]=MyWorld.down; }

}

else if (stage=='l'){

if (Map[x-1][y]!=9){

if (Map[x][y-1]==9){Way[x][y]=MyWorld.left; stage='u';}

else if (Map[x][y+1]==9){Way[x][y]=MyWorld.left; stage='d';}

}

else { x--; Way[x][y]=MyWorld.left; }

}

if (stage=='r'){

if (Map[x+1][y]==8){Way[x+1][y]=MyWorld.end; good++; break;}

}

if (stage=='l'){

if (Map[x-1][y]==8){Way[x-1][y]=MyWorld.end; good++; break;}

}

if (stage=='u'){

if (Map[x][y-1]==8){Way[x][y-1]=MyWorld.end; good++; break;}

}

if (stage=='d'){

if (Map[x][y+1]==8){Way[x][y+1]=MyWorld.end; good++; break;}

}

k++;

}

if (good!=1){

System.out.println("ERORR!!!!!!!!");

ActionList.FatalErr=true;

}

}

///////////////////////////////////////////////////////////////////////////////

/**

* Print way massive

*/

public void PrintWay(){

for (int j=0; j<10; j++){

for (int i=0; i<20; i++){

System.out.print(Way[i][j]+" ");

}

System.out.print("\n");

}

}

///////////////////////////////////////////////////////////////////////////////

/**

* Function save value to massive in x and y coords

* @param wht what you want to save to massive

* @param x x coord

* @param y y coord

*/

public void SaveToMap(int wht, int x, int y){

Map[x][y]=wht;

}

///////////////////////////////////////////////////////////////////////////////

/**

* Print map massive

*/

public void PrintAllMap(){

for (int j=0; j<10; j++){

for (int i=0; i<20; i++){

System.out.print(Map[i][j]+" ");

}

System.out.print("\n");

}

}

///////////////////////////////////////////////////////////////////////////////

/**

* Get value from massive

* @return value from map massive

* @param x x coord

* @param y y coord

*/

public int MapValue(int x, int y){

return Map[x][y];

}

///////////////////////////////////////////////////////////////////////////////

}

Листинг 8. Файл MyEnemy.java

/*

* MyEnemy.java

*/

package myrequest;

import java.awt.Graphics;

import java.awt.Image;

import java.awt.Toolkit;

import java.awt.image.ImageObserver;

import javax.swing.Icon;

import javax.swing.ImageIcon;

/**

* General class for all ships

* @author Belyaev Alex

*/

public class MyEnemy {

static final int swg=1, bp=2, hf=3, swl=4, tb=5;

ImageObserver imageobs;

int speed=0, health=0, armor=0, getStone=0, getMoney=0, getIron=0, num=0; // ship stats

Image ship = null, ship_u = null, ship_r = null, ship_d = null, ship_l

Похожие материалы

Информация о работе