Разработка игровой программы для андроида

Общая характеристика игровых стратегий в жанре "башенная защита". Анализ GUI как графического пользовательского интерфейса, особенности его реализации. Математический подход в обеспечении игрового баланса. Реализация баланса в игре жанра башенной защиты.

Рубрика Программирование, компьютеры и кибернетика
Вид курсовая работа
Язык русский
Дата добавления 16.07.2016
Размер файла 125,0 K

Отправить свою хорошую работу в базу знаний просто. Используйте форму, расположенную ниже

Студенты, аспиранты, молодые ученые, использующие базу знаний в своей учебе и работе, будут вам очень благодарны.

gameField.removeTower(cellCoordinate.x, cellCoordinate.y);

//} else if(button == 1) {

//gameField.createCreep(cellCoordinate.x, cellCoordinate.y);

} else if(button == 1) {

gameField.setExitPoint(cellCoordinate.x, cellCoordinate.y);

} else if(button == 4) {

gameField.setSpawnPoint(cellCoordinate.x, cellCoordinate.y);

}

}

return false;

}

@Override

public boolean longPress(float x, float y) {

Gdx.app.log("CameraController::longPress()", " -- x:" + x + " y:" + y);

//gameField.createSpawnTimerForCreeps();

return false;

}

@Override

public boolean fling(float velocityX, float velocityY, int button) {

Gdx.app.log("CameraController::fling()", " -- velocityX:" + velocityX + " velocityY:" + velocityY + " button:" + button);

if(!lastCircleTouched) {

flinging = true;

velX = camera.zoom * velocityX * 0.5f;

velY = camera.zoom * velocityY * 0.5f;

}

return false;

}

@Override

public boolean pan(float x, float y, float deltaX, float deltaY) {

Gdx.app.log("CameraController::pan()", " -- x:" + x + " y:" + y + " deltaX:" + deltaX + " deltaY:" + deltaY);

if(gameInterface.getTowersRoulette().makeRotation(x, y, deltaX, deltaY)) {

lastCircleTouched = true;

return true;

}

lastCircleTouched = false;

if(gameField.getUnderConstruction() == null) {

if (camera.position.x + -deltaX * camera.zoom < MAX_DESTINATION_X && camera.position.x + -deltaX * camera.zoom > 0)

camera.position.add(-deltaX * camera.zoom, 0, 0);

if (Math.abs(camera.position.y + deltaY * camera.zoom) < MAX_DESTINATION_Y)

camera.position.add(0, deltaY * camera.zoom, 0);

}

return false;

}

@Override

public boolean panStop(float x, float y, int pointer, int button) {

Gdx.app.log("CameraController::panStop()", " -- x:" + x + " y:" + y + " pointer:" + pointer + " button:" + button);

return false;

}

@Override

public boolean zoom(float initialDistance, float distance) {

Gdx.app.log("CameraController::zoom()", " -- initialDistance:" + initialDistance + " distance:" + distance);

float ratio = initialDistance / distance;

float newZoom = initialScale * ratio;

if (newZoom < MAX_ZOOM && newZoom > MIN_ZOOM) {

camera.zoom = newZoom;

}

return false;

}

@Override

public boolean pinch(Vector2 initialPointer1, Vector2 initialPointer2, Vector2 pointer1, Vector2 pointer2) {

Gdx.app.log("CameraController::pinch()", " -- initialPointer1:" + initialPointer1 + " initialPointer2:" + initialPointer2 + " pointer1:" + pointer1 + " pointer2:" + pointer2);

return false;

}

public void update () {

if(gameField.getUnderConstruction() == null) {

if (flinging) {

velX *= 0.98f;

velY *= 0.98f;

if (camera.position.x + -velX * Gdx.graphics.getDeltaTime() > 0 && camera.position.x + -velX * Gdx.graphics.getDeltaTime() < MAX_DESTINATION_X)

camera.position.add(-velX * Gdx.graphics.getDeltaTime(), 0, 0);

if (Math.abs(camera.position.y + velY * Gdx.graphics.getDeltaTime()) < MAX_DESTINATION_Y)

camera.position.add(0, velY * Gdx.graphics.getDeltaTime(), 0);

if (Math.abs(velX) < 0.01f) velX = 0;

if (Math.abs(velY) < 0.01f) velY = 0;

}

}

}

}

class MyGestureDetector extends GestureDetector {

public MyGestureDetector(GestureListener listener) {

super(listener);

}

@Override

public boolean keyDown(int keycode) {

Gdx.app.log("MyGestureDetector::keyDown()", " -- keycode:" + keycode);

return false;

}

@Override

public boolean keyUp(int keycode) {

Gdx.app.log("MyGestureDetector::keyUp()", " -- keycode:" + keycode);

return false;

}

@Override

public boolean keyTyped(char character) {

Gdx.app.log("MyGestureDetector::keyTyped()", " -- character:" + character);

return false;

}

@Override

public boolean touchDown(int screenX, int screenY, int pointer, int button) {

Gdx.app.log("MyGestureDetector::touchDown()", " -- screenX:" + screenX + " screenY:" + screenY + " pointer:" + pointer + " button:" + button);

Vector3 touch = new Vector3(screenX, screenY, 0);

camera.unproject(touch);

GridPoint2 grafCoordinate = new GridPoint2((int) touch.x, (int) touch.y);

GridPoint2 cellCoordinate = gameField.whichCell(grafCoordinate);

if(cellCoordinate != null) {

if(gameField.getUnderConstruction() != null) {

gameField.getUnderConstruction().setStartCoors(cellCoordinate.x, cellCoordinate.y);

}

// Gdx.app.log("MyGestureDetector::mouseMoved()", " -- cellCoordinate.x:" + cellCoordinate.x + " cellCoordinate.y:" + cellCoordinate.y);

}

return false;

}

@Override

public boolean touchUp(int screenX, int screenY, int pointer, int button) {

Gdx.app.log("MyGestureDetector::touchUp()", " -- screenX:" + screenX + " screenY:" + screenY + " pointer:" + pointer + " button:" + button);

Vector3 touch = new Vector3(screenX, screenY, 0);

camera.unproject(touch);

GridPoint2 grafCoordinate = new GridPoint2((int) touch.x, (int) touch.y);

GridPoint2 cellCoordinate = gameField.whichCell(grafCoordinate);

if(cellCoordinate != null) {

gameField.buildTowersWithUnderConstruction(cellCoordinate.x, cellCoordinate.y);

// Gdx.app.log("MyGestureDetector::mouseMoved()", " -- cellCoordinate.x:" + cellCoordinate.x + " cellCoordinate.y:" + cellCoordinate.y);

}

return false;

}

@Override

public boolean touchDragged(int screenX, int screenY, int pointer) {

Gdx.app.log("MyGestureDetector::touchDragged()", " -- screenX:" + screenX + " screenY:" + screenY + " pointer:" + pointer);

Vector3 touch = new Vector3(screenX, screenY, 0);

camera.unproject(touch);

GridPoint2 grafCoordinate = new GridPoint2((int) touch.x, (int) touch.y);

GridPoint2 cellCoordinate = gameField.whichCell(grafCoordinate);

if(cellCoordinate != null) {

if(gameField.getUnderConstruction() != null) {

gameField.getUnderConstruction().setEndCoors(cellCoordinate.x, cellCoordinate.y);

}

// Gdx.app.log("MyGestureDetector::mouseMoved()", " -- cellCoordinate.x:" + cellCoordinate.x + " cellCoordinate.y:" + cellCoordinate.y);

}

return false;

}

@Override

public boolean mouseMoved(int screenX, int screenY) {

Gdx.app.log("MyGestureDetector::mouseMoved()", " -- screenX:" + screenX + " screenY:" + screenY);

Vector3 touch = new Vector3(screenX, screenY, 0);

camera.unproject(touch);

GridPoint2 grafCoordinate = new GridPoint2((int) touch.x, (int) touch.y);

GridPoint2 cellCoordinate = gameField.whichCell(grafCoordinate);

if(cellCoordinate != null) {

if(gameField.getUnderConstruction() != null) {

gameField.getUnderConstruction().setEndCoors(cellCoordinate.x, cellCoordinate.y);

}

// Gdx.app.log("MyGestureDetector::mouseMoved()", " -- cellCoordinate.x:" + cellCoordinate.x + " cellCoordinate.y:" + cellCoordinate.y);

}

return false;

}

@Override

public boolean scrolled(int amount) {

Gdx.app.log("MyGestureDetector::scrolled()", " -- amount:" + amount);

if(amount == 1) {

if (camera.zoom <= MAX_ZOOM)

camera.zoom += 0.1f;

} else if(amount == -1) {

if (camera.zoom >= MIN_ZOOM)

camera.zoom -= 0.1f;

}

camera.update();

return false;

}

}

