I'm unable to access a member from an object properly

  • (2 Pages)
  • +
  • 1
  • 2

18 Replies - 554 Views - Last Post: 06 December 2012 - 03:26 PM Rate Topic: -----

#1 Takwas  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 33
  • Joined: 05-September 12

I'm unable to access a member from an object properly

Posted 02 December 2012 - 05:56 PM

I'm trying to code a 2d game using the ACM library with which I've been learning Java.

The here are four classes:
1. GameBoard.java [creates a Game-Board template object, which I intend to use for other 2d games] (This is what is causing the problem)
2. Player.java (Actually this should I've been named Gun.java) [Creates an object that can shoot at the enemy];
3. Bullet.java [Creates a bullet object]
4. Invader.java [Creates an enemy object]
and
5. The main class "SpaceInvaders.java" that runs the applet;

So the code basically creates a 2d 'arcade' game in which the user shoots at enemies coming in the from the right.

I found out that my code does not allow the main class to communicate with the Game Board elements effectively.

For example a call to board.getPlayArea().getX() would return 0 instead of its new X position after after making the canvas larger and placing the board at the center of the canvas.
Hence, all board elements behave as if the board is placed at (0,0).

here are the code snippets for the different classes that manage to run the game:



Class 1:
    //SpaceInvaders.java
    //This is the main class that runs the Applet
	package space_game;
	
	import acm.program.*;
	import acm.graphics.*;
	import acm.util.*;
	
	import java.applet.AudioClip;
	import java.awt.Color;
	import java.awt.event.*;
	import java.util.ArrayList;
	
	public class SpaceInvaders extends GraphicsProgram{
	
		private static final int APP_WIDTH = 1100;
		private static final int APP_HEIGHT = 600;
		
		private static final int GAME_BOARD_WIDTH = 800;
		private static final int GAME_BOARD_HEIGHT = 400;
		
		
		private static final double BULLET_DIM = 3;
		private static final double PLAYER_WIDTH = 15;
		private static final double PLAYER_HEIGHT = 5;
		private static final double INVADER_WIDTH = 9;
		private static final double INVADER_HEIGHT = 12;
		private static final int PADDING = 5;
		
		
		private static final Color BG_COLOR = Color.WHITE;
		private static final Color BULLET_COLOR = Color.ORANGE;
		private static final Color PLAYER_COLOR = Color.GREEN;
		
		//private static final Color INVADER_COLOR = Color.LIGHT_GRAY;
		
		private GameBoard board;
		private GRect[] backGround;
		private GRect playArea;
		private Color[] boardCols;
		private Player player = new Player(PLAYER_WIDTH, PLAYER_HEIGHT,PLAYER_COLOR);
		private ArrayList<Bullet> bullet = new ArrayList<Bullet>();
		private Invader invader[];
		private int curBullet = 0;
		private double totalBullets = 0.0;
		private int level = 0;
		private double score = 0;
		private double speed;
		
		private Invader.Type type;
		private Bullet.Type bType;
		
		private RandomGenerator rgen = new RandomGenerator();
		private double yCord;
		private int invadersRemovalCount = 0;
		private int totalInvadersRemoved = 0;
		private boolean gamePaused;
		private boolean gameOver;
		
		private AudioClip coming;
		private AudioClip invaded;
		private AudioClip shoot;
		private AudioClip killed;
		
		public void init(){
			resize(APP_WIDTH, APP_HEIGHT);
			setBackground(BG_COLOR);
			
			addMouseListeners();
			
			backGround = new GRect[4];
			
			boardCols = new Color[4];
			boardCols[0] = Color.BLACK;
			boardCols[1] = Color.BLUE;
			boardCols[2] = Color.GRAY;
			boardCols[3] = Color.WHITE;
			
			speed = 0.3;
			bType = Bullet.Type.BALLER;
			
			coming = MediaTools.loadAudioClip("audio/CrayonRock.au");
			invaded = MediaTools.loadAudioClip("audio/OnTheHunt.au");
			shoot = MediaTools.loadAudioClip("audio/gun.au");
			killed = MediaTools.loadAudioClip("audio/tweeters.au");
			
			gamePaused = false;
			gameOver = false;
		}
		
		public void run(){
			
			setup();
			int scoreChecker;
			
			while(true){
				
				if(level_1()){
					type = Invader.Type.PAWN;
					bType = Bullet.Type.BALLER;
					scoreChecker = 1;
				}			
				else if(level_2()){
					type = Invader.Type.KNIGHT;
					bType = Bullet.Type.BALLER;
					speed = 0.2;
					scoreChecker = 2;
				}
				else if(level_3()){
					type = Invader.Type.QUEEN;
					bType = Bullet.Type.SNIPER;
					speed = 0.1;
					scoreChecker = 3;
				}
				else {
					coming.stop();
					coming = MediaTools.loadAudioClip("audio/BussaMove.au");
					coming.loop();
						break;
				}
				score *= scoreChecker;
				board.updateInfo(1, String.valueOf((int) score));
				
				createInvaders(new GPoint((playArea.getX()+playArea.getWidth())-PADDING, playArea.getY()+PADDING), playArea.getWidth(), playArea.getHeight()-PADDING, type, rgen.nextInt((int) (APP_HEIGHT*0.03), (int) (APP_HEIGHT*0.05)));
				
				board.updateInfo(2, String.valueOf(level+1).concat(" / 10"));
				
				invadersRemovalCount = 0;
				moveInvaders(invader);
				
				level++;
							
			}
			gameOver = true;
			reset();
	
		}
	
		private void setup(){
	
			board = new GameBoard(GAME_BOARD_WIDTH, GAME_BOARD_HEIGHT, boardCols ,">>>SP4C3 INV4D3RS<<<", PADDING, 13, "Invaders Exterminated: ", "Bullets Used: ");
			add(board, (getWidth()-board.getWidth())/2, (getHeight()-board.getHeight())/2);
			playArea = new GRect(board.getX(), board.getY()+(board.getHeight()*0.15), board.getWidth(), board.getPlayArea().getHeight());
			
			backGround[0] = new GRect(APP_WIDTH, APP_HEIGHT);
			backGround[0].setFilled(true);
			backGround[0].setColor(boardCols[2]);
			add(backGround[0], 0, 0);
			
			backGround[1] = new GRect(APP_WIDTH, APP_HEIGHT);
			backGround[1].setFilled(true);
			backGround[1].setColor(getBackground());
			add(backGround[1], 0, playArea.getY());
			
			backGround[2] = new GRect(APP_WIDTH, APP_HEIGHT);
			backGround[2].setFilled(true);
			backGround[2].setColor(boardCols[2]);
			add(backGround[2], 0, getYEnd(playArea));
	
			
			add(playArea);
			playArea.setVisible(false);
			playArea.addMouseMotionListener(this);
			board.sendToFront();
			
			add(player, board.getX()+PADDING, (playArea.getY()+(playArea.getHeight()*0.5)));
			
			backGround[3] = new GRect(0,0);
			backGround[3].setBounds(board.getPauseButton().getBounds());
			backGround[3].setLocation(playArea.getX()+((playArea.getWidth()-backGround[3].getWidth())/2), (playArea.getY()-((board.getStatusArea().getHeight()-backGround[3].getHeight())/2)-backGround[3].getHeight()));
			add(backGround[3]);
			//backGround[3].setVisible(false);
			           
			coming.loop();
			
		}
		
		private void createInvaders(GPoint pos, double wdt, double hgt, Invader.Type type, int numInvaders){
			invader = new Invader[numInvaders];
			for(int i=0; i<numInvaders; i++){
				invader[i] = new Invader(INVADER_WIDTH, INVADER_HEIGHT, type);
				add(invader[i], pos.getX()+rgen.nextDouble(0.0, wdt*0.25), pos.getY()+((hgt/numInvaders)*i));
				invader[i].setVisible(false);
			}
			
		}
		
		private void moveInvaders(Invader[] inv){
			int i ;
			while(true){
				if(gamePaused){
					board.changeState();
					waitForClick();
					board.changeState();
				}
				
				gamePaused = false;
				if (!bullet.isEmpty())
					for(int j=0; j<bullet.size(); j++){
						bullet.get(j).move(2, 0);
						
						if(collides(bullet.get(j), inv) || bullet.get(j).getX()>=getXEnd(playArea))
							remove(bullet.get(j));
				}
				
				if(invadersExited(inv, invadersRemovalCount)){
					invaded.play();	
						if(levelChanging()){
							reset();	
						}
					break;
				}
				
				for(i=0; i<inv.length; i++){
					inv[i].move(-1, 0);
					
					if(xIsInPlayArea(inv[i].getX(), inv[i].getWidth())){
						inv[i].setVisible(true);
					}
					
					if(!inv[i].isDead() && inv[i].getX()<=playArea.getX()){
						inv[i].changeState();
						remove(inv[i]);
	
						invadersRemovalCount++;
					}
					
				}
				
				pause(100*speed);
				animatebottomBar();
			}
			for(i=0; i<inv.length; i++){
				remove(inv[i]);
			}
			
		}
		private void animatebottomBar() {
			board.name.move(-1, 0);
			if(board.name.getX()<board.getPlayArea().getX())
				board.name.setLocation(getXEnd(board.getPlayArea()), board.name.getY());
		}
		
		
		private boolean levelChanging(){
			return (level==2||level==5||level==9);
		}
		
		private boolean collides(Bullet b, Invader[] inv){		
			
			for(int i =0; i<inv.length; i++){
				if(!inv[i].isDead() && (inv[i].contains(b.getX()+b.getWidth()*0.9, b.getY()+b.getHeight()) || inv[i].contains(b.getX()+b.getWidth()*0.9, b.getY()+b.getHeight()))){
					inv[i].hit();
					
					if(inv[i].maxHitReached()){
						inv[i].changeState();
						killed.play();
						
						remove(inv[i]);
						invadersRemovalCount++;
						
						totalInvadersRemoved++;
						score = ((totalInvadersRemoved/totalBullets)*1000);
						board.updateInfo(3, "Invaders Exterminated: "+totalInvadersRemoved);
						board.updateInfo(1, String.valueOf((int) score));
					}
					return true;
				}
			}	
			return false;
		}
		
		private boolean invadersExited(Invader[] inv, int count){
			return count == inv.length;
			
		}
		
	
		private boolean level_1(){
			return level<3;
		}
		
		private boolean level_2(){
			return level<6;
		}
		
		private boolean level_3(){
			return level<10;
		}
		
		public void keyPressed(KeyEvent k){
			if(k.getKeyCode() == KeyEvent.VK_ENTER)
				shoot();
			if(k.getKeyCode() == KeyEvent.VK_UP)
				player.move(0,-1);
			if(k.getKeyCode() == KeyEvent.VK_DOWN)
				player.move(0,1);
			
			shoot();
			showStatus("..."+k.getKeyCode());
		}
		
		public void mouseClicked(MouseEvent e){
			
			if(backGround[3].contains(e.getX(), e.getY())){
				
				gamePaused = true;
				//((GCompound) getElementAt(e.getX(), e.getY())).scale(50);
			}
		}
		
		public void mousePressed(MouseEvent e){
			if(!gameOver){
				shoot();
			}
		}
		
		public void mouseMoved(MouseEvent e){
		
			if(yIsInPlayArea(player.getY(), player.getHeight())){
				player.move(0, e.getY()-yCord);
				yCord = e.getY();
			}
			
			if(outUpwards(player.getY())){
				player.move(0, 2);
			}
			if(outDownwards(getYEnd(player))){
				player.move(0, -2);
			}		
			
		}
		
		public void mouseEntered(MouseEvent e){
			player.setLocation(player.getX(), e.getY());
		}
		
		private void shoot(){
			switch(bType){
			case SNIPER:
				bullet.add(new Bullet(BULLET_DIM,Color.WHITE, bType));
				break;
			default:
				bullet.add(new Bullet(BULLET_DIM,BULLET_COLOR, bType));
				break;
			}
			
			add(bullet.get(curBullet), player.getX()+player.getWidth(), player.getY());
			
			if(yIsInPlayArea((bullet.get(curBullet).getY()), bullet.get(curBullet).getHeight())){	
				shoot.play();
				curBullet++;
				totalBullets++;
				score = ((totalInvadersRemoved/totalBullets)*1000);
				board.updateInfo(4, "Bullets Used: ".concat(String.valueOf((int) totalBullets)));
				board.updateInfo(1, String.valueOf((int) score));
			}
	
			else{
				bullet.get(curBullet).sendToBack();
			}
				
		}
		
		private boolean xIsInPlayArea(double x, double wdt){
			return  (playArea.getX()<=x)&&((playArea.getX()+playArea.getWidth()>=x+wdt));
		}
		
		private boolean yIsInPlayArea(double y, double hgt){
			return  (playArea.getY()<=y)&&((playArea.getY()+playArea.getHeight()>=y+hgt));
		}
		
		private boolean outUpwards(double y){
			return playArea.getY()>y;
		}
	
		private boolean outDownwards(double y){
			return playArea.getY()+playArea.getHeight()<y;
		}
		
		private double getXEnd(GObject g){
			return g.getX()+g.getWidth();
		}
		
		private double getYEnd(GObject g){
			return (g.getY()+g.getHeight());
		}
		
		private void reset(){
			for(int j=0; j<bullet.size(); j++){
				remove(bullet.get(j));
			}
			bullet.clear();
			curBullet = 0;
			board.name.setLocation((board.getPlayArea().getX()+(board.getPlayArea().getWidth()-board.name.getWidth())/2), board.name.getY());
			
			showStatus("RESET CARRIED OUT!");
		}
	}



Class 2:
    //Player.java creates a shooting object [a Gun]
	package space_game;
	
	import acm.graphics.*;
	import java.awt.Color;
	
	public class Player extends GCompound{
	
		private GRect player;
		
		public Player(double wdt, double hgt, Color col1, Color col2){
			player = new GRect(wdt, hgt);
			player.setFilled(true);
			player.setColor(col1);
			player.setFillColor(col2);
			add(player, 0,0);
			
			player = new GRect(wdt*0.4, hgt*0.7);
			player.setFilled(true);
			player.setColor(col1);
			player.setFillColor(col2);
			add(player, 0,hgt);
			
			player = new GRect(wdt*0.2, hgt*0.5);
			player.setFilled(true);
			player.setColor(col1);
			player.setFillColor(col2);
			add(player, 0,hgt*1.7);
		}
		
		public Player(double wdt, double hgt, Color col){
			this(wdt, hgt, col, col);
		}
		
		public Player(double wdt, Color col){
			this(wdt,wdt,col);
		}
	}



Class 3:
//Bullet.java creates the bullet fired by the gun above
	package space_game;
	
	import acm.graphics.*;
	import java.awt.Color;
	
	public class Bullet extends GCompound{
	
		private GOval bullet;
		private GOval[] bulletArr = new GOval[4];
		private Type type;
		
		public Bullet(double dia, Color col){
			this(dia, col, col, Type.BALLER);
		}
		
		public Bullet(double dia, Color col, Type t){
			this(dia, col, col, t);
		}
		
		public Bullet(double dia, Color col1, Color col2, Type t){
			type = t;
			
			
			switch(type){
			case BALLER:
				bullet = new GOval(dia,dia);
				bullet.setFilled(true);
				bullet.setColor(col1);
				bullet.setFillColor(col2);
				add(bullet, 0 ,0);
				
				break;
			
			case SNIPER:
				
				dia*=2;
				for(int i = 0; i<4; i++){
					bulletArr[i] = new GOval(dia*((i+1)*(0.55)),dia*((i+1)*(0.2)));
					bulletArr[i].setFilled(true);
					bulletArr[i].setColor(col1);
					bulletArr[i].setFillColor(col2);
					
					switch(i){
					case 0:
						add(bulletArr[0], 0 ,0);
						break;
					default:
						add(bulletArr[i], bulletArr[i-1].getWidth()*0.9 , -bulletArr[i-1].getHeight()*0.5);
						break;
					}
					
				}
				break;
			}
		}
		
		public enum Type{
			BALLER, SNIPER
		} 
	}
//Bullet.java creates the bullet fired by the gun above
	package space_game;
	
	import acm.graphics.*;
	import java.awt.Color;
	
	public class Bullet extends GCompound{
	
		private GOval bullet;
		private GOval[] bulletArr = new GOval[4];
		private Type type;
		
		public Bullet(double dia, Color col){
			this(dia, col, col, Type.BALLER);
		}
		
		public Bullet(double dia, Color col, Type t){
			this(dia, col, col, t);
		}
		
		public Bullet(double dia, Color col1, Color col2, Type t){
			type = t;
			
			
			switch(type){
			case BALLER:
				bullet = new GOval(dia,dia);
				bullet.setFilled(true);
				bullet.setColor(col1);
				bullet.setFillColor(col2);
				add(bullet, 0 ,0);
				
				break;
			
			case SNIPER:
				
				dia*=2;
				for(int i = 0; i<4; i++){
					bulletArr[i] = new GOval(dia*((i+1)*(0.55)),dia*((i+1)*(0.2)));
					bulletArr[i].setFilled(true);
					bulletArr[i].setColor(col1);
					bulletArr[i].setFillColor(col2);
					
					switch(i){
					case 0:
						add(bulletArr[0], 0 ,0);
						break;
					default:
						add(bulletArr[i], bulletArr[i-1].getWidth()*0.9 , -bulletArr[i-1].getHeight()*0.5);
						break;
					}
					
				}
				break;
			}
		}
		
		public enum Type{
			BALLER, SNIPER
		} 
	}




Class 4:
//Invader.java creates an enemy object
	package space_game;
	
	import acm.graphics.*;
	import acm.util.ErrorException;
	
	import java.awt.Color;
	
	public class Invader extends GCompound{
	
		private GPolygon invader;
		private Color bodyColor;
		private Color skinColor;
		private int hits;
		private Type type;
		private State state;
		
		public Invader(double wdt, double hgt, Color col1, Type t){
			switch(t){
			case PAWN:
				type = Type.PAWN;
				bodyColor = Color.PINK;
				break;
			case KNIGHT:
				type = Type.KNIGHT;
				bodyColor = Color.MAGENTA;
				break;
			case QUEEN: 
				type = Type.QUEEN;
				bodyColor = Color.RED;
				wdt*=1.5;
				hgt*=1.5;
				break;
			default: throw new ErrorException("Invalid Type!");
			}
			
			hits = 0;
			state = State.ALIVE;
			skinColor = col1;
			invader = new GPolygon();
			
			invader.addVertex(-wdt, hgt*0.125);
			invader.addEdge(wdt*0.5, hgt*0.125);
			invader.addEdge(-wdt*0.5, hgt*0.125);
			invader.addEdge(wdt*0.5, hgt*0.125);
			invader.addEdge(-wdt*0.5, hgt*0.125);
			invader.addEdge(wdt*0.5, hgt*0.125);
			invader.addEdge(-wdt*0.5, hgt*0.125);
			invader.addEdge(wdt, hgt*0.125);
			invader.addVertex(0,0);
			
			
			invader.setFilled(true);
			invader.setColor(skinColor);
			invader.setFillColor(bodyColor);
			add(invader, 0,0);
		}
		
		public Invader(double wdt, double hgt, Type t){
			this(wdt, hgt, Color.BLACK, t);
		}
		
		public Invader(double wdt, Color col, Type t){
			this(wdt,wdt,Color.BLACK,t);
		}
		
		public void setType(Type t){
			
			switch(t){
			case PAWN:
				bodyColor = Color.PINK;
				type = Type.PAWN;
				break;
			case KNIGHT:
				bodyColor = Color.MAGENTA;
				type = Type.KNIGHT;
				break;
			case QUEEN: 
				bodyColor = Color.RED;
				type = Type.QUEEN;
				break;
			default: throw new ErrorException("Invalid Type!");
			}
		
		}
		
		public void hit(){
			this.hits++;
		}
	
		public int getHits(){
			return hits;
		}
		
		public boolean maxHitReached(){
			switch (this.type){
			case PAWN:
				return(this.hits==2);
			case KNIGHT:
				return(this.hits==4);
			case QUEEN:
				return(this.hits==4);
			default:
				return false;
			}
		}
		
		public void changeState(){
			if(state == State.ALIVE)
				state = State.DEAD;
			else{
				state = State.ALIVE;
			}
		}
		
		public boolean isDead(){
			return (state == State.DEAD);
		}
	
		public enum Type{
			PAWN, KNIGHT, QUEEN
		}
		
		public enum State{
			ALIVE, DEAD
		}
	}




Class 5:
    //GameBoard.java creates a game-board that can be used by other 2d 'arcade'
    //games
	package space_game;
	
	/**
	 * >>>[File: GameBoard.java]<<<
	 * [=======================]
	 * 
	 * Creates a Game-Board Template
	 * 
	 * [=======================]
	 * 
	 * This is an arcade-style-GameBoard Java class.
	 * The Game-Board objects created from here can
	 * be used by various game objects from other 
	 * classes
	 * 
	 * [================================================]
	 * 
	 * @author ac3Takwas
	 * 
	 */
	import acm.graphics.*;
	
	import java.awt.Color;
	
	public class GameBoard extends GCompound{
	
		/*Declaration of instance variables*/
	
		private GRect statusArea;
		private GRect pauseButton;
		private GRoundRect playArea;
		private GRoundRect bottom;
		public GLabel name;
		private GLabel scoreArea;
		private GLabel level;
		private GLabel info_1;
		private GLabel info_2;
		private GLabel pauseLabel;
		private int padding;
		
		
		
		/**
		 * Constructs a Game-Board given the listed parameters.
		 * @param width
		 * @param height
		 * @param col
		 * @param gameName
		 * @param padding
		 * @param statusFont
		 * @param info_1
		 * @param info_2
		 */
		public GameBoard(double width, double height, Color[] col, String gameName, int padding, int statusFont, String info_1, String info_2){
		
			playArea = new GRoundRect(width, height*0.75);
			statusArea = new GRect(playArea.getWidth()-(playArea.getArcWidth()*2), height*0.15);
			bottom = new GRoundRect(playArea.getWidth(), height*0.1);
			
			pauseLabel = new GLabel("PAUSE");
			this.padding = padding;
			createCanvas(height, col);
	
			addBoardElements(col, gameName, padding, statusFont, info_1, info_2);
			
			addPauseButton(col, width, padding, statusFont);
		}
	
		
		/**
		 * Creates the Game-Board canvas when called by a Constructor
		 * [========================================================]
		 * 
		 * @param hgt
		 * @param colorPack
		 */
		private void createCanvas(double hgt, Color[] colorPack){
			statusArea.setFilled(true);
			statusArea.setFillColor(colorPack[1]);
			statusArea.setColor(colorPack[0]);
			
			playArea.setFilled(true);
			playArea.setFillColor(colorPack[0]);
			playArea.setColor(colorPack[1]);
			
			bottom.setFilled(true);
			bottom.setFillColor(colorPack[1]);
			bottom.setColor(colorPack[0]);
			
			add(statusArea, playArea.getArcWidth(), 0);
	
			add(playArea, 0, hgt*0.15);
			
			add(bottom, 0, playArea.getY()+playArea.getHeight());
	
		}
			
		/**
		 * Adds the various screen elements to the already drawn canvas.
		 * For instance the element that displays the game score is created
		 * by this method
		 * [===============================================================]
		 * 
		 * @param colorPack
		 * @param gameName
		 * @param padding
		 * @param statusFont
		 * @param info_1
		 * @param info_2
		 */
		private void addBoardElements(Color colorPack[], String gameName, int padding, int statusFont, String info_1, String info_2) {
			addTopLevelElements(colorPack, padding, statusFont, info_1, info_2);
			
			addBottomLevelElements(colorPack, gameName);
					
		}
		
		/*Adds the Game-Board elements displayed at the top of the Playing-Area*/
		private void addTopLevelElements(Color[] colorPack, int padding, int statusFont, String info_1, String info_2) {
			scoreArea = new GLabel("SCORE: 0");
			scoreArea.setFont("Courier-BOLD-"+statusFont);
			scoreArea.setColor(colorPack[3]);
			add(scoreArea, ((statusArea.getY()+statusArea.getWidth())-((scoreArea.getWidth())+padding)), statusArea.getY()+padding+scoreArea.getAscent());
			
			level = new GLabel("LEVEL: 1");
			level.setFont("Courier-BOLD-"+statusFont);
			level.setColor(colorPack[3]);		
			add(level, ((statusArea.getY()+statusArea.getWidth())-((level.getWidth())+padding)), (statusArea.getY()+statusArea.getHeight())-(padding/2));
			
			if(info_1 != null){
				this.info_1 = new GLabel(""+info_1);
				this.info_1.setFont("Courier-BOLD-"+statusFont);
				this.info_1.setColor(colorPack[3]);
				add(this.info_1, (playArea.getArcWidth())+padding, statusArea.getY()+padding+this.info_1.getAscent());
			}
			
			if(info_2 != null){
				this.info_2 = new GLabel(""+info_2);
				this.info_2.setFont("Courier-BOLD-"+statusFont);
				this.info_2.setColor(colorPack[3]);
				add(this.info_2, (playArea.getArcWidth())+padding, (statusArea.getY()+statusArea.getHeight())-(padding/2));
			}
	
		}
	
		/*Adds the Game-Board elements displayed at the bottom of the Playing-Area*/
		private void addBottomLevelElements(Color[] colorPack, String gameName) {
			name = new GLabel(gameName);
			name.setFont("Courier-BOLD-15");
			name.setColor(colorPack[2]);
			
			add(name, (getWidth()-name.getWidth())/2, (bottom.getY()+bottom.getHeight())-bottom.getArcHeight());
	
			
		}
		
		
		/**
		 * Creates and adds the button that pauses and resumes the game
		 * [==========================================================]
		 * 
		 * @param col
		 * @param width
		 * @param padding
		 * @param statusFont
		 */
		private void addPauseButton(Color[] col, double width, int padding, int statusFont) {
			pauseLabel.setFont("Courier-BOLD-"+statusFont);
			pauseLabel.setColor(col[3]);
			
			pauseButton = 	new GRect(pauseLabel.getWidth()+padding*2, pauseLabel.getAscent()+padding*2);
			pauseButton.setFilled(true);
			pauseButton.setFillColor(col[2]);
			pauseButton.setColor(col[0]);
			add(pauseButton, (getWidth()-pauseButton.getWidth())/2, (statusArea.getHeight() - pauseButton.getHeight())/2);
			
			add(pauseLabel, pauseButton.getX()+padding, pauseButton.getY()+padding+pauseLabel.getAscent());
			
		}
		
		@Override
		public void repaint(){
			
		}
	
		public boolean isInPlayArea(GObject g){
			return  contains(playArea, g);
		}
		
		/**
		 * @param g1
		 * @param g2
		 * @return true if g1 contains g2
		 */
		private boolean contains(GObject g1, GObject g2){
			return  (g1.getY()<=g2.getY())&&((g1.getY()+g1.getHeight()>=g2.getY()+g2.getHeight())) 
					&&
					(g1.getX()<=g2.getX())&&((g1.getX()+g1.getWidth()>=g2.getX()+g2.getWidth()));
		}
		
		public boolean yIsInPlayArea(double y, double hgt){
			return  (this.playArea.getY()<=y)&&((this.playArea.getY()+this.playArea.getHeight()>=y+hgt));
		}
		
		public boolean xIsInPlayArea(double x, double wdt){
			return  (this.playArea.getX()<=x)&&((this.playArea.getX()+this.playArea.getWidth()>=x+wdt));
		}
		
		public boolean outUpwards(double y){
			return this.playArea.getY()>y;
		}
	
		public boolean outDownwards(double y){
			return this.playArea.getY()+this.playArea.getHeight()<y;
		}
		
		public GObject getPlayArea(){
			return this.playArea;
		}
		public GObject getPauseButton(){
			return this.pauseButton;
		}
		public GObject getStatusArea(){
			return this.statusArea;
		}
		
		public void changeState(){
			if(pauseLabel.getLabel().equalsIgnoreCase("Start")){
				pauseLabel.setLabel("PAUSE");
			}
			else{
				pauseLabel.setLabel("START");
			}
			
			repaint();
		}
		
		
		public void updateInfo(int index, String str){
			
			switch(index){
			case 1:
				scoreArea.setLabel("SCORE: "+str);
				scoreArea.setLocation((statusArea.getY()+statusArea.getWidth())-((scoreArea.getWidth())+padding), scoreArea.getY());
				break;
			case 2:
				level.setLabel("LEVEL: "+str);
				level.setLocation((statusArea.getY()+statusArea.getWidth())-((level.getWidth())+padding), level.getY());
				break;
			case 3:
				info_1.setLabel(""+str);
				break;
			default:
				info_2.setLabel(""+str);
				break;
			}
			
			repaint();
		}
		
		
	}


Is This A Good Question/Topic? 0
  • +

Replies To: I'm unable to access a member from an object properly

#2 jon.kiparsky  Icon User is offline

  • Pancakes!
  • member icon


Reputation: 7292
  • View blog
  • Posts: 12,100
  • Joined: 19-March 11

Re: I'm unable to access a member from an object properly

Posted 02 December 2012 - 06:02 PM

Not sure exactly what your question is. Is the problem with board.getPlayArea().getX()? If so, what's a GObject, and what does its getX() look like?
Was This Post Helpful? 0
  • +
  • -

#3 Takwas  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 33
  • Joined: 05-September 12

Re: I'm unable to access a member from an object properly

Posted 03 December 2012 - 02:09 AM

View Postjon.kiparsky, on 03 December 2012 - 02:02 AM, said:

Not sure exactly what your question is. Is the problem with board.getPlayArea().getX()? If so, what's a GObject, and what does its getX() look like?



A GObject is a Superclass of all objects in the ACM Library just like Object in Java. So, every GRect, GOval, GPolygon, GLabel for instance is a GObject.

Yes, my question is with board.getPlayArea().getX().

The getX() method returns the x-coordinate of its caller on the GraphicsProgram (class that runs the program) canvas.
As you can see from the program, the program works because I hard coded a new 'playArea' within the main class and also a new 'pauseButton' which is represented by 'backGround[3]' in the main class.

So if I were to make a call to " board.getPlayArea().getX() " on line 221 instead playArea.getX() which I have there.
Or a call to board.getPauseButton() on line 305 instead the call to background[3] which I have there, I wouldn't be able to pause the game.

Note: I won't be having any of these problems if I had the window resized to fit the board and have the board placed at (0,0).?


Also:
1. My keyPressed() doesn't work at all, so I can't control the game with my keyboard.
2. What does 163 do?
Was This Post Helpful? 0
  • +
  • -

#4 Sheph  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 432
  • View blog
  • Posts: 1,019
  • Joined: 12-October 11

Re: I'm unable to access a member from an object properly

Posted 03 December 2012 - 02:58 AM

You override repaint() (in GameBoard) with a blank method body, but you make calls to this method all over the place. What do you expect to happen? If things aren't getting repainted, maybe you are not seeing things as they are.

This post has been edited by Sheph: 03 December 2012 - 02:58 AM

Was This Post Helpful? 1
  • +
  • -

#5 Takwas  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 33
  • Joined: 05-September 12

Re: I'm unable to access a member from an object properly

Posted 03 December 2012 - 04:36 AM

View PostSheph, on 03 December 2012 - 10:58 AM, said:

You override repaint() (in GameBoard) with a blank method body, but you make calls to this method all over the place. What do you expect to happen? If things aren't getting repainted, maybe you are not seeing things as they are.


How do I use the repaint() method?
Was This Post Helpful? 0
  • +
  • -

#6 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8315
  • View blog
  • Posts: 31,836
  • Joined: 06-March 08

Re: I'm unable to access a member from an object properly

Posted 03 December 2012 - 04:42 AM

Just don't override it :)
Was This Post Helpful? 1
  • +
  • -

#7 g00se  Icon User is online

  • D.I.C Lover
  • member icon

Reputation: 2553
  • View blog
  • Posts: 10,637
  • Joined: 20-September 08

Re: I'm unable to access a member from an object properly

Posted 03 December 2012 - 05:44 AM

Quote

How do I use the repaint() method?
You call it when you want the component to be repainted
Was This Post Helpful? 0
  • +
  • -

#8 Takwas  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 33
  • Joined: 05-September 12

Re: I'm unable to access a member from an object properly

Posted 03 December 2012 - 06:58 AM

View Postg00se, on 03 December 2012 - 01:44 PM, said:

Quote

How do I use the repaint() method?
You call it when you want the component to be repainted


Yes I do want the labels on the screen like score and game level to be updated(repainted())

View Postpbl, on 03 December 2012 - 12:42 PM, said:

Just don't override it :)/>


I don't quite understand you. Is it bad to override a method that you need. I use it to update the score and other screen data as their values change.

Pls also try to answer the other questions I asked about line 163 and keyboard control from keyPressed() method.!
Was This Post Helpful? 0
  • +
  • -

#9 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8315
  • View blog
  • Posts: 31,836
  • Joined: 06-March 08

Re: I'm unable to access a member from an object properly

Posted 03 December 2012 - 03:06 PM

The repaint() method re-scghefuled in the good thread a call to the paint() method

If you don't want to rewrite all that code, at least in your version of repaint() call super.repaint();
Was This Post Helpful? 1
  • +
  • -

#10 Takwas  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 33
  • Joined: 05-September 12

Re: I'm unable to access a member from an object properly

Posted 04 December 2012 - 02:03 AM

View Postpbl, on 03 December 2012 - 11:06 PM, said:

The repaint() method re-scghefuled in the good thread a call to the paint() method

If you don't want to rewrite all that code, at least in your version of repaint() call super.repaint();


Do you mean something like pauseButton.repaint();?
Was This Post Helpful? 0
  • +
  • -

#11 Sheph  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 432
  • View blog
  • Posts: 1,019
  • Joined: 12-October 11

Re: I'm unable to access a member from an object properly

Posted 04 December 2012 - 02:18 AM

No, he means the repaint() method for a GUI component contains a bunch of code that makes sure paint() is called on the proper thread. When you override a method from a superclass (such as repaint), you are effectively saying, "Don't do what you normally do, do what I say". You want it to do what it normally does otherwise things won't get done properly, so either don't override it (remove the method from your class) or if you have to do something special, use super.repaint() within the method somewhere.
Was This Post Helpful? 2
  • +
  • -

#12 Takwas  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 33
  • Joined: 05-September 12

Re: I'm unable to access a member from an object properly

Posted 04 December 2012 - 03:03 AM

Now I get the drill. Thanks alot everyone.

I removed the overriden repaint() method and I've made no calls to it.
All the real-time data like score, enemies killed and level are still getting updated as normal. How is this happening? I thought one had to make a call to repaint() in other to have all these components change in real time.
Was This Post Helpful? 0
  • +
  • -

#13 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8315
  • View blog
  • Posts: 31,836
  • Joined: 06-March 08

Re: I'm unable to access a member from an object properly

Posted 04 December 2012 - 02:19 PM

When you modify a JComponent it calls repaint() itself
You only need tio call repaint() when you have customomized drawing to update
Was This Post Helpful? 1
  • +
  • -

#14 Takwas  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 33
  • Joined: 05-September 12

Re: I'm unable to access a member from an object properly

Posted 04 December 2012 - 05:41 PM

View Postpbl, on 04 December 2012 - 10:19 PM, said:

When you modify a JComponent it calls repaint() itself
You only need tio call repaint() when you have customomized drawing to update


I think I can say to a considerable extent, that I get a hang of things now.

Thanks pbl;
Thanks Sheph;
Thanks g00se;

BTW, here is a modified version of my code that allows me to access members of my GameBoard class and also control the game with a keyboard (a call to addKeyListeners() in my init() method was missing).




Modified Class: SpaceInvaders.java

package space_game;

import acm.program.*;
import acm.graphics.*;
import acm.util.*;

import java.applet.AudioClip;
import java.awt.Color;
import java.awt.event.*;
import java.util.ArrayList;

public class SpaceInvaders extends GraphicsProgram{

    private static final int APP_WIDTH = 1100;
    private static final int APP_HEIGHT = 600;

    private static final int GAME_BOARD_WIDTH = APP_WIDTH;
    private static final int GAME_BOARD_HEIGHT = APP_HEIGHT;


    private static final double BULLET_DIM = 2;
    private static final double PLAYER_WIDTH = 15;
    private static final double PLAYER_HEIGHT = 5;
    private static final double INVADER_WIDTH = 8;
    private static final double INVADER_HEIGHT = 12;
    private static final int PADDING = 5;


    private static final Color BG_COLOR = Color.WHITE;
    private static final Color BULLET_COLOR = Color.ORANGE;
    private static final Color PLAYER_COLOR = Color.GREEN;

    private static final Color[] INVADER_COLOR = {Color.PINK, Color.MAGENTA, Color.RED };

    private GameBoard board;
    private Color[] boardColorPack_1;
    private Color[] boardColorPack_2;
    private Gun gun;
    private ArrayList<Bullet> bullet = new ArrayList<Bullet>();
    private Invader invader[];
    private int curBullet;
    private double totalBullets;
    private int level;
    private double score ;
    private double speed;

    private Invader.Type invaderType;
    private Bullet.Type bulletType;

    private RandomGenerator rgen = new RandomGenerator();
    private double yCord;
    private int invadersRemovalCount = 0;
    private int totalInvadersRemoved = 0;
    private boolean gamePaused;
    private boolean gameOver;

    private AudioClip coming;
    private AudioClip invaded;
    private AudioClip shoot;
    private AudioClip killed;

    public void init(){
        resize(APP_WIDTH, APP_HEIGHT);
        setBackground(BG_COLOR);

        addMouseListeners();
        addKeyListeners();

        
        boardColorPack_2 = new Color[4];
        boardColorPack_2[0] = Color.BLACK;
        boardColorPack_2[1] = Color.BLUE;
        boardColorPack_2[2] = Color.WHITE;
        boardColorPack_2[3] = Color.GRAY;
        
        boardColorPack_1 = new Color[2];
        boardColorPack_1[0] = Color.GRAY;
        boardColorPack_1[1] = Color.WHITE;

        curBullet = 0;
        totalBullets = 0.0;
        level = 0;
        score = 0;
        speed = 0.3;
        bulletType = Bullet.Type.BALLER;

        coming = MediaTools.loadAudioClip("audio/CrayonRock.au");
        invaded = MediaTools.loadAudioClip("audio/OnTheHunt.au");
        shoot = MediaTools.loadAudioClip("audio/gun.au");
        killed = MediaTools.loadAudioClip("audio/tweeters.au");

        gamePaused = false;
        gameOver = false;
    }

    public void run(){

        setup();
        int scoreChecker;

        while(true){

            if(level_1()){
                invaderType = Invader.Type.PAWN;
                bulletType = Bullet.Type.BALLER;
                scoreChecker = 1;
            }           
            else if(level_2()){
                invaderType = Invader.Type.KNIGHT;
                bulletType = Bullet.Type.BALLER;
                speed = 0.2;
                scoreChecker = 2;
            }
            else if(level_3()){
                invaderType = Invader.Type.QUEEN;
                bulletType = Bullet.Type.SNIPER;
                speed = 0.05;
                scoreChecker = 3;
            }
            else {
                coming.stop();
                coming = MediaTools.loadAudioClip("audio/BussaMove.au");
                coming.loop();
                    break;
            }
            
            score *= scoreChecker;
            board.updateInfo(1, String.valueOf((int) score));

            createInvaders(new GPoint(getXEnd(board.getPlayArea())-PADDING, board.getPlayArea().getY()+PADDING), board.getPlayArea().getWidth(), board.getPlayArea().getHeight()-PADDING, invaderType, rgen.nextInt((int) (APP_HEIGHT*0.03), (int) (APP_HEIGHT*0.05)));

            board.updateInfo(2, String.valueOf(level+1).concat(" / 10"));

            invadersRemovalCount = 0;
            moveInvaders(invader);

            level++;

        }
        gameOver = true;
        reset();

    }

    private void setup(){

        board = new GameBoard(GAME_BOARD_WIDTH, GAME_BOARD_HEIGHT, boardColorPack_1, boardColorPack_2 ,">>>SP4C3 INV4D3RS<<<", PADDING, 13, "Invaders Exterminated: ", "Bullets Used: ");
        add(board, (getWidth()-board.getWidth())/2, (getHeight()-board.getHeight())/2);

        gun = new Gun(PLAYER_WIDTH, PLAYER_HEIGHT,PLAYER_COLOR);
        add(gun, board.getPlayArea().getX()+PADDING, (board.getPlayArea().getY()+(board.getPlayArea().getHeight()*0.5)));

        coming.loop();

    }

    private void createInvaders(GPoint pos, double wdt, double hgt, Invader.Type invaderType, int numInvaders){
        invader = new Invader[numInvaders];
        for(int i=0; i<numInvaders; i++){
            invader[i] = new Invader(INVADER_WIDTH, INVADER_HEIGHT, INVADER_COLOR, invaderType);
            add(invader[i], pos.getX()+rgen.nextDouble(0.0, wdt*0.25), pos.getY()+((hgt/numInvaders)*i));
            invader[i].setVisible(false);
        }

    }

    private void moveInvaders(Invader[] inv){
        int i ;
        while(true){
        	if(outUpwards(gun.getY())){
                gun.setLocation(gun.getX(), board.getPlayArea().getY()+PADDING);
            }
            if(outDownwards(getYEnd(gun))){
            	gun.setLocation(gun.getX(), getYEnd(board.getPlayArea())-(gun.getHeight()+PADDING));
            }
            
            if(gamePaused){
                board.changeState();
                waitForClick();
                board.changeState();
            }

            gamePaused = false;
            if (!bullet.isEmpty())
                for(int j=0; j<bullet.size(); j++){
                    bullet.get(j).move(2, 0);

                    if(collides(bullet.get(j), inv) || bullet.get(j).getX()>=getXEnd(board.getPlayArea()))
                        remove(bullet.get(j));
            }

            if(invadersExited(inv, invadersRemovalCount)){
                invaded.play(); 
                    if(levelChanging()){
                        reset();    
                    }
                break;
            }

            for(i=0; i<inv.length; i++){
                inv[i].move(-1, 0);

                if(xIsInPlayArea(inv[i].getX(), inv[i].getWidth())){
                    inv[i].setVisible(true);
                }

                if(!inv[i].isDead() && inv[i].getX()<=board.getPlayArea().getX()){
                    inv[i].changeState();
                    remove(inv[i]);

                    invadersRemovalCount++;
                }

            }

            pause(100*speed);
            animatebottomBar();
        }
        for(i=0; i<inv.length; i++){
            remove(inv[i]);
        }

    }
    private void animatebottomBar() {
        board.name.move(-1, 0);
        if(board.name.getX()<board.getPlayArea().getX())
            board.name.setLocation(getXEnd(board.getPlayArea()), board.name.getY());
    }


    private boolean levelChanging(){
        return (level==2||level==5||level==9);
    }

    private boolean collides(Bullet b, Invader[] inv){      

        for(int i =0; i<inv.length; i++){
            if(!inv[i].isDead() && !b.equals(inv[i].getPreviousHit()) && (inv[i].contains(getXEnd(B)/>*0.9, getYEnd(B)/>) || inv[i].contains(getXEnd(B)/>*0.9, getYEnd(B)/>))){
                inv[i].hit();
                inv[i].hasBeenHitBy(B)/>;

                if(inv[i].maxHitsReached()){
                    inv[i].changeState();
                    killed.play();

                    remove(inv[i]);
                    invadersRemovalCount++;

                    totalInvadersRemoved++;
                    score = ((totalInvadersRemoved/totalBullets)*1000);
                    board.updateInfo(3, "Invaders Exterminated: "+totalInvadersRemoved);
                    board.updateInfo(1, String.valueOf((int) score));
                }
                return true;
            }
        }   
        return false;
    }

    private boolean invadersExited(Invader[] inv, int count){
        return count == inv.length;

    }


    private boolean level_1(){
        return level<3;
    }

    private boolean level_2(){
        return level<6;
    }

    private boolean level_3(){
        return level<10;
    }

    public void keyPressed(KeyEvent k){
    	if(yIsInPlayArea(gun.getY(), gun.getHeight()))
	        switch(k.getKeyCode()){
	        case KeyEvent.VK_ENTER:
	            shoot();
	            break;
	        case KeyEvent.VK_UP:
	            gun.move(0,-4);
	            break;
	        case KeyEvent.VK_DOWN:
	            gun.move(0,4);
	            break;
	        case KeyEvent.VK_W:
	            gun.move(0,-4);
	            break;
		    case KeyEvent.VK_A:
		        gun.move(0,4);
		        break;
		        
		        default:
		        	break;
		    }
    	
    }

    public void mouseClicked(MouseEvent e){

        if(board.getPauseButton().contains(e.getX(), e.getY()))
            gamePaused = true;
    }

    public void mousePressed(MouseEvent e){
        if(!gameOver){
            shoot();
        }
    }

    public void mouseMoved(MouseEvent e){

        if(yIsInPlayArea(gun.getY(), gun.getHeight())){
            gun.move(0, e.getY()-yCord);
            yCord = e.getY();
        }       

    }

    public void mouseEntered(MouseEvent e){
        gun.setLocation(gun.getX(), e.getY());
    }

    private void shoot(){
        switch(bulletType){
        case SNIPER:
            bullet.add(new Bullet(BULLET_DIM,Color.WHITE, bulletType));
            break;
        default:
            bullet.add(new Bullet(BULLET_DIM,BULLET_COLOR, bulletType));
            break;
        }

        add(bullet.get(curBullet), gun.getX()+gun.getWidth(), gun.getY());

        if(yIsInPlayArea((bullet.get(curBullet).getY()), bullet.get(curBullet).getHeight())){   
            shoot.play();
            curBullet++;
            totalBullets++;
            score = ((totalInvadersRemoved/totalBullets)*1000);
            board.updateInfo(4, "Bullets Used: ".concat(String.valueOf((int) totalBullets)));
            board.updateInfo(1, String.valueOf((int) score));
        }

        else{
            bullet.get(curBullet).sendToBack();
        }

    }

    private boolean xIsInPlayArea(double x, double wdt){
        return  (board.getPlayArea().getX()<=x)&&((board.getPlayArea().getX()+board.getPlayArea().getWidth()>=x+wdt));
    }

    private boolean yIsInPlayArea(double y, double hgt){
        return  (board.getPlayArea().getY()<=y)&&((board.getPlayArea().getY()+board.getPlayArea().getHeight()>=y+hgt));
    }

    private boolean outUpwards(double y){
        return board.getPlayArea().getY()>y;
    }

    private boolean outDownwards(double y){
        return board.getPlayArea().getY()+board.getPlayArea().getHeight()<y;
    }

    private double getXEnd(GObject g){
        return g.getX()+g.getWidth();
    }

    private double getYEnd(GObject g){
        return (g.getY()+g.getHeight());
    }

    private void reset(){
        for(int j=0; j<bullet.size(); j++){
            remove(bullet.get(j));
        }
        bullet.clear();
        curBullet = 0;
        board.name.setLocation((board.getPlayArea().getX()+(board.getPlayArea().getWidth()-board.name.getWidth())/2), board.name.getY());

        showStatus("RESET CARRIED OUT!");
    }
}









Modified Class: GameBoard.java

package space_game;

import acm.graphics.*;

import java.awt.Color;

public class GameBoard extends GCompound{

	private GCompound canvas;
	private GRect[] canvasRect = new GRect[3];
	private GRect statusArea;
	private GRect pauseButton;
	private GRoundRect playArea;
	private GRoundRect bottom;
	public GLabel name;
	private GLabel scoreArea;
	private GLabel levelArea;
	private GLabel info_1;
	private GLabel info_2;
	private GLabel pauseLabel;
	private int padding;
	
	public GameBoard(double width, double height, Color[] colorPack_1, Color[] colorPack_2, String gameName, int padding, int statusFont, String info_1, String info_2){
		canvas = new GCompound();
		
		this.padding = padding;
		
		createCanvas(width, height, colorPack_1);
		createPlayRegion(width *0.7, height*0.6, colorPack_2);
		
		addBoardElements(colorPack_2, gameName, padding, statusFont, info_1, info_2);
		
		addPauseButton(colorPack_2, width, padding, statusFont);
	}
	
	private void createCanvas(double width, double height, Color[] colorPack_2) {
		canvasRect[0] = new GRect(0,0, width, height*0.2 );

		canvasRect[1] = new GRect(0,height*0.2, width, height*0.6 );

		canvasRect[2] = new GRect( 0,height*0.8, width, height*0.2);

		for(int i=0; i<canvasRect.length; i++){
			canvasRect[i].setFilled(true);
			canvasRect[i].setFillColor(colorPack_2[i%2]);
			canvasRect[i].setColor(colorPack_2[i%2]);
			canvas.add(canvasRect[i]);
		}
		
		add(canvas);
	}
	
	private void createPlayRegion(double width, double height, Color colorPack_2[]){
		playArea = new GRoundRect(width, canvasRect[1].getHeight());
		statusArea = new GRect(playArea.getWidth()-(playArea.getArcWidth()*2), height*0.20);
		bottom = new GRoundRect(playArea.getWidth(), height*0.15);
		
		statusArea.setFilled(true);
		statusArea.setFillColor(colorPack_2[1]);
		statusArea.setColor(colorPack_2[0]);
		
		playArea.setFilled(true);
		playArea.setFillColor(colorPack_2[0]);
		playArea.setColor(colorPack_2[1]);
		
		bottom.setFilled(true);
		bottom.setFillColor(colorPack_2[1]);
		bottom.setColor(colorPack_2[0]);
		
		add(playArea, ((this.getWidth()-width)/2), canvasRect[1].getY());
		add(statusArea, playArea.getX()+playArea.getArcWidth(), playArea.getY()-(statusArea.getHeight()));
		add(bottom, playArea.getX(), getYEnd(playArea));
	}
	
	private void addBoardElements(Color colorPack_2[], String gameName, int padding, int statusFont, String info_1, String info_2) {
		addTopLevelElements(colorPack_2, padding, statusFont, info_1, info_2);
		
		addBottomLevelElements(gameName);			
	}
	
	private void addTopLevelElements(Color[] colorPack_2, int padding, int statusFont, String info_1, String info_2) {
		scoreArea = new GLabel("SCORE: 0");
		scoreArea.setFont("Courier-BOLD-"+statusFont);
		scoreArea.setColor(colorPack_2[2]);
		add(scoreArea, (getXEnd(statusArea)-(scoreArea.getWidth()+padding)), statusArea.getY()+padding+scoreArea.getAscent());
		
		levelArea = new GLabel("LEVEL: 1");
		levelArea.setFont("Courier-BOLD-"+statusFont);
		levelArea.setColor(colorPack_2[2]);		
		add(levelArea, (getXEnd(statusArea)-(levelArea.getWidth()+padding)), (getYEnd(statusArea)-(padding)));
		
		if(info_1 != null){
			this.info_1 = new GLabel(""+info_1);
			this.info_1.setFont("Courier-BOLD-"+statusFont);
			this.info_1.setColor(colorPack_2[2]);
			add(this.info_1, (statusArea.getX()+padding), statusArea.getY()+padding+this.info_1.getAscent());
		}
		
		if(info_2 != null){
			this.info_2 = new GLabel(""+info_2);
			this.info_2.setFont("Courier-BOLD-"+statusFont);
			this.info_2.setColor(colorPack_2[2]);
			add(this.info_2, (statusArea.getX()+padding), (getYEnd(statusArea)-padding));
		}
	}

	private void addBottomLevelElements(String gameName) {
		name = new GLabel(gameName);
		name.setFont("Courier-BOLD-15");
		name.setColor(canvasRect[2].getFillColor());
		
		add(name, (bottom.getX()+((bottom.getWidth()-name.getWidth())/2)), getYEnd(bottom)-padding);	
	}
	
	private void addPauseButton(Color[] col, double width, int padding, int statusFont) {
		pauseLabel = new GLabel("PAUSE");
		pauseLabel.setFont("Courier-BOLD-"+statusFont);
		pauseLabel.setColor(statusArea.getFillColor());
		
		pauseButton = new GRect(pauseLabel.getWidth()+padding*2, pauseLabel.getAscent()+padding*2);
		pauseButton.setFilled(true);
		pauseButton.setFillColor(col[2]);
		pauseButton.setColor(col[0]);
		add(pauseButton, (statusArea.getX()+(statusArea.getWidth()-pauseButton.getWidth())/2), statusArea.getY()+(statusArea.getHeight() - pauseButton.getHeight())/2);
		
		add(pauseLabel, pauseButton.getX()+padding, pauseButton.getY()+padding+pauseLabel.getAscent());
		
	}
	
	private double getXEnd(GObject g){
        return g.getX()+g.getWidth();
    }

    private double getYEnd(GObject g){
        return (g.getY()+g.getHeight());
    }

	public boolean isInPlayArea(double x, double wdt, double y, double hgt){
		return  (this.playArea.getY()<=y)&&((this.playArea.getY()+this.playArea.getHeight()>=y+hgt)) 
				&&
				(this.playArea.getX()<=x)&&((this.playArea.getX()+this.playArea.getWidth()>=x+wdt));
	}
	
	public boolean yIsInPlayArea(double y, double hgt){
		return  (this.playArea.getY()<=y)&&((this.playArea.getY()+this.playArea.getHeight()>=y+hgt));
	}
	
	public boolean xIsInPlayArea(double x, double wdt){
		return  (this.playArea.getX()<=x)&&((this.playArea.getX()+this.playArea.getWidth()>=x+wdt));
	}
	
	public boolean outUpwards(double y){
		return this.playArea.getY()>y;
	}

	public boolean outDownwards(double y){
		return this.playArea.getY()+this.playArea.getHeight()<y;
	}
	
	public GObject getPlayArea(){
		return this.playArea;
	}
	public GObject getPauseButton(){
		return this.pauseButton;
	}
	public GObject getStatusArea(){
		return this.statusArea;
	}
	
	public void changeState(){
		if(pauseLabel.getLabel().equalsIgnoreCase("Resume")){
			pauseLabel.setLabel("PAUSE");
		}
		else{
			pauseLabel.setLabel("RESUME");
			
		}
		
		pauseLabel.setLocation(statusArea.getX()+((statusArea.getWidth()-pauseLabel.getWidth())/2), pauseLabel.getY());
		pauseButton.setBounds(pauseLabel.getX()-padding, pauseLabel.getY()-(pauseLabel.getAscent()+padding), (pauseLabel.getWidth()+(padding*2)), (pauseLabel.getAscent()+(padding*2)));

	}
	
	
	public void updateInfo(int index, String str){
		
		switch(index){
		case 1:
			scoreArea.setLabel("SCORE: "+str);
			scoreArea.setLocation((statusArea.getY()+statusArea.getWidth())-((scoreArea.getWidth())+padding), scoreArea.getY());
			break;
		case 2:
			levelArea.setLabel("LEVEL: "+str);
			levelArea.setLocation((statusArea.getY()+statusArea.getWidth())-((levelArea.getWidth())+padding), levelArea.getY());
			break;
		case 3:
			info_1.setLabel(""+str);
			break;
		default:
			info_2.setLabel(""+str);
			break;
		}
	}
	
	
}








Modified Class: Gun.java

package space_game;

import acm.graphics.*;
import java.awt.Color;

public class Gun extends GCompound{

	private GRect gunSegment[] = new GRect[3];
	
	public Gun(double wdt, double hgt, Color col1, Color col2){
		gunSegment[0] = new GRect(wdt, hgt);
		gunSegment[0].setFilled(true);
		gunSegment[0].setColor(col1);
		gunSegment[0].setFillColor(col2);
		add(gunSegment[0], 0,0);
		
		gunSegment[1] = new GRect(wdt*0.4, hgt*0.7);
		gunSegment[1].setFilled(true);
		gunSegment[1].setColor(col1);
		gunSegment[1].setFillColor(col2);
		add(gunSegment[1], 0,hgt);
		
		gunSegment[2] = new GRect(wdt*0.2, hgt*0.5);
		gunSegment[2].setFilled(true);
		gunSegment[2].setColor(col1);
		gunSegment[2].setFillColor(col2);
		add(gunSegment[2], 0,hgt*1.7);
	}
	
	public Gun(double wdt, double hgt, Color col){
		this(wdt, hgt, col, col);
	}
	
	public Gun(double wdt, Color col){
		this(wdt,wdt,col);
	}
}









Modified Class: Invaders.java

package space_game;

import acm.graphics.*;
import acm.util.ErrorException;

import java.awt.Color;

public class Invader extends GCompound{

	private GPolygon invaderBody;
	private Color[] typeBodyColor;
	private Color[] typeSkinColor;
	private Color bodyColor;
	private Color skinColor;
	private int hits;
	private int maxHits;
	private State state;
	private Bullet bullet;
	
	public Invader(double wdt, double hgt, Color[] col1, Color[] col2, Type t){
		switch(t){
		case PAWN:
			bodyColor = col1[0];
			skinColor = col2[0];
			maxHits = 1;
			break;
		case KNIGHT:
			bodyColor = col1[1];
			skinColor = col2[1];
			maxHits = 3;
			wdt*=1.2;
			hgt*=1.2;
			break;
		case QUEEN: 
			bodyColor = col1[2];
			skinColor = col2[2];
			maxHits = 2;
			wdt*=1.5;
			hgt*=1.5;
			break;
		default: throw new ErrorException("Invalid Type!");
		}
		
		hits = 0;
		state = State.ALIVE;
		typeBodyColor = col1;
		typeSkinColor = col2;
		
		invaderBody = new GPolygon();
		
		
		invaderBody.addVertex(-wdt, hgt*0.125);
		invaderBody.addEdge(wdt*0.5, hgt*0.125);
		invaderBody.addEdge(-wdt*0.5, hgt*0.125);
		invaderBody.addEdge(wdt*0.5, hgt*0.125);
		invaderBody.addEdge(-wdt*0.5, hgt*0.125);
		invaderBody.addEdge(wdt*0.5, hgt*0.125);
		invaderBody.addEdge(-wdt*0.5, hgt*0.125);
		invaderBody.addEdge(wdt, hgt*0.125);
		invaderBody.addVertex(0,0);
		
		
		invaderBody.setFilled(true);
		invaderBody.setColor(skinColor);
		invaderBody.setFillColor(bodyColor);
		add(invaderBody, 0,0);
	}
	
	public Invader(double wdt, double hgt, Color[] col, Type t){
		this(wdt, hgt, col, col, t);
	}
	
	public Invader(double wdt, Color col[], Type t){
		this(wdt,wdt,col,t);
	}
	
	public void setType(Type t){
		
		switch(t){
		case PAWN:
			bodyColor = typeBodyColor[0];
			skinColor = typeSkinColor[0];
			hits = 0;
			maxHits = 1;
			break;
		case KNIGHT:
			bodyColor = typeBodyColor[1];
			skinColor = typeSkinColor[1];
			hits = 0;
			maxHits = 3;
			break;
		case QUEEN: 
			bodyColor = typeBodyColor[2];
			skinColor = typeSkinColor[2];
			hits = 0;
			maxHits = 2;
			break;
		default: throw new ErrorException("Invalid Type!");
		}
	
	}
	
	public void hit(){
		this.hits++;
	}

	public int getHits(){
		return hits;
	}
	
	public boolean maxHitsReached(){
		return (hits >= maxHits);
	}
	
	public void changeState(){
		if(state == State.ALIVE)
			state = State.DEAD;
		else{
			state = State.ALIVE;
		}
	}
	
	public boolean isDead(){
		return (state == State.DEAD);
	}
	
	public Bullet getPreviousHit(){
		if(hits>0)
			return bullet;
		else{
			return null;		
		}
	}
	
	public void hasBeenHitBy(Bullet B)/>{
		bullet = b;
	}

	public enum Type{
		PAWN, KNIGHT, QUEEN
	}
	
	public enum State{
		ALIVE, DEAD
	}
}









Modified Class: Bullet.java

package space_game;

import acm.graphics.*;
import java.awt.Color;

public class Bullet extends GCompound{

	private GOval bulletBody;							//creates the basic baller-type bullet
	private GOval[] bulletSegment = new GOval[4];		//each variable represents a segment of the SNIPER bullet
	private Type type;
	
	public Bullet(double dia, Color col){
		this(dia, col, col, Type.BALLER);
	}
	
	public Bullet(double dia, Color col, Type t){
		this(dia, col, col, t);
	}
	
	public Bullet(double dia, Color col1, Color col2, Type t){
		type = t;
		
		
		switch(type){
		case BALLER:
			bulletBody = new GOval(dia,dia);
			bulletBody.setFilled(true);
			bulletBody.setColor(col1);
			bulletBody.setFillColor(col2);
			add(bulletBody, 0 ,0);
			
			break;
		
		case SNIPER:
			
			dia*=2;
			for(int i = 0; i<4; i++){
				bulletSegment[i] = new GOval(dia*((i+1)*(0.55)),dia*((i+1)*(0.2)));
				bulletSegment[i].setFilled(true);
				bulletSegment[i].setColor(col1);
				bulletSegment[i].setFillColor(col2);
				
				switch(i){
				case 0:
					add(bulletSegment[0], 0 ,0);
					break;
				default:
					add(bulletSegment[i], bulletSegment[i-1].getWidth()*0.9 , -bulletSegment[i-1].getHeight()*0.5);
					break;
				}
				
			}
			break;
		}
	}
	
	public enum Type{
		BALLER, SNIPER
	} 
}



Was This Post Helpful? 0
  • +
  • -

#15 Takwas  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 33
  • Joined: 05-September 12

Re: I'm unable to access a member from an object properly

Posted 06 December 2012 - 01:41 AM

If you were to run this game, you would find out that as the levels get
increased, the game speed gets slower instead
of the contrary. I've looked at my code but
nothing seems to be wrong with it. Could it be a
problem with my CPU or an increased number
of computations.
Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2