+1 (315) 557-6473 

Create A Program to Animate a Game Map View in Java Assignment Solution.


Instructions

Objective
Write a program to create a game map view in java language.

Requirements and Specifications

  1. Introduction
  2. The purpose of this assignment is to help you gain experience with interactive graphics and animation techniques such as repainting, timer-driven animation, collision detection, and object selection. Specifically, you are to make the following modifications to your game:

    • the game world map is to display in the GUI (in addition to the text form on the console),
    • the movement (animation) of game objects is to be driven by a timer,
    •  the game is to support dynamic collision detection and response,
    • the game is to support simple interactive editing of some of the objects in the world, and
    •  the game is to include sounds appropriate to collisions and other events.
  3. Game World Map
If you did Assignment2 (A2) properly, your program included an instance of a MapView class which is an observer that displayed the game elements on the console. MapView also extended Container and it was placed in the middle of the game form, although it was empty.
For this assignment, MapView will display the contents of the game graphically in the container in the middle of the game screen (in addition to displaying it in the text form on the console). When the MapView update() is invoked, it should now also should call repaint() on itself. As described in the course notes, MapView should override paint(), which will be invoked as a result of calling repaint(). It is then the duty of paint() to iterate through the game objects invoking draw() in each object – thus redrawing all the objects in the world in the container. Note that paint() must have access to the GameWorld.
That means that the reference to the GameWorld must be saved when MapView is constructed, or alternatively the update() method must save it prior to calling repaint().
Note that the modified MapView class communicates with the rest of the program exactly as it did previously (e.g., it is an observer of GameWorld)
Source Code
GAME
package com.mycompany.a2;
import com.codename1.charts.util.ColorUtil;
import com.codename1.ui.*;
import com.codename1.ui.layouts.BorderLayout;
import com.codename1.ui.layouts.BoxLayout;
import com.codename1.ui.layouts.FlowLayout;
import com.codename1.ui.plaf.Border;
import com.codename1.ui.util.UITimer;
//import com.mycompany.a2.commands.*;
//import com.mycompany.a2.controllers.MapView;
//import com.mycompany.a2.controllers.ScoreView;
public class Game extends Form implements Runnable
{
 //Declaration of variables
 private GameWorld gw;
 private ScoreView sv;
 private MapView mv;
 //private boolean isQuit = false;
 private UITimer timer;
 public Game()
 {
  gw = new GameWorld();
  sv = new ScoreView(gw);
  mv = new MapView(gw);
  timer = UITimer.timer(1000, true, this, this);
  Toolbar toolbar = new Toolbar();
  this.setToolbar(toolbar);
  toolbar.setTitle("FlagByFlag Game");
  toolbar.getAllStyles().setBackgroundGradientEndColor(ColorUtil.WHITE);
  // Creating West Container
  Container westContainer = new Container();
  westContainer.getAllStyles().setBorder(Border.createLineBorder(4, ColorUtil.GRAY));
  westContainer.setLayout(new BoxLayout(2));
  // Creating East Container
  Container eastContainer = new Container();
  eastContainer.getAllStyles().setBorder(Border.createLineBorder(4, ColorUtil.GRAY));
  eastContainer.setLayout(new BoxLayout(2));
  // Creating South Container
  Container southContainer = new Container();
  southContainer.getAllStyles().setBorder(Border.createLineBorder(4, ColorUtil.GRAY));
  southContainer.setLayout(new FlowLayout(Component.CENTER));
  // Commands
  Command accelerateCommand = new Accelerate(gw);
  Command brakeCommand = new Brake(gw);
  Command leftCommand = new Left(gw);
  Command rightCommand = new Right(gw);
  Command eneryStationCollisionCommand = new FoodStationCollision(gw);
  Command droneCollisionCommand = new SpiderCollision(gw);
  Command tickCommand = new ClockTick(gw);
  Command exitCommand = new Exit(gw);
  Command baseCommand = new FlagCollision(gw);
  // Key listerners which execute king binding mechanism
  addKeyListener('a', accelerateCommand);
  addKeyListener('b', brakeCommand);
  addKeyListener('l', leftCommand);
  addKeyListener('r', rightCommand);
  addKeyListener('e', eneryStationCollisionCommand);
  addKeyListener('g', droneCollisionCommand);
  addKeyListener('t', tickCommand);
  addKeyListener('x', exitCommand);
  Button accelerateButton = new Button("Accelerate");// Acclerate button creation
  accelerateButton.setCommand(accelerateCommand);
  westContainer.addComponent(accelerateButton);
  accelerateButton.getAllStyles().setFgColor(ColorUtil.WHITE);
  accelerateButton.getAllStyles().setBgColor(ColorUtil.BLUE);
  accelerateButton.getAllStyles().setBgTransparency(255);
  accelerateButton.getAllStyles().setMarginBottom(0);
  accelerateButton.setWidth(2);
  Button leftButton = new Button("Left"); // Left button creation
  leftButton.setCommand(leftCommand);
  westContainer.addComponent(leftButton);
  leftButton.getAllStyles().setFgColor(ColorUtil.WHITE);
  leftButton.getAllStyles().setBgColor(ColorUtil.BLUE);
  leftButton.getAllStyles().setBgTransparency(255);
  leftButton.getAllStyles().setMarginBottom(0);
// Button changeStategy = new Button("Change Startgies"); //Change Startgies
// westContainer.addComponent(changeStategy);
// changeStategy.getAllStyles().setFgColor(ColorUtil.WHITE);
// changeStategy.getAllStyles().setBgColor(ColorUtil.BLUE);
// changeStategy.getAllStyles().setBgTransparency(255);
// changeStategy.getAllStyles().setMarginBottom(10);
  Button brakeButton = new Button("Brake");// Break button creation
  brakeButton.setCommand(brakeCommand);
  eastContainer.addComponent(brakeButton);
  brakeButton.getAllStyles().setFgColor(ColorUtil.WHITE);
  brakeButton.getAllStyles().setBgColor(ColorUtil.BLUE);
  brakeButton.getAllStyles().setBgTransparency(255);
  brakeButton.getAllStyles().setMarginBottom(0);
  Button rightButton = new Button("Right");// Right button declaration
  rightButton.setCommand(rightCommand);
  eastContainer.addComponent(rightButton);
  rightButton.getAllStyles().setFgColor(ColorUtil.WHITE);
  rightButton.getAllStyles().setBgColor(ColorUtil.BLUE);
  rightButton.getAllStyles().setBgTransparency(255);
  rightButton.getAllStyles().setMarginBottom(0);
  Button baseButton = new Button("Collide with Flag");// Flag button collision creation
  southContainer.add(baseButton);
  baseButton.setWidth(2);
  baseButton.setCommand(baseCommand);
  baseButton.getAllStyles().setFgColor(ColorUtil.WHITE);
  baseButton.getAllStyles().setBgColor(ColorUtil.BLUE);
  baseButton.getAllStyles().setBgTransparency(255);
  baseButton.getAllStyles().setMarginRight(2);
  Button foodButton = new Button("Collide with Food Station");// Energy Station button collision
  southContainer.add(foodButton);
  foodButton.setCommand(eneryStationCollisionCommand);
  foodButton.getAllStyles().setFgColor(ColorUtil.WHITE);
  foodButton.getAllStyles().setBgColor(ColorUtil.BLUE);
  foodButton.getAllStyles().setBgTransparency(255);
  foodButton.getAllStyles().setMarginRight(2);
  Button spiderButton = new Button("Collide with Spider");// spider collision button creation
  southContainer.addComponent(spiderButton);
  spiderButton.setCommand(droneCollisionCommand);
  spiderButton.getAllStyles().setFgColor(ColorUtil.WHITE);
  spiderButton.getAllStyles().setBgColor(ColorUtil.BLUE);
  spiderButton.getAllStyles().setBgTransparency(255);
  Button tickButton = new Button("Tick");// tick command button creation
  tickButton.setCommand(tickCommand);
  southContainer.add(tickButton);
  tickButton.getAllStyles().setFgColor(ColorUtil.WHITE);
  tickButton.getAllStyles().setBgColor(ColorUtil.BLUE);
  tickButton.getAllStyles().setBgTransparency(255);
  toolbar.addCommandToSideMenu(accelerateCommand);
  Command soundCommand = new Sound(gw);
  CheckBox soundCheck = new CheckBox();
  toolbar.addComponentToSideMenu(soundCheck);
  soundCheck.setCommand(soundCommand);
  Command aboutInfoCommand = new About(gw);
  toolbar.addCommandToSideMenu(aboutInfoCommand);
  Command helpButton = new Help(gw);
  toolbar.addCommandToRightBar(helpButton);
  toolbar.addCommandToSideMenu(exitCommand);
  this.setLayout(new BorderLayout());
  this.add(BorderLayout.WEST, westContainer);
  this.add(BorderLayout.EAST, eastContainer);
  this.add(BorderLayout.SOUTH, southContainer);
  this.add(BorderLayout.NORTH, sv);
  this.add(BorderLayout.CENTER, mv);
  gw.setMapHeight(mv.getComponentForm().getHeight());
  gw.setMapWidth(mv.getComponentForm().getWidth());
  gw.init();
  this.show();
 }
 @Override
 public void run() {
  if (gw.getEnergyLevel() < 0 || gw.getLivesLeft() <= 0) {
   timer.cancel();
  }
  gw.clockTick();
 }
}
GAME OBJECT
package com.mycompany.a2;
import com.codename1.charts.util.ColorUtil;
import com.codename1.ui.Font;
import com.codename1.ui.Graphics;
import com.codename1.ui.geom.Point;
public class GameObject implements IDrawable {
 public static int SIZE_COEFF = 8;
 public static final Font FONT = Font.createTrueTypeFont("native:MainBlack", 6);
 private int size = 0; // All game objects have an integer attribute size.
 private double xlocation = 0.0;// All games objects have location and initial location of objects is set to 0,0
         // for both x and y
 private double ylocation = 0.0;// " " " "
 private int color = ColorUtil.rgb(141, 179, 226);// All game objects have color defined as integer
 // Declaration of setter and getter methods
 public void setSize(int size) {
  this.size = size;
 }
 public int getSize() // All game objects can obtain the size but they cannot change the size.
 {
  return size;
 }
 public void setXlocation(double xlocation)// All game objects have x and y location and intial location is at 0.0,
            // and 0.0
 {
  this.xlocation = xlocation;
 }
 public double getXlocation() {
  return xlocation;
 }
 public void setYlocation(double ylocation)// Intial location is set to zero because we want objects are at center in
            // the world
 {
  this.ylocation = ylocation;
 }
 public double getYlocation() {
  return ylocation;
 }
 public void setColor(int color)// All the game objects have color defined as integer
 {
  this.color = color;
 }
 public int getColor() {
  return color;
 }
 // Location and color can be changed however size does not have ability to get
 // changed once it is created.
 public String toString() // Display method
 {
  String myDesc = " loc=" + Math.round(xlocation * 10.0) / 10.0 + "," + Math.round(ylocation * 10.0) / 10.0
    + " color=[" + ColorUtil.red(color) + "," + ColorUtil.green(color) + "," + ColorUtil.blue(color) + "]"
    + " size=" + this.getSize();
  return myDesc;
 }
 @Override
 public void draw(Graphics g, Point pCmpRelPrnt) {
  // TODO Auto-generated method stub
 }
 protected void drawString(Graphics g, String s, int x, int y) {
  int width = 0;
  for (char c : s.toCharArray()) {
   width += FONT.charWidth(c);
  }
  g.drawString(s, x - width / 2, y - FONT.getHeight() / 2);
 }
}
GAME WORLD
package com.mycompany.a2;
//import java.util.ArrayList;
import com.codename1.charts.util.ColorUtil;
//import com.mycompany.a2.Abstract.MovableObject;
//import com.mycompany.a2.Interfaces.IIterator;
//import com.mycompany.a2.controllers.PlayerAnt;
//import com.mycompany.a2.models.Bases;
//import com.mycompany.a2.models.FoodStations;
//import com.mycompany.a2.models.Spiders;
import java.util.Observable;
import java.util.Random;
public class GameWorld extends Observable {// Game world is defined as an observable
 private int lives = 3;
 private int clock = 0;
 // private ArrayList list = new ArrayList(); // Array
 // list to store Game Object
 private PlayerAnt ant;
 Random rand = new Random();
 private int lastBase = 4;
 private boolean soundChecked = false;
 private GameObjectCollection list;
 private int mapHeight;
 private int mapWidth;
 public GameWorld() {
  list = new GameObjectCollection();
  ant = new PlayerAnt(625.0, 465.0);
 }
 public void init() {
  // list = new GameObjectCollection();
  // list.clear();
  // ants.reset();
  addBases();// Calling the base to add four Bases to the Game World
  addAnts();// Adding the Ants to game world
  addFoodStations();// Adding the Food to the game world
  addSpiders();// Adding the Spiders to the game World
  this.setChanged();
  this.notifyObservers();
 }
 public void addBases() {
  list.add(new Bases(281.0, 533.0, 1));// Creating Bases, and all bases should be assigned to locations chosen by
           // user.
  list.add(new Bases(1221.0, 249.0, 2));
  list.add(new Bases(741.0, 897.0, 3));
  list.add(new Bases(1477.0, 665.0, 4));
 }
 public void addAnts() {
  list.add(ant);
 }
 public void addFoodStations() {
  list.add(new FoodStations(577, 237, 15));
  list.add(new FoodStations(1281, 1069, 20));
 }
 public void addSpiders() {
  list.add(new Spiders(233.0, 873.0, randomSpeed(), randomSize(), randomHeading()));
  list.add(new Spiders(1041.0, 493.0, randomSpeed(), randomSize(), randomHeading()));
 }
 public double randomX()// Generating the random number between 0 and 1024
 {
  int randomNum = rand.nextInt(1738);
  return randomNum;
 }
 public double randomY()// Generating the random number between 0 and 768
 {
  int randomNum = rand.nextInt(1298);
  return randomNum;
 }
 public int randomSize()// Generating the random number between 10 and 50
 {
  int randomNum = rand.nextInt(20 + 1) + 5;
  return randomNum;
 }
 public int randomSpeed()// Generating the random number between 5 and 10
 {
  int randomNum = rand.nextInt((10 - 5) + 1) + 5;
  return randomNum;
 }
 public int randomHeading()// Generating the random number between 0 and 359
 {
  int randomNum = rand.nextInt((359 - 0) + 1) + 0;
  return randomNum;
 }
 public void accelerate() // This method increase the speed player robots
 {
  int speedIncrease = 2;
  ant.setAntSpeed(ant.getSpeed() + speedIncrease);
  this.setChanged();
  this.notifyObservers();
  System.out.println("The speed has been increased by 2 successfully");
 }
 public void brake()// This method decrease the speed of robot
 {
  int speedDecrease = 2;
  ant.setAntSpeed(ant.getSpeed() - speedDecrease);
  this.setChanged();
  this.notifyObservers();
  System.out.println("The speed has been Decrease by 2 successfully");
 }
 public void left()// This method turns the robot left
 {
  int leftChange = -5;
  ant.steeringHeading(leftChange);
  this.setChanged();
  this.notifyObservers();
  System.out.println("Ant has been turned left successfully");
 }
 public void right()// This method turns the robot right
 {
  int rightChange = 5;
  ant.steeringHeading(rightChange);
  this.setChanged();
  this.notifyObservers();
  System.out.println("Ant has been turned right successfully");
 }
 public void FlagCollision(int x)// This method anytime user enter # between 1-9 we run the functions after robot
         // has been collided with Base
 {
  System.out.println("Colliding with Flag " + x);
  if ((x - ant.getLastBasereached() == 1)) {
   ant.setLastBaseReached(x);
  }
  this.setChanged();
  this.notifyObservers();
 }
 public void FoodStationsCollision()// This method execute the commands when user pretend that robots has been
          // collided with base station
 {
  GameObject energyStation = new GameObject();
  IIterator theElements = list.getIterator();
  while (theElements.hasNext()) {
   GameObject f = (GameObject) theElements.getNext();
   {
    if (f instanceof FoodStations) {
     if (((FoodStations) f).getCapacity() != 0) {
      energyStation = f;
     }
    }
   }
  }
  // After the collision, Robots energy level is increased, capactiy is set to 0
  // and color is changed to light green
  ant.setEnergyLevel(ant.getEnergyLevel() + ((FoodStations) energyStation).getCapacity());
  ((FoodStations) energyStation).setCapacity(0);
  ((FoodStations) energyStation).setColor(ColorUtil.rgb(0, 120, 0));
  list.add(new FoodStations(randomX(), randomY(), randomSize()));
  this.setChanged();
  this.notifyObservers();
  System.out.println(" Ant has collided with Food Station");
 }
 public void SpiderCollision()// This method execute the commands after the collision of drones
 {
  ant.collisionOfSpiders();
  this.setChanged();
  this.notifyObservers();
  System.out.println("Ant and Spider have collided");
 }
 public void clockTick() {
  clock++;
  IIterator theElements = list.getIterator();
  while (theElements.hasNext()) {
   GameObject f = (GameObject) theElements.getNext();
   if (f instanceof Spiders) {
    ((Spiders) f).randomHeading();
   }
   if (f instanceof MovableObject) {
    ((MovableObject) f).move();
   }
  }
  ant.reduceEnergy();// Robots energy level is reduced by the amount indicated by its
       // energyConsumptionRate
  if (ant.getLastBasereached() == lastBase) {
   System.out.println("Game Over, You win! Total time: " + this.clock);
  }
  if (ant.getIsDead()) {
   lives = lives - 1;
   if (lives == 0) {
    System.out.println("Game Over, you failed");
    System.exit(0);
   } else
    System.out.print("Robot has died");
   this.init();
  }
  this.setChanged();
  this.notifyObservers();
  System.out.println(" Clock has been ticked successfully");
 }
 public void display() {
  System.out.println("\nNumber of lives left is: " + lives);
  System.out.println("Current value of clock is: " + clock);
  System.out.println("The highest base number reached is: " + ant.getLastBasereached());
  System.out.println("Energy level of Ant is: " + ant.getEnergyLevel());
  System.out.println("Ant Current Damage level is: " + ant.getDamageLevel());
 }
 public String isSound()// sound function which is invoked from the side menu
 {
  if (this.soundChecked) {
   return " ON";
  } else {
   return " OFF";
  }
 }
 public void toggleSound() {
  this.soundChecked = !(this.soundChecked);
  this.setChanged();
  this.notifyObservers();
 }
 public void map() {
  System.out.println();
  IIterator theElements = list.getIterator();
  while (theElements.hasNext()) {
   GameObject g = (GameObject) theElements.getNext();
   System.out.println(g.toString());
  }
 }
 public int getLivesLeft() {
  return lives;
 }
 public int getClock() {
  return clock;
 }
 public int getAntLastBaseReached() {
  return ant.getLastBasereached();
 }
 public int getEnergyLevel() {
  return ant.getEnergyLevel();
 }
 public int getDamageLevel() {
  return ant.getDamageLevel();
 }
 public void setMapHeight(int height) {
  this.mapHeight = height;
  System.out.println("" + height);
 }
 public void setMapWidth(int width) {
  this.mapWidth = width;
 }
 public GameObjectCollection getObjects() {
  return list;
 }
 public void exit() {
  System.exit(0);
 }
}
MAP VIEW
package com.mycompany.a2;
import com.codename1.charts.util.ColorUtil;
import com.codename1.ui.Container;
import com.codename1.ui.Graphics;
import com.codename1.ui.geom.Point;
import com.codename1.ui.plaf.Border;
import com.mycompany.a2.GameObjectCollection.Iterator;
import com.mycompany.a2.GameWorld;
import java.util.Observable;
import java.util.Observer;
public class MapView extends Container implements Observer // Mapview implemets observer
{
 private GameWorld model;
 public MapView(Observable myModel) {
  model = (GameWorld) myModel;
  myModel.addObserver(this);
  this.getAllStyles().setBorder(Border.createLineBorder(4, ColorUtil.rgb(255, 0, 0)));// Creating the red line
                       // border around the
                       // container
 }
 @Override
 public void update(Observable observable, Object data) {
  repaint();
 }
 @Override
 public void paint(Graphics g) {
  IIterator iter = model.getObjects().getIterator();
  while(iter.hasNext()) {
   GameObject go = (GameObject)iter.getNext();
   go.draw(g, new Point(getX(), getY()));
  }
 }
}