private CameraController cameraController = new CameraController();

private MyGestureDetector myGestureDetector = new MyGestureDetector(cameraController);

public GameScreen() {

this.gs = this;

this.camera = new OrthographicCamera();

this.camera.setToOrtho(false, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());

gameField = new GameField("maps/arena3.tmx");

gameInterface = new GameInterface(gameField);

InputMultiplexer inputMultiplexer = gameInterface.setCommonInputHandler(new GestureDetector(cameraController));

inputMultiplexer.addProcessor(myGestureDetector);

Gdx.input.setInputProcessor(inputMultiplexer);

Gdx.app.log("tag", "cel " + gameField.getSizeCellX() + " field" + gameField.getSizeFieldX());

Gdx.app.log("tag", "cel " + gameField.getSizeCellY() + " field" + gameField.getSizeFieldY());

MAX_DESTINATION_X = gameField.getSizeCellX() * gameField.getSizeFieldX();

MAX_DESTINATION_Y = gameField.getSizeCellY() * gameField.getSizeFieldY() / 2f;

}

@Override

public void show() {

//Start position of camera

camera.position.add((gameField.getSizeFieldX()*gameField.getSizeCellX())/2,0,0);

}

private void inputHandler(float delta) {

if(Gdx.input.isKeyJustPressed(Input.Keys.MINUS)) {

if(camera.zoom <= MAX_ZOOM)

camera.zoom += 0.1f;

camera.update();

Gdx.app.log("GameScreen::inputHandler()", "-- Pressed MINUS");

} else if(Gdx.input.isKeyJustPressed(Input.Keys.PLUS)) {

if(camera.zoom >= MIN_ZOOM)

camera.zoom -= 0.1f;

camera.update();

Gdx.app.log("GameScreen::inputHandler()", "-- Pressed PLUS");

} else if(Gdx.input.isKeyJustPressed(Input.Keys.NUM_0) || Gdx.input.isKeyJustPressed(Input.Keys.NUMPAD_0)) {

//gameField.setGamePause(!gameField.getGamePaused());

gameInterface.getCreepsRoulette().buttonClick();

Gdx.app.log("GameScreen::inputHandler()", "-- Pressed NUM_0");

} else if(Gdx.input.isKeyJustPressed(Input.Keys.NUM_1)) {

gameField.isDrawableGrid = !gameField.isDrawableGrid;

Gdx.app.log("GameScreen::inputHandler()", "-- gameField.isDrawableGrid:" + gameField.isDrawableGrid);

} else if(Gdx.input.isKeyJustPressed(Input.Keys.NUM_2)) {

gameField.isDrawableCreeps = !gameField.isDrawableCreeps;

Gdx.app.log("GameScreen::inputHandler()", "-- gameField.isDrawableCreeps:" + gameField.isDrawableCreeps);

} else if(Gdx.input.isKeyJustPressed(Input.Keys.NUM_3)) {

gameField.isDrawableTowers = !gameField.isDrawableTowers;

Gdx.app.log("GameScreen::inputHandler()", "-- gameField.isDrawableTowers:" + gameField.isDrawableTowers);

} else if(Gdx.input.isKeyJustPressed(Input.Keys.NUM_4)) {

gameField.isDrawableRoutes = !gameField.isDrawableRoutes;

Gdx.app.log("GameScreen::inputHandler()", "-- gameField.isDrawableRoutes:" + gameField.isDrawableRoutes);

} else if(Gdx.input.isKeyJustPressed(Input.Keys.NUM_5)) {

gameField.isDrawableGridNav = !gameField.isDrawableGridNav;

Gdx.app.log("GameScreen::inputHandler()", "-- gameField.isDrawableGridNav:" + gameField.isDrawableGridNav);

}

}

@Override

public void render(float delta) {

//Gdx.app.log("GameScreen::render()", "-- delta:" + delta);

Gdx.gl20.glClearColor(0, 0, 0, 1);

Gdx.gl20.glClear(GL20.GL_COLOR_BUFFER_BIT);

String gameState = gameField.getGameState();

if (gameState.equals("In progress")) {

inputHandler(delta);

cameraController.update();

camera.update();

gameField.render(delta, camera);

gameInterface.act(delta);

gameInterface.draw();

gameInterface.getInterfaceStage().getBatch().begin();

bitmapFont.getData().setScale(4);

bitmapFont.setColor(Color.YELLOW);

bitmapFont.draw(gameInterface.getInterfaceStage().getBatch(), String.valueOf("Gold amount: " + gameField.getGamerGold()), Gdx.graphics.getWidth() / 2 - 150, Gdx.graphics.getHeight() - 10);

gameInterface.getInterfaceStage().getBatch().end();

} else if(gameState.equals("Lose")){

currentDuration += delta;

if(currentDuration > MAX_DURATION_FOR_DEFEAT_SCREEN) {

//this.dispose();

TowerDefence.getInstance().setMainMenu(this);

return;

}

if(defeatScreen == null)

defeatScreen = new Texture(Gdx.files.internal("img/defeat.jpg"));

gameInterface.getInterfaceStage().getBatch().begin();

gameInterface.getInterfaceStage().getBatch().draw(defeatScreen, 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());

gameInterface.getInterfaceStage().getBatch().end();

}else if (gameState.equals("Win")){

currentDuration += delta;

if(currentDuration > MAX_DURATION_FOR_DEFEAT_SCREEN) {

//this.dispose();

TowerDefence.getInstance().setMainMenu(this);

return;

}

if(defeatScreen == null)

defeatScreen = new Texture(Gdx.files.internal("img/victory.jpg"));

gameInterface.getInterfaceStage().getBatch().begin();

gameInterface.getInterfaceStage().getBatch().draw(defeatScreen, 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());

gameInterface.getInterfaceStage().getBatch().end();

} else {

Gdx.app.log("Something goes wrong", "123");

}

}

@Override

public void resize(int width, int height) {

camera.viewportHeight = height;

camera.viewportWidth = width;

camera.update();

Gdx.app.log("GameScreen::resize()", "-- New width:" + width + " height:" + height);

//gameInterface.getInterfaceStage().getViewport().update(width, height);

//gameInterface.getInterfaceStage().getCamera().viewportHeight = height;

//gameInterface.getInterfaceStage().getCamera().viewportWidth = width;

//gameInterface.getInterfaceStage().getCamera().update();

}

