block collision issues on a 2D map tiled java - java

I'm having problems with wall collision. Basically I want my player to stop whenever it collides with a block.
Here's what I did so far:
Keylistener set up:
addKeyListener(new KeyAdapter(){
public void keyPressed(KeyEvent e){
if(e.getKeyCode() == KeyEvent.VK_A){
pressL = true;
}
if(e.getKeyCode() == KeyEvent.VK_D){
pressR = true;
}
if(e.getKeyCode() == KeyEvent.VK_W){
pressU = true;
}
if(e.getKeyCode() == KeyEvent.VK_S){
pressD = true;
}
}
public void keyReleased(KeyEvent e){
if(e.getKeyCode() == KeyEvent.VK_A){
pressL = false;
}
if(e.getKeyCode() == KeyEvent.VK_D){
pressR = false;
}
if(e.getKeyCode() == KeyEvent.VK_W){
pressU = false;
}
if(e.getKeyCode() == KeyEvent.VK_S){
pressD = false;
}
}
public void keyTyped(KeyEvent e){
}
});
Player's movement:
public void playerMovement(){
player.horizontalMovement(0);
player.verticalMovement(0)
map.horizontalMovement(0);
map.verticalMovement(0);
if(pressR && !pressL && !pressU && !pressD){
if(!east){
toggleRight();
}
if(collision("east"))
east = true;
}
if(pressL && !pressR && !pressD && !pressU){
if(!west)
toggleLeft();
if(collision("west"))
west = true;
}
if(pressD && !pressU && !pressR && !pressL){
if(!south)
toggleDown();
if(collision("south"))
south = true;
}
if(pressU && !pressD && !pressL && !pressR){
if(!north)
toggleUp();
if(collision("north"))
north = true;
}
}
Here's where the collision test is:
public boolean collision(String loc){
Rectangle pR = player.getBound();
Rectangle pM = map.getBound(0, 0);
if(loc.equals("east")){
if(pR.equals(pM)){
if(west)
return false;
if(!west)
return true;
} west = false; south = false;north = false;
}
if(loc.equals("west"))
if(pR.intersects(pM)){
if(east)
return false;
if(!east)
return true;
} east = false; south = false;north = false;
}
if(loc.equals("south")){
if(pR.intersects(pM)){
if(north)
return false;
if(!north)
return true;
} north = false; west = false;east = false;
}
if(loc.equals("north")){
if(pR.intersects(pM)){
if(south)
return false;
if(!south)
return true;
} south = false; west = false;east = false;
}
return false;
}
I set up my code likes this to avoid being stuck whenever I collide with a block I'm testing with. It works but there are a lot of bugs I'm encountering. One example is sometimes I get stuck, or the player can pass through the block with pressing the vertical with the horizontal keys. I'm having problems figuring out the proper algorithm for this. And by the way the direction is based on the viewer's direction not the player's.
Can someone share with me a descent way of do it? Thanks.

For player and walls (blocks) create Shapes (e.g. Polygon can be used). The use Shape's methods
public boolean intersects(double x, double y, double w, double h);
public boolean intersects(Rectangle2D r);
Or you can create Areas from the Shapes and use
public void intersect(Area rhs)

Related

Prevent Array List Overlap?