@Override

public void pause() {

}

@Override

public void resume() {

}

@Override

public void hide() {

//dispose();

}

@Override

public void dispose() {

gameField = null;

gameInterface = null;

}

}

CreepsRoulette.java:

package com.betmansmall.game.GameScreenInteface;

import com.badlogic.gdx.Application;

import com.badlogic.gdx.Gdx;

import com.badlogic.gdx.graphics.Texture;

import com.badlogic.gdx.scenes.scene2d.Group;

import com.badlogic.gdx.scenes.scene2d.InputEvent;

import com.badlogic.gdx.scenes.scene2d.ui.Image;

import com.badlogic.gdx.scenes.scene2d.ui.ImageButton;

import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;

import com.betmansmall.game.GameScreen;

import com.betmansmall.game.gameLogic.Creep;

import com.betmansmall.game.gameLogic.GameField;

import java.util.Arrays;

import java.util.List;

public class CreepsRoulette extends Roulette {

private CreepsRoulette cr;

private Group group;

private ImageButton playButton;

private ImageButton pauseButton;

private static volatile Boolean IS_PAUSE = true;

private static GameScreen gs;

private GameField gameField;

public CreepsRoulette(GameField gameField) {

this.gameField = gameField;

init();

}

private void init() {

group = new Group();

playButton = new ImageButton(new Image(new Texture(Gdx.files.internal("img/playbutton.png"))).getDrawable());

playButton.setSize(getLocalWidth(ROULETTE_RADIUS),getLocalHeight(ROULETTE_RADIUS));

playButton.setPosition(0, 0);

pauseButton = new ImageButton(new Image(new Texture(Gdx.files.internal("img/pausebutton.png"))).getDrawable());

pauseButton.setSize(getLocalWidth(ROULETTE_RADIUS),getLocalHeight(ROULETTE_RADIUS));

pauseButton.setPosition(0, 0);

pauseButton.setVisible(true);

group.addActor(pauseButton);

group.addActor(playButton);

}

public void buttonClick() {

if(IS_PAUSE) {

IS_PAUSE = !IS_PAUSE;

pauseButton.setZIndex(1);

playButton.setZIndex(0);

} else {

IS_PAUSE = !IS_PAUSE;

pauseButton.setZIndex(0);

playButton.setZIndex(1);

}

gameField.setGamePause(IS_PAUSE);

}

public boolean isButtonTouched(float x, float y) {

boolean isTouched = false;

if(x <= getLocalWidth(ROULETTE_RADIUS)&& y > Gdx.graphics.getHeight() - getLocalHeight(ROULETTE_RADIUS)){

isTouched = true;

}

if(isTouched) buttonClick();

return isTouched;

}

@Override

public List<Group> getGroup() {

return Arrays.asList(group);

}

}

GameInterface.java:

package com.betmansmall.game.GameScreenInteface;

import com.badlogic.gdx.Gdx;

import com.badlogic.gdx.InputMultiplexer;

import com.badlogic.gdx.InputProcessor;

import com.badlogic.gdx.scenes.scene2d.Actor;

import com.badlogic.gdx.scenes.scene2d.Stage;

import com.betmansmall.game.gameLogic.GameField;

import static com.badlogic.gdx.scenes.scene2d.actions.Actions.moveTo;

import static com.badlogic.gdx.scenes.scene2d.actions.Actions.parallel;

import static com.badlogic.gdx.scenes.scene2d.actions.Actions.rotateBy;

import static com.badlogic.gdx.scenes.scene2d.actions.Actions.touchable;

/**

* Created by Transet on 07.02.2016.

* This class provides elements which placed on game screen.

* TODO implement more interface options

*/

public class GameInterface {

public enum GameInterfaceElements {

TOWERS_ROULETTE,

CREEPS_ROULETTE

}

public TowersRoulette getTowersRoulette() {

return towersRoulette;

}

public void setTowersRoulette(TowersRoulette towersRoulette) {

this.towersRoulette = towersRoulette;

}

public CreepsRoulette getCreepsRoulette() {

return creepsRoulette;

}

public Stage getInterfaceStage(){

return stage;

}

public void setCreepsRoulette(CreepsRoulette creepsRoulette) {

this.creepsRoulette = creepsRoulette;

}

private TowersRoulette towersRoulette;

private CreepsRoulette creepsRoulette;

private Stage stage;

private GameField gameField;

public GameInterface(GameField gameField) {

this.gameField = gameField;

init();

}

private void init() {

stage = new Stage();

towersRoulette = new TowersRoulette(gameField);

creepsRoulette = new CreepsRoulette(gameField);

for(Actor actor : creepsRoulette.getGroup()) {

stage.addActor(actor);

}

for(Actor actor : towersRoulette.getGroup()) {

stage.addActor(actor);

}

}

public InputMultiplexer setCommonInputHandler(InputProcessor inputProcessor) {

InputMultiplexer inputMultiplexer = new InputMultiplexer();

inputMultiplexer.addProcessor(inputProcessor);

inputMultiplexer.addProcessor(stage);

return inputMultiplexer;

}

public void act(float delta) {

stage.act(delta);

}

public void draw() {

stage.draw();

}

}

TowerRoulette.java:

package com.betmansmall.game.GameScreenInteface;

import com.badlogic.gdx.Gdx;

import com.badlogic.gdx.graphics.Texture;

import com.badlogic.gdx.math.Vector2;

import com.badlogic.gdx.scenes.scene2d.Group;

import com.badlogic.gdx.scenes.scene2d.actions.RotateByAction;

import com.badlogic.gdx.scenes.scene2d.actions.RotateToAction;

import com.badlogic.gdx.scenes.scene2d.ui.Image;

import com.badlogic.gdx.scenes.scene2d.ui.ImageButton;

import com.badlogic.gdx.utils.Array;

import com.betmansmall.game.gameLogic.GameField;

import com.betmansmall.game.gameLogic.playerTemplates.Faction;

import com.betmansmall.game.gameLogic.playerTemplates.FactionsManager;

import com.betmansmall.game.gameLogic.playerTemplates.TemplateForTower;

import java.util.Arrays;

import java.util.Collections;

import java.util.List;

import static com.badlogic.gdx.scenes.scene2d.actions.Actions.*;

public class TowersRoulette extends Roulette {

private Group circleGroup;

private Group buttonGroup;

private ImageButton rouletteButton;

private ImageButton rouletteCircle;

private static volatile Boolean IS_HIDE_TOWERS = true;

private GameField gameField;

private RotateToAction rotateToAction;

private TemplateForTower templateForTower;

private FactionsManager factionsManager;

private Faction faction;

public TowersRoulette(GameField gameField) {

this.gameField = gameField;

init();

}

private void init() {

circleGroup = new Group();

buttonGroup = new Group();

rouletteButton = new ImageButton(new Image(new Texture(Gdx.files.internal("img/tower_roulette_main.png"))).getDrawable());

rouletteButton.setName("rouletteButton");

rouletteButton.setSize(getLocalWidth(ROULETTE_RADIUS), getLocalHeight(ROULETTE_RADIUS));

rouletteButton.setPosition(Gdx.graphics.getWidth() - rouletteButton.getWidth(), 0);

rouletteButton.setOrigin(Gdx.graphics.getWidth(), 0);

buttonGroup.addActor(rouletteButton);

buttonGroup.setOrigin(Gdx.graphics.getWidth(), 0);

rouletteCircle = new ImageButton(new Image(new Texture(Gdx.files.internal("img/golden_ring.png"))).getDrawable());

rouletteCircle.setSize(getLocalWidth(RING_RADIUS) * 2, getLocalHeight(RING_RADIUS) * 2);

rouletteCircle.setPosition(Gdx.graphics.getWidth() - rouletteCircle.getWidth() / 2, 0 - rouletteCircle.getHeight() / 2);

rouletteCircle.setVisible(false);

circleGroup.addActor(rouletteCircle);

circleGroup.setOrigin(Gdx.graphics.getWidth(), 0);

}

private void buttonClick() {

IS_HIDE_TOWERS = !IS_HIDE_TOWERS;

rouletteCircle.setVisible(!IS_HIDE_TOWERS);

rouletteButton.setPosition(Gdx.graphics.getWidth() - rouletteButton.getWidth(), 0);

if(IS_HIDE_TOWERS)

gameField.cancelUnderConstruction();

}

private void ringClick(){

// Gdx.app.log("TAG", "Tower is selected");

rouletteButton.setSize(getLocalWidth(ROULETTE_RADIUS), getLocalHeight(ROULETTE_RADIUS));

rouletteButton.setPosition(Gdx.graphics.getWidth() - rouletteButton.getWidth(), 0);

float trash = circleGroup.getRotation() % 90; //TODO rename trash variable

if(trash > 45 ) {

circleGroup.addAction(rotateBy(90f - trash, 0.5f));

} else {

circleGroup.addAction(rotateBy(-trash, 0.5f));

}

//TODO implement neccessary part just workaround

chooseTower(trash);

}

public boolean makeRotation(float x, float y, float deltaX, float deltaY) {

x = Gdx.graphics.getWidth() - x;

y = Gdx.graphics.getHeight() - y;

if((x*x + y*y) <= (getLocalWidth(RING_RADIUS) * getLocalWidth(RING_RADIUS))

&& x <= getLocalWidth(RING_RADIUS) && y <= getLocalWidth(RING_RADIUS) && !IS_HIDE_TOWERS) {

if (!((x*x + y*y) <= getLocalWidth(ROULETTE_RADIUS) * getLocalWidth(ROULETTE_RADIUS)

&& x <= getLocalWidth(ROULETTE_RADIUS) && y <= getLocalWidth(ROULETTE_RADIUS))) {

float rotation = -((deltaX < 0)? -1f : 1f) * ((deltaY < 0)? deltaY * (-1f) : deltaY);

circleGroup.rotateBy(rotation);

return true;

}

}

return false;

}

public void chooseTower(float isGreatedRound) {

Array<TemplateForTower> templateForTowers = gameField.getAllFirstTowersFromFirstFaction();

TemplateForTower localTemplate = templateForTowers.get(0);

float tmp;

if(isGreatedRound > 45 ) {

tmp = 90f - isGreatedRound + circleGroup.getRotation();

} else {

tmp = - isGreatedRound + circleGroup.getRotation();

}

int towerId = (int)(tmp % (90 * templateForTowers.size)) / 90;

if(towerId < templateForTowers.size)

localTemplate = templateForTowers.get(Math.abs(towerId));

Gdx.app.log("tag", "sette :" + localTemplate.name);

gameField.createdUnderConstruction(localTemplate);

}

public boolean isButtonTouched(float x, float y) {

boolean isTouched = false;

x = Gdx.graphics.getWidth() - x;

y = Gdx.graphics.getHeight() - y;

//RING PRESS DETECTION

if((x*x + y*y) <= (getLocalWidth(RING_RADIUS) * getLocalWidth(RING_RADIUS))

&& x <= getLocalWidth(RING_RADIUS) && y <= getLocalWidth(RING_RADIUS) && !IS_HIDE_TOWERS) {

if (!((x*x + y*y) <= getLocalWidth(ROULETTE_RADIUS) * getLocalWidth(ROULETTE_RADIUS)

&& x <= getLocalWidth(ROULETTE_RADIUS) && y <= getLocalWidth(ROULETTE_RADIUS))) {

isTouched = true;

Gdx.app.log("TAG", "RING");

if(isTouched) ringClick();

return isTouched;

}

}

//BUTTON PRESS DETECTION

if ((x*x + y*y) <= getLocalWidth(ROULETTE_RADIUS) * getLocalWidth(ROULETTE_RADIUS)

&& x <= getLocalWidth(ROULETTE_RADIUS) && y <= getLocalWidth(ROULETTE_RADIUS)) {

isTouched = true;

// Gdx.app.log("TAG", "ROULETTE");

// return isTouched;

if(isTouched) buttonClick();

return isTouched;

}

// Gdx.app.log("TAG", "NOTHING");

return false;

}

@Override

public List<Group> getGroup() {

return Arrays.asList(buttonGroup, circleGroup);

}

}

GameField.java:

package com.betmansmall.game.gameLogic;

import com.badlogic.gdx.Gdx;

import com.badlogic.gdx.graphics.Color;

import com.badlogic.gdx.graphics.OrthographicCamera;

import com.badlogic.gdx.graphics.g2d.Animation;

import com.badlogic.gdx.graphics.g2d.BitmapFont;

import com.badlogic.gdx.graphics.g2d.SpriteBatch;

import com.badlogic.gdx.graphics.g2d.TextureRegion;

import com.badlogic.gdx.graphics.glutils.ShapeRenderer;

import com.badlogic.gdx.maps.MapLayer;

import com.badlogic.gdx.maps.MapLayers;

import com.badlogic.gdx.maps.tiled.TiledMap;

import com.badlogic.gdx.maps.tiled.TiledMapTileLayer;

import com.badlogic.gdx.maps.tiled.TiledMapTileSet;

import com.badlogic.gdx.maps.tiled.TiledMapTileSets;

import com.badlogic.gdx.maps.tiled.TmxMapLoader;

import com.badlogic.gdx.maps.tiled.renderers.IsometricTiledMapRenderer;

import com.badlogic.gdx.maps.tiled.tiles.AnimatedTiledMapTile;

import com.badlogic.gdx.maps.tiled.tiles.StaticTiledMapTile;

import com.badlogic.gdx.math.GridPoint2;

import com.badlogic.gdx.utils.Array;

import com.betmansmall.game.WhichCell;

import com.betmansmall.game.gameLogic.pathfinderAlgorithms.GridNav.GridNav;

import com.betmansmall.game.gameLogic.pathfinderAlgorithms.GridNav.Vertex;

import com.betmansmall.game.gameLogic.playerTemplates.Direction;

import com.betmansmall.game.gameLogic.playerTemplates.FactionsManager;

import com.betmansmall.game.gameLogic.playerTemplates.TemplateForTower;

import com.betmansmall.game.gameLogic.playerTemplates.TemplateForUnit;

import java.util.ArrayDeque;

/**

* Created by betmansmall on 08.02.2016.

*/