I am creating a Binding of Isaac-esque Roguelike that is generated using an Array List using four Booleans. The four Booleans being North, East, South, and West. Corresponding to which doors is open.
The problem with Array Lists is that it can 'overlap'. For example, if I go east, than south, than west, than north, I'll be in a whole new room, and not the original.
Is there a way to stop this from happening, or at least prevent it? Such as if the room above room 1 (room 2) has south set to true, than north will be true in room 1 to connect the two rooms. Or if room 2 has south set to false, than north will be false in room 1 to stop overlap.
Here is my current code (I know my code isn't exactly clean and has a lot of magic numbers, but those shouldn't be important for this question)-
GameState:
public class GameState extends JFrame implements KeyListener {
Container contentPane=this.getContentPane();
Graphics bufferGraphics;
int characterX=463;
int characterY=486;
int oldCharacterX=463;
int oldCharacterY=486;
int xAxis;
int yAxis;
int minimapX=1300;
int minimapY=515;
Image characterNorth = CustomImages.createImageIcon("Images/characterNorth.jpg").getImage();
Image characterEast = CustomImages.createImageIcon("Images/characterEast.jpg").getImage();
Image characterSouth = CustomImages.createImageIcon("Images/characterSouth.jpg").getImage();
Image characterWest = CustomImages.createImageIcon("Images/characterWest.jpg").getImage();
Image brickWall = CustomImages.createImageIcon("Images/brickWall.jpg").getImage();
Image brickFloor = CustomImages.createImageIcon("Images/brickFloor.jpg").getImage();
Image character=characterNorth;
boolean pressed=false;
boolean minimap=true;
ArrayList<RoomState> map = new ArrayList<RoomState>();
RoomState currentRoom = new RoomState();
RoomState currentRoomState=new RoomState();
GameState() {
this.setBounds(0, 0, 1680, 1050);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addKeyListener(this);
setFocusable(true);
requestFocusInWindow();
}
public void move(int x, int y) { //Check Move
currentRoomState=currentRoomState.MoveToNextRoom(true, false, false, false);
currentRoomState=currentRoomState.MoveToNextRoom(false, true, false, false);
currentRoomState=currentRoomState.MoveToNextRoom(false, false, true, false);
currentRoomState=currentRoomState.MoveToNextRoom(false, false, false, true);
}
public void paint(Graphics g) { //Graphics
for(xAxis=58;xAxis<=858;xAxis=xAxis+50) {
for(yAxis=81;yAxis<=881;yAxis=yAxis+50) {
g.drawImage(brickFloor,xAxis,yAxis,null);
}
yAxis=31;
}
for(xAxis=8;xAxis<958;xAxis=xAxis+50) {
g.drawImage(brickWall,xAxis,yAxis,null);
}
yAxis=931;
for(xAxis=8;xAxis<=908;xAxis=xAxis+50) {
g.drawImage(brickWall,xAxis,yAxis,null);
}
xAxis=8;
for(yAxis=81;yAxis<=881;yAxis=yAxis+50) {
g.drawImage(brickWall,xAxis,yAxis,null);
}
xAxis=908;
for(yAxis=81;yAxis<=881;yAxis=yAxis+50) {
g.drawImage(brickWall,xAxis,yAxis,null);
}
if(currentRoom.northDoor) {
g.drawImage(brickFloor,458,31,null);
}
if(currentRoom.eastDoor) {
g.drawImage(brickFloor,908,481,null);
}
if(currentRoom.southDoor) {
g.drawImage(brickFloor,458,931,null);
}
if(currentRoom.westDoor) {
g.drawImage(brickFloor,8,481,null);
}
g.drawImage(character,characterX,characterY,null);
g.drawString("[ ]",minimapX,minimapY);
g.setColor(Color.RED);
g.drawString("[ ]", 1300, 515);
}
#Override
public void keyPressed(KeyEvent arg0) { //Character Rotation/Movement.
if(pressed==false) {
pressed=true;
oldCharacterX=characterX;
oldCharacterY=characterY;
if(arg0.getKeyCode() == KeyEvent.VK_W || arg0.getKeyCode() == KeyEvent.VK_UP) {
if(character==characterNorth) {
if(characterY>86 && characterX>13 && characterX<913) {
characterY=characterY-50;
}else if(currentRoom.northDoor && characterX==463) {
oldCharacterY=characterY;
characterY=characterY-50;
if(characterY==-14) {
if(currentRoom.rs_NorthDoor != null) {
currentRoom=currentRoom.rs_NorthDoor;
}else {
RoomState nextRoom = new RoomState(currentRoom,false, false, true, false);
currentRoom.rs_NorthDoor = nextRoom;
map.add(nextRoom);
currentRoom = nextRoom;
nextRoom = null;
}
minimapY=minimapY-10;
characterX=463;
characterY=936;
repaint();
}
}
}else {
character=characterNorth;
}
}
if(arg0.getKeyCode() == KeyEvent.VK_A || arg0.getKeyCode() == KeyEvent.VK_LEFT) {
if(character==characterWest && characterY>36 && characterY<926) {
if(characterX>63) {
oldCharacterX=characterX;
characterX=characterX-50;
}else if(currentRoom.westDoor && characterY==486) {
oldCharacterX=characterX;
characterX=characterX-50;
if(characterX==-37) {
if(currentRoom.rs_WestDoor != null) {
currentRoom = currentRoom.rs_WestDoor;
}else {
RoomState nextRoom = new RoomState(currentRoom,false, true, false, false);
currentRoom.rs_WestDoor = nextRoom;
map.add(nextRoom);
currentRoom = nextRoom;
nextRoom = null;
}
minimapX=minimapX-8;
characterX=913;
characterY=486;
repaint();
}
}
}else {
character=characterWest;
}
}
if(arg0.getKeyCode() == KeyEvent.VK_S || arg0.getKeyCode() == KeyEvent.VK_DOWN) {
if(character==characterSouth) {
if(characterY<871 && characterX>13 && characterX<913) {
oldCharacterY=characterY;
characterY=characterY+50;
}else if(currentRoom.southDoor && characterX==463) {
oldCharacterY=characterY;
characterY=characterY+50;
if(characterY==986) {
if(currentRoom.rs_SouthDoor != null) {
currentRoom=currentRoom.rs_SouthDoor;
}else {
RoomState nextRoom = new RoomState(currentRoom,true, false, false, false);
currentRoom.rs_SouthDoor = nextRoom;
map.add(nextRoom);
currentRoom = nextRoom;
nextRoom = null;
}
minimapY=minimapY+10;
characterX=463;
characterY=36;
repaint();
}
}
}else {
character=characterSouth;
}
}
if(arg0.getKeyCode() == KeyEvent.VK_D || arg0.getKeyCode() == KeyEvent.VK_RIGHT) {
if(character==characterEast && characterY>36 && characterY<926) {
if(characterX<848) {
oldCharacterX=characterX;
characterX=characterX+50;
}else if(currentRoom.eastDoor && characterY==486) {
oldCharacterX=characterX;
characterX=characterX+50;
if(characterX==963) {
if(currentRoom.rs_EastDoor != null) {
currentRoom = currentRoom.rs_EastDoor;
}else {
RoomState nextRoom = new RoomState(currentRoom,false, false, false, true);
currentRoom.rs_EastDoor = nextRoom;
map.add(nextRoom);
currentRoom = nextRoom;
nextRoom = null;
}
minimapX=minimapX+8;
characterX=13;
characterY=486;
repaint();
}
}
}else {
character=characterEast;
}
}
if(oldCharacterX != characterX || oldCharacterY != characterY) {
repaint(oldCharacterX,oldCharacterY,40,40);
}
repaint(characterX,characterY,40,40);
}
}
#Override
public void keyReleased(KeyEvent arg0) { //Prevents Holding Down Keys.
if(arg0.getKeyCode() == KeyEvent.VK_W || arg0.getKeyCode() == KeyEvent.VK_UP) {
pressed=false;
}
if(arg0.getKeyCode() == KeyEvent.VK_A || arg0.getKeyCode() == KeyEvent.VK_LEFT) {
pressed=false;
}
if(arg0.getKeyCode() == KeyEvent.VK_S || arg0.getKeyCode() == KeyEvent.VK_DOWN) {
pressed=false;
}
if(arg0.getKeyCode() == KeyEvent.VK_D || arg0.getKeyCode() == KeyEvent.VK_RIGHT) {
pressed=false;
}
}
#Override
public void keyTyped(KeyEvent arg0) {
}
}
RoomState:
public class RoomState {
boolean northDoor;
boolean eastDoor;
boolean southDoor;
boolean westDoor;
boolean doorsOpen;
int northRoll;
int eastRoll;
int southRoll;
int westRoll;
Random r=new Random();
//Reference to the adjacent rooms
RoomState rs_NorthDoor=null;
RoomState rs_EastDoor=null;
RoomState rs_SouthDoor=null;
RoomState rs_WestDoor=null;
RoomState() { //Initial
while(!doorsOpen) {
northRoll=r.nextInt(6)+1;
eastRoll=r.nextInt(6)+1;
southRoll=r.nextInt(6)+1;
westRoll=r.nextInt(6)+1;
if(northRoll==1) {
northDoor=true;
}else {
northDoor=false;
}
if(eastRoll==1) {
eastDoor=true;
}else {
eastDoor=false;
}
if(southRoll==1) {
southDoor=true;
}else {
southDoor=false;
}
if(westRoll==1) {
westDoor=true;
}else {
westDoor=false;
}
if(northDoor==false && eastDoor==false && southDoor==false && westDoor==false) {
doorsOpen=false;
}else {
doorsOpen=true;
}
}
}
RoomState(RoomState previousState, boolean north, boolean east, boolean south, boolean west) {
this();
if(north) {
rs_NorthDoor=previousState;
northDoor=true;
}else if(east) {
rs_EastDoor=previousState;
eastDoor=true;
}else if(south) {
rs_SouthDoor=previousState;
southDoor=true;
}else if(west) {
rs_WestDoor=previousState;
westDoor=true;
}
}
public RoomState MoveToNextRoom(boolean north, boolean east, boolean south, boolean west) {
if(north) {
if(rs_NorthDoor==null) {
rs_NorthDoor=new RoomState(this,north,east,south,west);
}
return rs_NorthDoor;
}
if(east) {
if(rs_EastDoor==null) {
rs_EastDoor=new RoomState(this,north,east,south,west);
}
return rs_EastDoor;
}
if(south) {
if(rs_SouthDoor==null) {
rs_SouthDoor=new RoomState(this,north,east,south,west);
}
return rs_SouthDoor;
}
if(west) {
if(rs_WestDoor==null) {
rs_WestDoor=new RoomState(this,north,east,south,west);
}
return rs_WestDoor;
}
return null;
}
}