public class GameField {

private ShapeRenderer shapeRenderer = new ShapeRenderer();

private SpriteBatch spriteBatch = new SpriteBatch();

private BitmapFont bitmapFont = new BitmapFont();

private TiledMap map;

private IsometricTiledMapRenderer renderer;

private int sizeFieldX, sizeFieldY;

private int sizeCellX, sizeCellY;

public int getSizeFieldX() {

return sizeFieldX;

} public int getSizeFieldY() {

return sizeFieldY;

}

public int getSizeCellX() {

return sizeCellX;

} public int getSizeCellY() {

return sizeCellY;

}

// private TiledMapTileLayer foreground, backbround;

public boolean isDrawableGrid = true;

public boolean isDrawableCreeps = true;

public boolean isDrawableTowers = true;

public boolean isDrawableRoutes = true;

public boolean isDrawableGridNav = false;

private Cell[][] field;

private GridNav gridNav;

// private GridPoint2 spawnPoint, exitPoint;

private WaveManager waveManager;

// private int defaultNumCreateCreeps = 100;

private CreepsManager creepsManager;

private TowersManager towersManager;

private FactionsManager factionsManager;

// private float intervalForSpawnCreeps = 1f;

// private float elapsedTimeForSpawn = 0f;

// GAME INTERFACE ZONE1

private WhichCell whichCell;

private boolean gamePaused;

private int maxOfMissedCreeps;

private int missedCreeps;

private int gamerGold;

// GAME INTERFACE ZONE2

//TEST ZONE1

private Animation animation;

private float stateTime;

//TEST ZONE2

public GameField(String mapName) {

map = new TmxMapLoader().load(mapName);

renderer = new IsometricTiledMapRenderer(map, spriteBatch);

sizeFieldX = map.getProperties().get("width", Integer.class);

sizeFieldY = map.getProperties().get("height", Integer.class);

sizeCellX = map.getProperties().get("tilewidth", Integer.class);

sizeCellY = map.getProperties().get("tileheight", Integer.class);

waveManager = new WaveManager();

creepsManager = new CreepsManager();

towersManager = new TowersManager();

factionsManager = new FactionsManager();

createField(sizeFieldX, sizeFieldY, map.getLayers());

TiledMapTileSets tileSets = map.getTileSets();

for(TiledMapTileSet tileSet:tileSets) {

String tileSetName = tileSet.getName();

Gdx.app.log("GameField::GameField()", "-- TileSet:" + tileSetName);

if(tileSetName.contains("unit")) {

TemplateForUnit unit = new TemplateForUnit(tileSet);

factionsManager.addUnitToFaction(unit);

if(animation == null) {

AnimatedTiledMapTile animatedTiledMapTile = unit.animations.get("idle_" + Direction.UP);

StaticTiledMapTile[] staticTiledMapTiles = animatedTiledMapTile.getFrameTiles();

Array<TextureRegion> textureRegions = new Array<TextureRegion>(staticTiledMapTiles.length);

// Gdx.app.log("GameField::GameField()", " -- textureRegion.size:" + staticTiledMapTiles.length);

for(int k = 0; k < staticTiledMapTiles.length; k++) {

TextureRegion textureRegion = staticTiledMapTiles[k].getTextureRegion();

textureRegions.add(textureRegion);

}

stateTime = 0f;

animation = new Animation(0.25f, textureRegions);

}

} else if(tileSetName.contains("tower")) {

TemplateForTower tower = new TemplateForTower(tileSet);

factionsManager.addTowerToFaction(tower);

}

}

// GAME INTERFACE ZONE1

whichCell = new WhichCell(sizeFieldX, sizeFieldY, sizeCellX, sizeCellY);

gamePaused = true;

maxOfMissedCreeps = 7;

missedCreeps = 0;

gamerGold = 50;

// GAME INTERFACE ZONE2

}

private void createField(int sizeFieldX, int sizeFieldY, MapLayers mapLayers) {

if(field == null) {

field = new Cell[sizeFieldX][sizeFieldY];

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

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

field[x][y] = new Cell();

for(MapLayer mapLayer: mapLayers) {

if(mapLayer instanceof TiledMapTileLayer) {

TiledMapTileLayer layer = (TiledMapTileLayer) mapLayer;

TiledMapTileLayer.Cell cell = layer.getCell(x, y);

if(cell != null) {

if(cell.getTile().getProperties().get("busy") != null) {

field[x][y].setTerrain();

} else if(cell.getTile().getProperties().get("spawnPoint") != null && cell.getTile().getProperties().get("spawnPoint").equals("1")) {

// spawnPoint = new GridPoint2(x, y);

waveManager.spawnPoints.add(new GridPoint2(x, y));

// field[x][y].setTerrain();

Gdx.app.log("GameField::GameField()", "-- Set spawnPoint: (" + x + ", " + y + ")");

} else if (cell.getTile().getProperties().get("exitPoint") != null && cell.getTile().getProperties().get("exitPoint").equals("1")) {

// exitPoint = new GridPoint2(x, y);

waveManager.exitPoints.add(new GridPoint2(x, y));

// field[x][y].setTerrain();

Gdx.app.log("GameField::GameField()", "-- Set exitPoint: (" + x + ", " + y + ")");

}

}

} else {

Gdx.app.log("GameField::createField()", " -- Не смог преобразовать MapLayer в TiledMapTileLayer");

}

}

}

}

gridNav = new GridNav();

gridNav.loadCharMatrix(getCharMatrix());

}

}

public char[][] getCharMatrix() {

if(field != null) {

char[][] charMatrix = new char[sizeFieldY][sizeFieldX];

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

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

if(field[x][y].isTerrain() || field[x][y].getTower() != null) {

charMatrix[y][x] = 'T';

} else {

charMatrix[y][x] = '.';

}

// System.out.print(charMatrix[y][x]);

}

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

}

return charMatrix;

}

return null;

}

public void dispose() {

renderer.dispose();

renderer = null;

}

public void render(float delta, OrthographicCamera camera) {

renderer.setView(camera);

renderer.render();

if(!gamePaused) {

spawnCreep(delta);

stepAllCreep(delta);

attackCreeps(delta);

}

if(isDrawableGrid)

drawGrid(camera);

if(isDrawableCreeps)

drawCreeps(camera);

if(isDrawableTowers)

drawTowers(camera);

if(isDrawableRoutes)

drawRoutes(camera);

if(isDrawableGridNav)

drawGridNav(camera);

if(animation != null) {

stateTime += delta;

TextureRegion currentFrame = animation.getKeyFrame(stateTime, true); // #16

spriteBatch.begin();

spriteBatch.draw(currentFrame, 50, 300, 300, 300); // #17

// bitmapFont.draw(spriteBatch, getGamerGold(), Gdx.graphics.getWidth()/2-10, Gdx.graphics.getHeight())

// bitmapFont.draw(spriteBatch, String.valueOf(getGamerGold()), Gdx.graphics.getWidth()/2-10, Gdx.graphics.getHeight()-10);

spriteBatch.end();

}

}

private void drawGrid(OrthographicCamera camera) {

int widthForTop = sizeFieldY * (sizeCellX/2);

int heightForTop = sizeFieldY * (sizeCellY/2);

int widthForBottom = sizeFieldX * (sizeCellX/2);

int heightForBottom = sizeFieldX * (sizeCellY/2);

int halfSizeCellX = sizeCellX/2;

int halfSizeCellY = sizeCellY/2;

shapeRenderer.setProjectionMatrix(camera.combined);

shapeRenderer.begin(ShapeRenderer.ShapeType.Line);

shapeRenderer.setColor(Color.BROWN); // (100, 60, 21, 1f);

for(int x = 0; x <= sizeFieldX; x++)

shapeRenderer.line(x*halfSizeCellX, halfSizeCellY - x*halfSizeCellY, widthForTop + x*halfSizeCellX, halfSizeCellY + heightForTop - x*halfSizeCellY);

for(int y = 0; y <= sizeFieldY; y++)

shapeRenderer.line(y*halfSizeCellX, halfSizeCellY + y*halfSizeCellY, widthForBottom + y*halfSizeCellX, halfSizeCellY - heightForBottom + y*halfSizeCellY);

shapeRenderer.end();

}

private void drawCreeps(OrthographicCamera camera) {

int halfSizeCellX = sizeCellX / 2;

int halfSizeCellY = sizeCellY / 2;

// spriteBatch.setProjectionMatrix(camera.combined);

// spriteBatch.begin();

for(Creep creep: creepsManager.getAllCreeps()) {

int oldX = creep.getOldPosition().getX(), oldY = creep.getOldPosition().getY();

int newX = creep.getNewPosition().getX(), newY = creep.getNewPosition().getY();

float fVx = halfSizeCellX*newY + newX*halfSizeCellX;

float fVy = halfSizeCellY*newY - newX*halfSizeCellY;

float elapsedTime = creep.getElapsedTime(), speed = creep.getSpeed();

if(newX < oldX && newY > oldY) {

fVy -= (sizeCellY/speed)*(speed-elapsedTime);

} else if(newX == oldX && newY > oldY) {

fVx -= (sizeCellX/2/speed)*(speed-elapsedTime);

fVy -= (sizeCellY/2/speed)*(speed-elapsedTime);

} else if(newX > oldX && newY > oldY) {

fVx -= (sizeCellX/speed)*(speed-elapsedTime);

} else if(newX > oldX && newY == oldY) {

fVx -= (sizeCellX/2/speed)*(speed-elapsedTime);

fVy += (sizeCellY/2/speed)*(speed-elapsedTime);

} else if(newX > oldX && newY < oldY) {

fVy += (sizeCellY/speed)*(speed-elapsedTime);

} else if(newX == oldX && newY < oldY) {

fVx += (sizeCellX/2/speed)*(speed-elapsedTime);

fVy += (sizeCellY/2/speed)*(speed-elapsedTime);

} else if(newX < oldX && newY < oldY) {

fVx += (sizeCellX/speed)*(speed-elapsedTime);

} else if(newX < oldX && newY == oldY) {

fVx += (sizeCellX/2/speed)*(speed-elapsedTime);

fVy -= (sizeCellY/2/speed)*(speed-elapsedTime);

}

TextureRegion curentFrame = creep.getCurentFrame();

int deltaX = (curentFrame.getRegionWidth()-sizeCellX)/2;

int deltaY = (curentFrame.getRegionHeight()-sizeCellY)/2;

fVx -= deltaX;

fVy -= deltaY;

shapeRenderer.setProjectionMatrix(camera.combined);

shapeRenderer.begin(ShapeRenderer.ShapeType.Filled);

shapeRenderer.setColor(Color.BLACK);

float spaceInHpBar = 1;

float hpBarWidth = 30;

float hpBarHeight = 7;

float hpBarWidthSpace = (curentFrame.getRegionWidth()-hpBarWidth)/2;

float hpBarTopSpace = hpBarHeight;

shapeRenderer.rect(fVx + hpBarWidthSpace, fVy + curentFrame.getRegionHeight() - hpBarTopSpace, hpBarWidth, hpBarHeight);

shapeRenderer.setColor(Color.GREEN);

int maxHP = creep.getTemplateForUnit().healthPoints;

int hp = creep.getHp();

hpBarWidth = hpBarWidth/maxHP * hp;

shapeRenderer.rect(fVx + hpBarWidthSpace+spaceInHpBar, fVy + curentFrame.getRegionHeight() - hpBarTopSpace + spaceInHpBar, hpBarWidth - (spaceInHpBar*2), hpBarHeight - (spaceInHpBar*2));

// shapeRenderer.setColor(Color.BLUE); // (100, 60, 21, 1f);

// shapeRenderer.circle(fVx, fVy, 1);

shapeRenderer.end();

spriteBatch.setProjectionMatrix(camera.combined);

spriteBatch.begin();

spriteBatch.draw(curentFrame, fVx, fVy);

spriteBatch.end();

// Gdx.app.log("GameField::drawCreeps()", " -- x:" + x + " y:" + y + " x1:" + x1 + " y1:" + y1);

// Gdx.app.log("GameField::drawCreeps()", " -- sizeTexReg:" + creep.getCurentFrame().getRegionWidth() + "x" + creep.getCurentFrame().getRegionHeight());

}

// spriteBatch.end();

}

private void drawRoutes(OrthographicCamera camera) {

int halfSizeCellX = sizeCellX / 2;

int halfSizeCellY = sizeCellY / 2;

shapeRenderer.setProjectionMatrix(camera.combined);

shapeRenderer.begin(ShapeRenderer.ShapeType.Filled);

shapeRenderer.setColor(Color.BROWN); // (100, 60, 21, 1f);

for(Creep creep: creepsManager.getAllCreeps()) {

ArrayDeque<Vertex> route = creep.getRoute();

if(route != null) {

for(Vertex coor : route) {

int vX = coor.getX();

int vY = coor.getY()+1; // LibGDX some problems. Have offset (0,0) coor.

float fVx = halfSizeCellX * vY + vX * halfSizeCellX;

float fVy = halfSizeCellY * vY - vX * halfSizeCellY;

shapeRenderer.circle(fVx, fVy, 5);

}

}

}

shapeRenderer.end();

}

private void drawTowers(OrthographicCamera camera) {

int halfSizeCellX = sizeCellX / 2;

int halfSizeCellY = sizeCellY / 2;

spriteBatch.setProjectionMatrix(camera.combined);

spriteBatch.begin();

float fix = 1f;

for(Tower tower: towersManager.getAllTowers()) {

int x = tower.getPosition().x;

int y = tower.getPosition().y+1;

float x1 = halfSizeCellX*y + x*halfSizeCellX;

float y1 = halfSizeCellY*y - x*halfSizeCellY;

int towerSize = tower.getTemplateForTower().size;

TextureRegion curentFrame = tower.getCurentFrame();

float deltaX = (sizeCellX/2)*fix;//(sizeCellX*towerSize)/sizeCellX;

float deltaY = ((sizeCellY/2)*towerSize)*fix;

spriteBatch.draw(curentFrame, x1 - deltaX, y1 - deltaY, (sizeCellX * towerSize) * fix, ((sizeCellY*2)*towerSize)*fix);

// Gdx.app.log("GameField::drawCreeps()", " -- x:" + x + " y:" + y + " x1:" + x1 + " y1:" + y1);

// Gdx.app.log("GameField::drawCreeps()", " -- deltaX:" + deltaX + " deltaY:" + deltaY + " towerSize:" + towerSize);

// Gdx.app.log("GameField::drawCreeps()", " -- sizeTexReg:" + tower.getCurentFrame().getRegionWidth() + "x" + tower.getCurentFrame().getRegionHeight());

}

spriteBatch.end();

}

private void drawGridNav(OrthographicCamera camera) {

int halfSizeCellX = sizeCellX / 2;

int halfSizeCellY = sizeCellY / 2;

shapeRenderer.setProjectionMatrix(camera.combined);

shapeRenderer.begin(ShapeRenderer.ShapeType.Filled);

// shapeRenderer.setColor(Color.RED); // (100, 60, 21, 1f);

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

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

float fVx = halfSizeCellX * (y+1) + x * halfSizeCellX;

float fVy = halfSizeCellY * (y+1) - x * halfSizeCellY;

if(!field[x][y].isEmpty()) {

if(field[x][y].isTerrain()) {

shapeRenderer.setColor(Color.RED);

} else if(field[x][y].getCreep() != null) {

shapeRenderer.setColor(Color.GREEN);

} else if(field[x][y].getTower() != null) {

shapeRenderer.setColor(Color.BLACK);

}

shapeRenderer.circle(fVx, fVy, 3);

}

}

}