KeyPressed/KeyReleased not working?

I'm trying to make a game in java, just a simple platformer, but I'm having difficulty when running the code. I can't seem to get any response from key presses. The only thing I can think hasn't been working properly is the keyPressed and keyReleased functions. Below is the relevant code.
public ReflexPanel() {
initBoard();
setFocusable(true);
addKeyListener(this);
Timer timer = new Timer(1000/120, this);
timer.start();
}
private void initBoard() {
loadMenu();
int w = menu.getWidth(this);
int h = menu.getHeight(this);
setPreferredSize(new Dimension(w, h));
}
private void step() {
if(mainMenu){
if(ePressed) {
System.exit(0);
}
if(hPressed) {
loadScores();
repaint();
}
}
}
public void keyTyped(KeyEvent e) {}
#Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == 'e') {
ePressed = true;
}
if (e.getKeyCode() == 'h') {
hPressed = true;
}
}
#Override
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == 'e') {
ePressed = false;
}
if (e.getKeyCode() == 'h') {
hPressed = false;
}
}
#Override
public void actionPerformed(ActionEvent e) {
step();
}
The ePressed and hPressed variables are just booleans set to false by default, and loadScores calls a png file.
You can't do this:
if(e.getKeyCode() == 'e'){
// code logic
}
KeyEvent::getKeyCode doesn't return the char you press on the keyboard. It "returns the integer keyCode associated with the key in this event". When using KeyEvent::getKeyCode you have to use the KeyEvent key constants values predefined in the class. So for example:
if(e.getKeyCode() == KeyEvent.VK_E){
// code logic
}
Or you can use KeyEvent::getKeyChar which "returns the character associated with the key in this event".
You're using getKeyCode() which returns an int value with constants given in KeyEvent class, such as KeyEvent.VK_E.
You're looking to use getKeyChar() which returns 'e' directly.
if (e.getKeyChar() == 'e') { // Now it has an actual chance of working

player1 stops moving if player2 moves the other direction

If I move my player1 and player2 up, and let's say I push the down key for player1, my player stops moving up. I can't find the problem. Can someone please help me and explain what I did wrong?
package game;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
public class KeyInput extends KeyAdapter{
private Handler handler;
private boolean [] keyPressed = new boolean [4];
public KeyInput(Handler handler){
this.handler = handler;
}
public void keyPressed(KeyEvent e){
int key = e.getKeyCode();
keyPressed[0]= false;
keyPressed[1]= false;
keyPressed[2]= false;
keyPressed[3]= false;
for(int i = 0; i <handler.object.size(); i++){
GameObject tempobject= handler.object.get(i);
if (tempobject.getId()== ID.Player1){
if (key == KeyEvent.VK_UP){tempobject.setSpeedy(-7); keyPressed[0] = true;}
if (key == KeyEvent.VK_DOWN){tempobject.setSpeedy(7); keyPressed[1] = true;}
}
if(tempobject.getId()== ID.player2)
if (key == KeyEvent.VK_W){tempobject.setSpeedy2(-7); keyPressed[2] = true;}
if (key == KeyEvent.VK_S){tempobject.setSpeedy2(7); keyPressed[3] = true;}
}
if(key == KeyEvent.VK_ESCAPE)System.exit(1);
}
public void keyReleased(KeyEvent e){
int key = e.getKeyCode();
for(int i = 0; i <handler.object.size(); i++){
GameObject tempobject= handler.object.get(i);
if (tempobject.getId()== ID.Player1){
if (key == KeyEvent.VK_UP) keyPressed[0] = false;
if (key == KeyEvent.VK_DOWN) keyPressed[1] = false;
if(!keyPressed[0] && !keyPressed[1])tempobject.setSpeedy(0);
}
if (tempobject.getId()== ID.player2){
if (key == KeyEvent.VK_W) keyPressed[2] = false;
if (key == KeyEvent.VK_S) keyPressed[3] = false;
if(!keyPressed[2] && !keyPressed[3])tempobject.setSpeedy2(0);
}
}
}
}
It probably has to do with this:
keyPressed[0]= false;
keyPressed[1]= false;
keyPressed[2]= false;
keyPressed[3]= false;
This would make it so that whenever any key is pressed, the other keys are set to false, even if they may still be being held down.

Implementing pause/resume function in Java game

I have managed to pause the game using *running = !running
But it's unable to unpause if this is used
And thread.resume() or thread.wait() doesn't work either to unpause it when 'P' is pressed
private volatile boolean running;
private Thread thread;
public static enum STATE {
MENU,
GAME,
};
public static STATE State = STATE.MENU;
public void init(){
requestFocus();
}
private synchronized void start(){
if(running)
return;
running = true;
thread = new Thread(this);
thread.start();
}
private synchronized void stop(){
if(!running)
return;
running = false;
try{
thread.join();
}catch(InterruptedException e){
e.printStackTrace();
}
}
public void run() {
init();
while(running){
/some codes
}
stop();
}
private void render(){
if(State == STATE.GAME){
p.render(g);
c.render(g);
}else if(State == STATE.MENU){
menu.render(g);
}
g.dispose();
bs.show();
}
public void keyPressed(KeyEvent e){
int key = e.getKeyCode();
if(State == STATE.GAME){
if(key == KeyEvent.VK_RIGHT){
p.setVelX(5);
}else if(key == KeyEvent.VK_LEFT){
p.setVelX(-5);
}else if(key == KeyEvent.VK_DOWN){
p.setVelY(5);
}else if(key == KeyEvent.VK_UP){
p.setVelY(-5);
}else if(key == KeyEvent.VK_SPACE && !is_shooting){
c.addEntity(new Bullet(p.getX(), p.getY(), tex, this));
is_shooting = true;
}else if(key == KeyEvent.VK_P){
This line is to pause.
running = !running;
}
}
}
public void keyReleased(KeyEvent e){
int key = e.getKeyCode();
if(key == KeyEvent.VK_RIGHT){
p.setVelX(0);
}else if(key == KeyEvent.VK_LEFT){
p.setVelX(0);
}else if(key == KeyEvent.VK_DOWN){
p.setVelY(0);
}else if(key == KeyEvent.VK_UP){
p.setVelY(0);
}else if(key == KeyEvent.VK_SPACE){
is_shooting = false;
}else if(key == KeyEvent.VK_P){
// This line doesn't work.
running = true;
}
}
At the moment, as soon as running is set to false, your game thread exits (run() method returns).
public void run() {
init();
while(running){
/some codes
}
stop();
}
Should be changed to something more like this:
public void run() {
init();
while(true){
if(!running) {
Thread.sleep(1000); //1 second or something else
continue;
}
//Game logic here
}
stop();
}
You will of course need to differentiate between running and paused, to be able to break out of this loop.
Setting running = !runnning will just change the variable, you're not actually stopping anything unless you're using the variable in the game loop.
To pause the method, use Thread.sleep()or simply stop the thread, then start it again if you don't know how long you want to pause it for.

How could I possibly create two of the same thing in java

Okay, so my question is, in swing, how could i make two of the same thing while they both have the same attributes but yet can act independently, for example, i am working on a city builder, when the uses presses a button to add a oil power station, the power station will get added to the world, however, there is only one. how could i make it so that the player could make a seamless amount of the same building but yet they all act independently, e.g when i go to add a second of the same building the first one won't follow the mouse.
heres my current code to help explain my issue:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
public class Game extends JFrame{
public Image map;
public Image utilButton;
public Image resButton;
public Image oilPlantBox;
public Image apartmentBlockABox;
//Building Img
public Image oilPowerStation;
public Image apartmentBlockA;
//Util selects
boolean showUtil = false;
boolean UtilSelect = false;
//Residential selects
boolean showRes = false;
boolean resSelect = false;
//Oil Power Station
boolean showOPPBox = true;
boolean checkOilPowerPlant = false;
boolean drawOilPlant = false;
boolean setPowerStation = false;
boolean placeOilPowerPlant = true;
int OilPowerStationxX = 0;
int OilPowerStationY = 0;
//Apartment Block A
boolean showABA = true;
boolean checkApartmentBlockA = false;
boolean drawApartmentBlockA = false;
boolean setApartmentBlockA = false;
boolean placeApartmentBlockA = true;
int apartmentBlockAX = 0;
int apartmentBlockAY = 0;
int x;
int y;
public int power = 0;
int jobs = 0;
public Game(){
//Load Images:
ImageIcon mapI = new ImageIcon("C:/Programs/Eclipse/eclipse/CityCenterBeta/bin/map.jpg");
map = mapI.getImage();
ImageIcon utilButtonI = new ImageIcon("C:/Programs/Eclipse/eclipse/CityCenterBeta/bin/UTIL.jpg");
utilButton = utilButtonI.getImage();
ImageIcon resButtonI = new ImageIcon("C:/Programs/Eclipse/eclipse/CityCenterBeta/bin/RES.jpg");
resButton = resButtonI.getImage();
ImageIcon oPB = new ImageIcon("C:/Programs/Eclipse/eclipse/CityCenterBeta/bin/oilPlantBox.png");
oilPlantBox = oPB.getImage();
ImageIcon aBAB = new ImageIcon("C:/Programs/Eclipse/eclipse/CityCenterBeta/bin/apartmentABlock.jpg");
apartmentBlockABox = aBAB.getImage();
//Building Images
//Oil Power Station
ImageIcon oilPlantI = new ImageIcon("C:/Programs/Eclipse/eclipse/CityCenterBeta/bin/oilPlant.jpg");
oilPowerStation = oilPlantI.getImage();
//Apartment Block A
ImageIcon apartmentBlockI = new ImageIcon("C:/Programs/Eclipse/eclipse/CityCenterBeta/bin/apartment block.jpg");
apartmentBlockA = apartmentBlockI.getImage();
//Set up game
addKeyListener(new AL());
addMouseListener(new Mouse());
init();
}
private Image dbImage;
private Graphics dbg;
public static void main(String[] args) {
new Game();
}
//When the program runs, thins are initialised here
public void init(){
windowManager();
}
public void paintComponent(Graphics g){
g.drawImage(map,0,0,null);
g.drawImage(utilButton,20,100,null);
g.drawImage(resButton,20,200,null);
if(showUtil == true){
if(showOPPBox == true){
g.drawImage(oilPlantBox,190,130,null);
}
}
if(showRes == true){
if(showABA == true){
g.drawImage(apartmentBlockABox,190,130,null);
}
}
if(drawOilPlant == true){
g.drawImage(oilPowerStation,OilPowerStationxX,OilPowerStationY,null);
if(checkOilPowerPlant == true){
setPowerStation = true;
}
if(drawApartmentBlockA == true){
g.drawImage(apartmentBlockA,apartmentBlockAX,apartmentBlockAY,null);
if(checkApartmentBlockA == true){
setApartmentBlockA = true;
}
}
}
repaint();
}
public void paint(Graphics g){
dbImage = createImage(getWidth(), getHeight());
dbg = dbImage.getGraphics();
paintComponent(dbg);
g.drawImage(dbImage,0,0,this);
}
public void windowManager(){
JFrame f = new JFrame();
setTitle("City Center");
setVisible(true);
setResizable(false);
setBackground(Color.BLACK);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setExtendedState(f.MAXIMIZED_BOTH);
setUndecorated(true);
}
public class AL extends KeyAdapter{
public void keyPressed(KeyEvent e){
int keyCode = e.getKeyCode();
if(keyCode == e.VK_ENTER){
if(setPowerStation == true)
placeOilPowerPlant = false;
checkOilPowerPlant = false;
setPowerStation = false;
showUtil = false;
UtilSelect = false;
showOPPBox = false;
oilPlantAtt();
System.out.println(jobs + " Job Openings");
System.out.println(power + "MW");
}
if(setApartmentBlockA == true){
placeApartmentBlockA = false;
checkApartmentBlockA = false;
setApartmentBlockA = false;
showRes = false;
resSelect = false;
showABA = false;
apartmentBlockAtt();
}
}
public void keyReleased(KeyEvent e){
}
}
public class Mouse extends MouseAdapter {
public void mousePressed(MouseEvent e) {
x = e.getX();
y = e.getY();
//Pressed Utilies button
if((x > 20) && (x < 120) && (y > 100) && (y < 200) && (showUtil == false)) {
showUtil = true;
UtilSelect = true;
showRes = false;
resSelect = false;
}
//Pressed Residential Button
if((x > 20) && (x < 120) && (y > 200) && (y < 300) && (showRes == false)){
showRes = true;
resSelect = true;
showUtil = false;
UtilSelect = false;
}
if((x > 190) && (x < 265) && (y > 130) && (y < 192)){
if(resSelect == true){
drawApartmentBlockA = true;
if(placeApartmentBlockA == true){
checkApartmentBlockA = true;
}
}
if(UtilSelect == true){
drawOilPlant = true;
if(placeOilPoerPlant == true){
checkOilPowerPlant = true;
}
}
}
if(setPowerStation == true){
OilPowerStationxX = x;
OilPowerStationY = y;
}else{
OilPowerStationxX = OilPowerStationxX;
OilPowerStationY = OilPowerStationY;
}
if(setApartmentBlockA == true){
apartmentBlockAX = x;
apartmentBlockAY = y;
}else{
apartmentBlockAX = apartmentBlockAX;
apartmentBlockAY = apartmentBlockAY;
}
}
}
public void oilPlantAtt(){
jobs = jobs + 150;
power = power + 1000;
}
public void apartmentBlockAtt(){
boolean work = false;
if(power > 0){
work = true;
}
if(work == true){
jobs = jobs - 300;
power = power - 100;
}
}
You actually need to create 2 different instances with the similar properties or try this snippet:
Object building = new Object();
building.isLockedInPlace = false;
And use building.isLockedInPlace to say if you have one down.
To have multiple, you will have to use Object.clone();.
Hope it works and happy coding!
Based on your problem description and your provided code, it appears that you are new to object-oriented programming (OOP), which Java revolves around. If you haven't done so already, I'd recommend looking through the core Java tutorials again, regarding objects and their use.
As it stands, you have included everything in one file: the attributes of your power plant, of your apartment block, etc. What your program should look like is the following:
A Game class (which you have already) that contains either one or a collection of City objects.
A City class which contains a collection of Building objects.
A Building class could be abstract or an interface, which your ApartmentBlock and PowerPlant classes would extend or implement.
This structure is extensible and allows you to easily add more buildings and building types. You can also better enforce data encapsulation (which you aren't doing at all here), as each concrete building class (like your ApartmentBlock and PowerPlant) would also be the only ones who cared about what image they were displaying, and other data building specific information that only they really need to know.

Categories