shapeRenderer.end();

}

public void setSpawnPoint(int x, int y) {

// spawnPoint = new GridPoint2(x, y);

waveManager.spawnPoints.set(0, new GridPoint2(x, y));

}

public void setExitPoint(int x, int y) {

// exitPoint = new GridPoint2(x, y);

waveManager.exitPoints.set(0, new GridPoint2(x, y));

rerouteForAllCreeps();

}

private void spawnCreep(float delta) {

Integer templateIndex = waveManager.getNextCreepTemplateIndexForSpawn(delta);

if(templateIndex != null) {

if(templateIndex >= 0) {

GridPoint2 spawnPoint = waveManager.spawnPoints.first();

if(spawnPoint != null) {

createCreep(spawnPoint.x, spawnPoint.y, factionsManager.getTemplateForUnitFromFirstFaction(templateIndex));

}

}

}

// elapsedTimeForSpawn += delta;

// if(elapsedTimeForSpawn > intervalForSpawnCreeps) {

// elapsedTimeForSpawn = 0f;

// if(creepsManager.amountCreeps() < defaultNumCreateCreeps) {

// if(spawnPoint != null) {

// createCreep(spawnPoint.x, spawnPoint.y);

// }

// }

// }

}

public void createCreep(int x, int y) {

createCreep(x, y, factionsManager.getRandomTemplateForUnitFromFirstFaction());

}

private void createCreep(int x, int y, TemplateForUnit templateForUnit) {

gridNav.loadCharMatrix(getCharMatrix());

ArrayDeque<Vertex> route = gridNav.route(x, y, waveManager.exitPoints.first().x, waveManager.exitPoints.first().y);

if(route != null) {

Creep creep = creepsManager.createCreep(route, templateForUnit);

field[x][y].setCreep(creep);

// Gdx.app.log("GameField::createCreep()", " -- x:" + x + " y:" + y + " eX:" + waveManager.exitPoints.first().x + " eY:" + waveManager.exitPoints.first().y);

// Gdx.app.log("GameField::createCreep()", " -- route:" + route);

}

}

public void towerActions(int x, int y) {

if(field[x][y].isEmpty()) {

createTower(x, y);

} else if(field[x][y].getTower() != null) {

removeTower(x, y);

}

}

public boolean createTower(int x, int y) {

TemplateForTower templateForTower = factionsManager.getCurrentTemplateTower();

if(gamerGold >= templateForTower.cost) {

int towerSize = templateForTower.size;

for (int tmpX = 0; tmpX < towerSize; tmpX++)

for (int tmpY = 0; tmpY < towerSize; tmpY++)

if (!field[tmpX + x][tmpY + y].isEmpty()) // HAVE BUGS! Can out of array!

return false;

GridPoint2 position = new GridPoint2(x, y);

Tower tower = towersManager.createTower(position, templateForTower);

for (int tmpX = 0; tmpX < towerSize; tmpX++)

for (int tmpY = 0; tmpY < towerSize; tmpY++)

field[tmpX + x][tmpY + y].setTower(tower);

rerouteForAllCreeps();

gamerGold -= templateForTower.cost;

Gdx.app.log("GameField::createTower()", " -- GamerGold:" + gamerGold);

return true;

} else {

return false;

}

}

public void removeTower(int touchX, int touchY) {

Tower tower = field[touchX][touchY].getTower();

if(tower != null) {

int x = tower.getPosition().x;

int y = tower.getPosition().y;

int towerSize = tower.getTemplateForTower().size;

for(int tmpX = 0; tmpX < towerSize; tmpX++) {

for(int tmpY = 0; tmpY < towerSize; tmpY++) {

field[x+tmpX][y+tmpY].removeTower();

}

}

towersManager.removeTower(tower);

rerouteForAllCreeps();

// gamerGold += (int) tower.getTemplateForTower().cost*0.5;

}

}

private void rerouteForAllCreeps() {

gridNav.loadCharMatrix(getCharMatrix());

for(Creep creep: creepsManager.getAllCreeps()) {

ArrayDeque<Vertex> route = gridNav.route(creep.getNewPosition().getX(), creep.getNewPosition().getY(), waveManager.exitPoints.first().x, waveManager.exitPoints.first().y);

if(route != null) {

route.removeFirst();

creep.setRoute(route);

}

}

}

private void stepAllCreep(float delta) {

for(int i=0; i<creepsManager.amountCreeps(); i++) {

Creep creep = creepsManager.getCreep(i);

Vertex oldPosition = creep.getNewPosition();

// field[oldPosition.getX()][oldPosition.getY()].removeCreep(creep);

// float elTime = creep.getElapsedReloadTime()+delta;

// if(elTime >= creep.getSpeed()) {

// creep.setElapsedReloadTime(0);

// stepOneCreep(creep);

// }

// else creep.setElapsedReloadTime(elTime);

Vertex newPosition = creep.move(delta);

if(newPosition != null) {

if(!newPosition.equals(oldPosition)) {

field[oldPosition.getX()][oldPosition.getY()].removeCreep(creep);

field[newPosition.getX()][newPosition.getY()].setCreep(creep);

// Gdx.app.log("GameField::stepAllCreep()", "-- Creep move to X:" + newPosition.getX() + " Y:" + newPosition.getY());

}

} else {

field[oldPosition.getX()][oldPosition.getY()].removeCreep(creep);

creepsManager.removeCreep(creep);

missedCreeps++;

// Gdx.app.log("GameField::stepAllCreep()", "-- Creep finished!");

}

}

}

private void attackCreeps(float delta) {

for(int i=0;i<towersManager.amountTowers();i++) {

Tower tower = towersManager.getTower(i);

float elTime = tower.getElapsedReloadTime()+delta;

if(elTime >= tower.getReloadTime()) {

tower.setElapsedReloadTime(0);

attackCreep(tower);

}

else tower.setElapsedReloadTime(elTime);

}

}

private void attackCreep(Tower tower) {

int radius = tower.getRadius();

for(int i=-radius;i<=radius;i++) {

for(int j=-radius;j<=radius;j++) {

GridPoint2 position = tower.getPosition();

if(field[position.x + i][position.y + j].getCreep() != null) {

Creep creep = field[position.x + i][position.y + j].getCreeps().first();

int hp = creep.getHp() - tower.getDamage();

if(hp <= 0) {

field[position.x+i][position.y+j].removeCreep(creep);

creepsManager.removeCreep(creep);

gamerGold += creep.getTemplateForUnit().bounty;

Gdx.app.log("Creep::attackCreep()", " -- ");

}

else {

creep.setHp(hp);

}

// Gdx.app.log("Creep healthPoints", creep.getHp()+"");

}

}

}

}

// public Array<TemplateForTower> getFirstTemplateForTowers() {

// factionsManager.ge

// }

// GAME INTERFACE ZONE1

public GridPoint2 whichCell(GridPoint2 gameCoordinate) {

return whichCell.whichCell(gameCoordinate);

}

public void setGamePause(boolean gamePaused) {

this.gamePaused = gamePaused;

}

public boolean getGamePaused() {

return gamePaused;

}

public int getNumberOfCreeps() {

return waveManager.getNumberOfCreeps() + creepsManager.amountCreeps();

}

public String getGameState() {

if(missedCreeps >= maxOfMissedCreeps) {

// Gdx.app.log("GameField::getGameState()", " -- LOSE!!");

return "Lose";

} else {

if(waveManager.getNumberOfCreeps() == 0 && creepsManager.amountCreeps() == 0) {

// Gdx.app.log("GameField::getGameState()", " -- WIN!!");

return "Win";

}

}

// Gdx.app.log("GameField::getGameState()", " -- IN PROGRESS!!");

return "In progress";

}

public int getGamerGold() {

return gamerGold;

}

// GAME INTERFACE ZONE2

}

WhichCell.java:

package com.betmansmall.game;

import com.badlogic.gdx.Gdx;

import com.badlogic.gdx.maps.tiled.TiledMapTile;

import com.badlogic.gdx.maps.tiled.TiledMapTileLayer;

import com.badlogic.gdx.math.GridPoint2;

import com.badlogic.gdx.math.Vector2;

import com.badlogic.gdx.math.Vector3;

import java.util.ArrayList;

/**

* Created by Андрей on 31.01.2016.

*/

public class WhichCell {

int sizeFieldX, sizeFieldY;

int sizeCellX, sizeCellY;

public WhichCell(int sizeFieldX, int sizeFieldY, int sizeCellX, int sizeCellY) {

this.sizeFieldX = sizeFieldX;

this.sizeFieldY = sizeFieldY;

this.sizeCellX = sizeCellX;

this.sizeCellY = sizeCellY;

}

public GridPoint2 whichCell(GridPoint2 gameCoordinate) {

int halfSizeCellX = sizeCellX/2;

int halfSizeCellY = sizeCellY/2;

for(int tileX = 0; tileX < sizeFieldX; tileX++) {

for(int tileY = 0; tileY < sizeFieldY; tileY++) {

float posX = (tileX*halfSizeCellX) + (tileY*halfSizeCellX);

float posY = -(tileX*halfSizeCellY) + (tileY*halfSizeCellY) + halfSizeCellY;

ArrayList<Vector2> tilePoints = new ArrayList<Vector2>();

tilePoints.add(new Vector2(posX, posY));

tilePoints.add(new Vector2(posX + halfSizeCellX, posY + halfSizeCellY));

tilePoints.add(new Vector2(posX + sizeCellX, posY));

tilePoints.add(new Vector2(posX + halfSizeCellX, posY - halfSizeCellY));

if(estimation(tilePoints, gameCoordinate)) {

return new GridPoint2(tileX, tileY);

}

}

}

return null;

}

private boolean estimation(ArrayList<Vector2> mapPoints, GridPoint2 touch) {

int res = 0;

for(int i = 0; i < mapPoints.size()-1; i++)

res += getDelta(mapPoints.get(i).x, mapPoints.get(i).y, mapPoints.get(i + 1).x, mapPoints.get(i + 1).y, touch);

res += getDelta(mapPoints.get(3).x,mapPoints.get(3).y, mapPoints.get(0).x, mapPoints.get(0).y, touch);

if(res == 0) {

return false;

} else return true;

}

private float getDelta(float q,float w, float e, float r, GridPoint2 touch) {

int j = getOktant(q - touch.x, touch.y - w);

int h = getOktant(e - touch.x, touch.y - r);

if((h - j) > 4)

return h-j - 8;

else if((h-j) < -4)

return h-j + 8;

else if((h-j) == 4 || (h-j) == -4) {

int f = correlation(q, w, e, r, touch);

if(f == 0)

Gdx.app.log("WhichCell::getDelta()", "-- Точка находится на границе полигона.");

return f;

}

return h-j;

}

private int correlation(float q, float w, float e, float r, GridPoint2 touch) {

float result = opredelitel(r, w, 1, 1)*touch.x + opredelitel(1, 1, e, q)*touch.y + opredelitel(w,q,r,e);

if(result == 0) {

return 0;

} else if(result < 0) {

return -4;

} else if(result > 0)

return 4;

return 0;

}

private int getOktant(float X, float Y) {

if(0 <= Y && Y < X)

return 1;

else if(0 < X && X <= Y)

return 2;

else if(-Y < X && X <= 0)

return 3;

else if(0 < Y && Y <= -X)

return 4;

else if(X < Y && Y <= 0)

return 5;

else if(Y <= X && X < 0)

return 6;

else if(0 <= X && X < -Y)

return 7;

else if(-X <= Y && Y < 0)

return 8;

return 0;

}

private float opredelitel(float x, float s, float t, float f) {

return x*f - s*t;

}

}

Размещено на Allbest.ru


Подобные документы

  • Разработка игрового проекта на игровом движке Unity 3D в среде программирования MS Visual Studio 2017. Блок-схема алгоритма работы приема сообщений с сервера на клиенте с упрощенным описанием выполняемых команд. Реализация пользовательского интерфейса.

    курсовая работа [1,5 M], добавлен 10.07.2017

  • Язык программирования Pascal и его турбооболочка. Аналитический обзор игрового программного обеспечения. Функции модуля Crt. Постановка задачи создания несложной игровой программы "Турбозмей", алгоритм реализации и описание пользовательского интерфейса.

    курсовая работа [100,4 K], добавлен 15.05.2014

  • Разработка программного продукта, предназначенного для имитации физического взаимодействия между объектами на основе игрового симулятора. Проектирование программы "LonelySpaceRanger", код которой представлен на языке VisualС++. Разработка интерфейса.

    дипломная работа [3,2 M], добавлен 30.11.2011

  • Разработка полноценной правильно функционирующей игровой программы "Парные картинки", изучение процедур и функций. Использование масштабируемых средств для построения баз данных. Компоненты Delphi в программе. Описание пользовательского интерфейса.

    курсовая работа [1,3 M], добавлен 13.07.2012

  • Комплексный подход в обеспечении информационной безопасности. Анализ процессов разработки, производства, реализации, эксплуатации средств защиты. Криптографические средства защиты информации. Основные принципы инженерно-технической защиты информации.

    курсовая работа [725,1 K], добавлен 11.04.2016

  • Разработка приложения на WinAPI с реализацией логической структуры в игре "Сапер". Реализация графической части приложения. Проверка на корректность поведения интерфейса программы, работы логической части игры, корректности записи и чтения файла.

    курсовая работа [1,1 M], добавлен 17.10.2012

  • Изучение правил проектирования (предоставление пользователю контроля над программой, уменьшение загрузки памяти, увеличение визуальной ясности, последовательность) и принципов разработки пользовательского интерфейса на примере программы "Tidy Start Menu".

    курсовая работа [286,6 K], добавлен 27.04.2010

  • Обзор системного и прикладного программного обеспечения используемого в ООО "Игровые системы". Описание компьютерной сети предприятия. Разработка игрового продукта для планшетов Apple iPad. Реализация визуального интерфейса и алгоритма работы модуля.

    отчет по практике [1,4 M], добавлен 18.01.2015

  • Анализ целевой аудитории. Функциональные характеристики пользовательского приложения. Разработка алгоритмов и интерфейса программного продукта, функций рабочей области. Написание скриптов на языке C#. Тестирование программы методом чёрного ящика.

    дипломная работа [1,5 M], добавлен 09.11.2016

  • Многообразие мини-игр и возможности языка Visual basic 6.0 для их реализации. Понятие мини-игр и их классификация. Элементы управления мини-игры "Реверси". Разработка прикладной программы. Создание игрового интерфейса. Написание программного кода.

    курсовая работа [1,5 M], добавлен 03.06.2014

Работы в архивах красиво оформлены согласно требованиям ВУЗов и содержат рисунки, диаграммы, формулы и т.д.
PPT, PPTX и PDF-файлы представлены только в архивах.
Рекомендуем скачать работу.