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;
}
}
Related
I am still new to java and I've been trying to make a SpaceInvaders copy in Java's native graphics. I've finished the basic mechanics, however the game slows down significantly when the player or aliens shoot a bullet. I have tried to find out what was causing the game to slow down, but was unable to.
public class Board extends JPanel implements KeyListener,ActionListener{
Ship ship;
Alien[] row1 = new Alien[10];
Alien[] row2 = new Alien[10];
Alien[] row3 = new Alien[10];
private Timer timer;
int DELAY = 16;
boolean reachedend = false;
Bullet bullet;
int lives;
public Board() {
setBackground(Color.BLACK);
addKeyListener(this);
lives = 3;
ship = new Ship();
fillAliens();
timer = new Timer(DELAY, this);
timer.start();
}
void fillAliens() {
for(int x=1;x<11;x++) {
row1[x-1] = new Alien(x*30+40,30);
row2[x-1] = new Alien(x*30+40,70);
row3[x-1] = new Alien(x*30+40,110);
}
}
void shoot() {
if(bullet==null) {
bullet = new Bullet(ship.x + ship.width/2,ship.y - ship.height/2,-1);
}
}
void drawAliens(Graphics2D g) {
g.setColor(Color.red);
for(int x=1;x<11;x++) {
if(row1[x-1].alive == true) {
g.fillRect(row1[x-1].x_loc, row1[x-1].y_loc, row1[x-1].width, row1[x-1].width);
}
if(row2[x-1].alive == true) {
g.fillRect(row2[x-1].x_loc, row2[x-1].y_loc, row2[x-1].width, row2[x-1].width);
}
if(row3[x-1].alive == true) {
g.fillRect(row3[x-1].x_loc, row3[x-1].y_loc, row3[x-1].width, row2[x-1].width);
}
}
}
public void addNotify() {
super.addNotify();
requestFocus();
}
void drawShip(Graphics2D g) {
g.fillRect(ship.x, ship.y, ship.width, ship.height);
}
#Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if(lives>0) {
if (key == KeyEvent.VK_SPACE) {
shoot();
}
if (key == KeyEvent.VK_LEFT) {
if(ship.x>=5) {
ship.x -= 5;
}
}
if (key == KeyEvent.VK_RIGHT) {
if(ship.x+ship.width<434) {
ship.x += 5;
}
}
}
repaint();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
drawShip(g2);
drawAliens(g2);
drawBullet(g2);
drawAlienBullet(g2);
drawLives(g2);
}
private void drawLives(Graphics2D g2) {
g2.setColor(Color.white);
g2.drawString("Lives:", 10, 300);
for(int x=1; x<=lives;x++) {
g2.fillRect(15*x+30, 290, 10, 10);
}
}
private void drawBullet(Graphics2D g2) {
g2.setColor(Color.GREEN);
if(bullet!=null) {
g2.fillRect(bullet.x_loc, bullet.y_loc, bullet.width, bullet.height);
}
}
private void drawAlienBullet(Graphics2D g2) {
g2.setColor(Color.BLUE);
for(int x=0;x<10;x++) {
if(row3[x].bullet != null) {
g2.fillRect(row3[x].bullet.x_loc, row3[x].bullet.y_loc, row3[x].bullet.width, row3[x].bullet.height);
}
if(row2[x].bullet != null) {
g2.fillRect(row2[x].bullet.x_loc, row2[x].bullet.y_loc, row2[x].bullet.width, row2[x].bullet.height);
}
if(row1[x].bullet != null ) {
g2.fillRect(row1[x].bullet.x_loc, row1[x].bullet.y_loc, row1[x].bullet.width, row1[x].bullet.height);
}
}
}
private void bulletHitPlayer() {
for(int x=0;x<10;x++) {
if(row3[x].bullet != null) {
if(row3[x].bullet.y_loc >= 350) {
row3[x].bullet = null;
break;
}
}
if(row2[x].bullet != null) {
if(row2[x].bullet.y_loc >= 350) {
row2[x].bullet = null;
break;
}
}
if(row1[x].bullet != null) {
if(row1[x].bullet.y_loc >= 350) {
row1[x].bullet = null;
break;
}
}
if(row3[x].bullet != null && row3[x].bullet.y_loc + 10 >= ship.y && row3[x].bullet.y_loc <= ship.y + ship.height && row3[x].bullet.x_loc >= ship.x && row3[x].bullet.x_loc <= ship.x+ship.width) {
row3[x].bullet = null;
lives--;
break;
}
if(row2[x].bullet != null && row2[x].bullet.y_loc + 10 >= ship.y && row2[x].bullet.y_loc <= ship.y + ship.height && row2[x].bullet.x_loc >= ship.x && row2[x].bullet.x_loc <= ship.x+ship.width) {
row2[x].bullet = null;
lives--;
break;
}
if(row1[x].bullet != null && row1[x].bullet.y_loc + 10 >= ship.y && row1[x].bullet.y_loc <= ship.y + ship.height && row1[x].bullet.x_loc >= ship.x && row1[x].bullet.x_loc <= ship.x+ship.width) {
row1[x].bullet = null;
lives--;
break;
}
}
}
private void bulletHit() {
if(bullet!=null) {
for(int x=0;x<10;x++) {
if(row3[x].alive == true && bullet.y_loc >= row3[x].y_loc && bullet.y_loc <= row3[x].y_loc+row3[x].width && bullet.x_loc >= row3[x].x_loc && bullet.x_loc <= row3[x].x_loc+row3[x].width) {
row3[x].alive = false;
bullet=null;
break;
}
if(row2[x].alive == true && bullet.y_loc >= row2[x].y_loc && bullet.y_loc <= row2[x].y_loc+row2[x].width && bullet.x_loc >= row2[x].x_loc && bullet.x_loc <= row2[x].x_loc+row2[x].width) {
row2[x].alive = false;
bullet=null;
break;
}
if(row1[x].alive == true && bullet.y_loc >= row1[x].y_loc && bullet.y_loc <= row1[x].y_loc+row1[x].width && bullet.x_loc >= row1[x].x_loc && bullet.x_loc <= row1[x].x_loc+row1[x].width) {
row1[x].alive = false;
bullet=null;
break;
}
}
}
if(bullet!=null) {
if(bullet.y_loc<0) {
bullet=null;
}
}
}
#Override
public void keyTyped(KeyEvent e) {}
#Override
public void keyReleased(KeyEvent e) {}
#Override
public void actionPerformed(ActionEvent e) {
bulletHitPlayer();
bulletHit();
repaint();
}
}
Problem:
You draw your scene, whenever you press a key; and you draw your scene once on startup (see API and Tutorials) - But you should continuously redraw your scene by using the Timer properly.
How to solve:
When you create your Timer let it
either repeat itself timer.setRepeats(true);
or restart the Timer manually:
public void actionPerformed(ActionEvent e) {
bulletHitPlayer();
bulletHit();
repaint();
timer.restart(); //manually restart the timer
}
I am currently trying to code a Tic Tac Toe game in Java that is playable across networks. I'm using socket programming in Java and for the UI I am using JavaFX. Upon launching the server and 2 clients, the client connects to the server, pairs players and creates the game. When trying to execute the actual Tic Tac Toe game the GUI gets stuck. I believe it may have something to do with threading but after countless hours of trying different solutions I haven't been able to figure it out.
Below is a video of the issue
https://www.youtube.com/watch?v=dCIxRkGJlCI&t=2s
My GitHub Repo:
https://github.com/Stinny/Tic-Tac-Toe
The issue I believe resides in the TicTacToeController.java class
Any info would be greatly appreciated!
This is my TicTacToeController Class
public class TicTacToeController implements Initializable {
private static Socket socket;
private static PrintWriter out;
private static BufferedReader in;
private static Image Circle = new Image("./Circle.png");
private static Image Cross = new Image("./Cross.png");
private static ImageView icon, opponentIcon;
#FXML
Button topLeft, topRight, topCenter,
midLeft, midCenter, midRight,
botLeft, botMid, botRight;
#FXML
Button play;
public void initialize(URL url, ResourceBundle rb) {
}
public void buttonClickHandler(ActionEvent evt) throws Exception{
Button clickedButton = (Button) evt.getTarget();
evt.getEventType();
String button =((Control)evt.getSource()).getId();
System.out.println(button);
if(button.equals("play")){
clickedButton.setDisable(true);
play();
}
else if (button.equals("topLeft")) {
out.print("MOVE0");
//do something
} else if (button.equals("topRight")) {
//do something
out.print("MOVE2");
} else if (button.equals("topCenter")) {
//do something
out.print("MOVE1");
} else if (button.equals("midLeft")) {
//do something
out.print("MOVE3");
} else if (button.equals("midCenter")) {
//do something
out.print("MOVE4");
} else if (button.equals("midRight")) {
//do something
out.print("MOVE5");
} else if (button.equals("botLeft")) {
//do something
out.print("MOVE6");
} else if (button.equals("botMid")) {
//do something
out.print("MOVE7");
} else if (button.equals("botRight")) {
//do something
out.print("MOVE8");
}
}
public void play() throws IOException {
String response;
try {
connectToServer();
response = in.readLine();
System.out.println("Send to server" + in);
char mark = response.charAt(7);
System.out.println("You are " + mark);
if (mark == 'X') {
icon = new ImageView(Circle);
opponentIcon = new ImageView(Cross);
} else {
icon = new ImageView(Cross);
opponentIcon = new ImageView(Circle);
}
//frame.setTitle("Tic Tac Toe - Player " + mark);
while (true) {
response = in.readLine();
if (response != null) {
System.out.println(response);
if (response.startsWith("VALID_MOVE")) {
int location = Integer.parseInt(response.substring(5));
if (location == 0) {
handleButtonClick(topLeft, icon);
} else if (location == 1) {
handleButtonClick(topLeft, icon);
} else if (location == 2) {
handleButtonClick(topLeft, icon);
} else if (location == 3) {
handleButtonClick(topLeft, icon);
} else if (location == 4) {
handleButtonClick(topLeft, icon);
} else if (location == 5) {
handleButtonClick(topLeft, icon);
} else if (location == 6) {
handleButtonClick(topLeft, icon);
} else if (location == 7) {
handleButtonClick(topLeft, icon);
} else if (location == 7) {
handleButtonClick(topLeft, icon);
} else if (location == 8) {
handleButtonClick(topLeft, icon);
}
} else if (response.startsWith("OPPONENT_MOVED")) {
int location = Integer.parseInt(response.substring(15));
if (location == 0) {
handleButtonClick(topLeft, opponentIcon);
} else if (location == 1) {
handleButtonClick(topCenter, opponentIcon);
} else if (location == 2) {
handleButtonClick(topRight, opponentIcon);
} else if (location == 3) {
handleButtonClick(midLeft, opponentIcon);
} else if (location == 4) {
handleButtonClick(midCenter, opponentIcon);
} else if (location == 5) {
handleButtonClick(midRight, opponentIcon);
} else if (location == 6) {
handleButtonClick(botLeft, opponentIcon);
} else if (location == 7) {
handleButtonClick(botMid, opponentIcon);
} else if (location == 8) {
handleButtonClick(botRight, opponentIcon);
}
} else if (response.startsWith("VICTORY")) {
//messageLabel.setText("You win");
break;
} else if (response.startsWith("DEFEAT")) {
//messageLabel.setText("You lose");
break;
} else if (response.startsWith("TIE")) {
//messageLabel.setText("You tied");
break;
}
}
}
out.println("QUIT");
}
finally {
socket.close();
}
}
public void handleButtonClick(Button button, ImageView mark){
button.setGraphic(mark);
}
public static void connectToServer(){
try {
socket = new Socket("localhost", 7777);
in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);
} catch (IOException e) {
System.out.println(e + " fuck");
}
}
}
This is my server class:
public class Server {
private static ServerSocket serverSocket;
private static ArrayList<Socket> sockets;
private static Socket socket;
public static void main(String[] args) throws Exception {
try {
serverSocket = new ServerSocket(7777);
sockets = new ArrayList<>();
for(int i = 1; i < 3; i++){
socket = serverSocket.accept();
System.out.println("Player " + i + " connected");
sockets.add(socket);
}
Game game = new Game();
System.out.println("Created game, waiting for players to connect");
Game.PlayerHandler playerX = game.new PlayerHandler(sockets.remove(sockets.size()-1), 'X');
Game.PlayerHandler playerO = game.new PlayerHandler(sockets.remove(sockets.size()-1), 'O');
game.currentPlayer = playerX;
playerX.start();
playerO.start();
System.out.println("Game started");
}catch(IOException e)
{
e.printStackTrace();
}
}
}
class Game{
private PlayerHandler[] board = {
null, null, null,
null, null, null,
null, null, null
};
PlayerHandler currentPlayer;
public boolean isFull(){
for(int i = 0; i < board.length; i++) {
if(board[i] == null){
return false;
}
}
return true;
}
public boolean hasWinner() {
if (checkHorizontalWin() || checkVerticalWin() || checkDiagonalWin()) {
return true;
} else {
return false;
}
}
public boolean checkHorizontalWin() {
if (board[0] != null && board[0] == board[1] && board[0] == board[2]) {
return true;
} else if(board[3] != null && board[3] == board[4] && board[3] == board[5]) {
return true;
} else if(board[6] != null && board[6] == board[7] && board[6] == board[8]) {
return true;
} else {
return false;
}
}
public boolean checkVerticalWin() {
if (board[0] != null && board[0] == board[3] && board[0] == board[6]) {
return true;
} else if(board[1] != null && board[1] == board[4] && board[1] == board[7]) {
return true;
} else if(board[2] != null && board[2] == board[5] && board[2] == board[8]) {
return true;
} else {
return false;
}
}
public boolean checkDiagonalWin() {
if (board[0] != null && board[0] == board[4] && board[0] == board[8]) {
return true;
} else if (board[2] != null && board[2] == board[4] && board[2] == board[6]) {
return true;
} else {
return false;
}
}
public synchronized boolean move(PlayerHandler player, int location) { //A player moves based on their assigned Piece
System.out.println("Player moved at location " + location);
if(board[location]==null){
board[location] = player;
currentPlayer = currentPlayer.opponent;
currentPlayer.opponentMoved(location);
return true;
}
return false;
}
class PlayerHandler extends Thread{
char mark;
private String name;
private Socket socket;
PlayerHandler opponent;
BufferedReader in;
PrintWriter out;
public PlayerHandler(Socket socket, char mark) {
this.socket = socket;
this.mark = mark;
try{
// initialize input and output streams
in = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);
out.println("WELCOME" + mark);
} catch(IOException e){
}
}
public void setOpponent(PlayerHandler opponent){
this.opponent = opponent;
}
public void opponentMoved(int location){
out.println("OPPONENT_MOVED" + location);
out.println(
hasWinner() ? "DEFEAT" : isFull() ? "TIE" : "");
}
public void run() {
try {
if (mark == 'X') {
out.println("MESSAGE Your move");
}
while (true) {
String command = in.readLine();
if (command != null) {
if (command.startsWith("MOVE")) {
int location = Integer.parseInt(command.substring(5));
System.out.println(location);
if (move(this, location)) {
out.println("VALID_MOVE" + "location");
out.println(hasWinner() ? "VICTORY"
: isFull() ? "TIE"
: "");
} else {
out.println("MESSAGE ?");
}
}
}
}
}catch(IOException e) {
System.out.println("Player died: " + e);
} finally {
try {socket.close();} catch(IOException e){}
}
}
}
}
Hello I'm fairly new to programming and this is my first time posting here so any help would be appreciated so:
my problem is that I"m trying to create some kind of 2D shooter game in java but I don't know if my simple game loop is good because when i shoot a missile it shoots a one every 20 ms and it's too fast and shoots a ton of missiles at once so is there any way to adjust it ? Like to keep some delay between every missile and the other??
and please tell me if i have problems or bad programming in my code !!
this is my game panel where most of the game happens and where my loop and adding missiles method in
public class GamePanel extends JPanel implements KeyListener {
Measurments mesure = new Measurments();
int panel_width = mesure.getUniversalWidth();
int panel_height = mesure.getUniversalHeight();
Timer timer;
Random rand = new Random();
ArrayList<Enemy> enemies = new ArrayList<>();
ArrayList<Missile> missiles = new ArrayList<>();
Player player = new Player(0, 0);
boolean up = false;
boolean down = false;
boolean right = false;
boolean left = false;
boolean isShooting = false;
boolean isRunning = true;
public boolean gameRunning() {
return isRunning;
}
int count = 5;
int missilesCount = 6;
public GamePanel() {
timer = new Timer(20, new ActionListener() {
public void actionPerformed(ActionEvent e) {
StartGame();
repaint();
}
});
setSize(panel_width, panel_height);
addKeyListener(this);
timer.start();
for (int i = 0; i < count; i++) {
addEnemy(new Enemy(rand.nextInt(750), rand.nextInt(500)));
}
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
player.paint(g2d);
for (int i = 0; i < enemies.size(); i++) {
Enemy temp = enemies.get(i);
temp.paint(g2d);
}
for (int i = 0; i < missiles.size(); i++) {
Missile mis = missiles.get(i);
mis.paint(g2d);
mis.behave();
}
}
public void StartGame() {
if (isRunning) {
runGame();
setBackground(Color.YELLOW);
} else {
setBackground(Color.BLACK);
}
}
public void runGame() {
update();
};
public void update() {
player.checkBorders();
checkColls();
if (up) {
player.updateUp();
}
if (down) {
player.updateDown();
}
if (right) {
player.updateRight();
}
if (left) {
player.updateLeft();
}
if (isShooting) {
for (int i = 0; i < 5; i++) {
missiles.add(new Missile(player.getX() + 16, player.getY() + 16));
}
}
for (int i = 0; i < missiles.size(); i++) {
Missile temp = missiles.get(i);
if (temp.getX() == panel_width) {
RemoveMissile(temp);
}
}
}
public void addEnemy(Enemy e) {
enemies.add(e);
}
public void removeEnemy(Enemy e) {
enemies.remove(e);
}
public void addMissile(Missile e) {
missiles.add(e);
}
public void RemoveMissile(Missile e) {
missiles.add(e);
}
public void checkColls() {
for (int i = 0; i < enemies.size(); i++) {
Enemy tempEnm = enemies.get(i);
for (int e = 0; e < missiles.size(); e++) {
Missile tempMis = missiles.get(e);
if (tempMis.missileRect().intersects(tempEnm.enemyRect())) {
enemies.remove(tempEnm);
missiles.remove(tempMis);
}
}
}
}
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == e.VK_UP) {
up = true;
}
if (key == e.VK_DOWN) {
down = true;
}
if (key == e.VK_RIGHT) {
right = true;
}
if (key == e.VK_LEFT) {
left = true;
}
if (key == e.VK_ENTER) {
isRunning = true;
}
if (key == e.VK_SPACE) {
isShooting = true;
}
}
public void keyReleased(KeyEvent e) {
int key = e.getKeyCode();
if (key == e.VK_UP) {
up = false;
}
if (key == e.VK_DOWN) {
down = false;
}
if (key == e.VK_RIGHT) {
right = false;
}
if (key == e.VK_LEFT) {
left = false;
}
if (key == e.VK_SPACE) {
isShooting = false;
}
}
public void keyTyped(KeyEvent e) {
}
}
Thanks in advance !!
private long fired = 0L;
public void update() {
...
// firing missiles: only if the missile count is less than the max., and the elapsed
// time is more than a limit (100 ms)
if ( isShooting && missiles.size() < missilesCount &&
( System.currentTimeMilis() - this.fired ) > 100 ) {
missiles.add( new Missile( player.getX() + 16, player.getY() + 16 ) );
// time of last firing
this.fired = System.currentTimeMilis();
}
...
}
public void RemoveMissile(Missile e) {
// as Guest is asked in another answer, this method should remove, not add...
missiles.remove(e);
}
I am trying to make a game in Java and this is my first time dealing with multithreading (well, asides from playing music concurrently via the Clip class.) I have a Canvas class which extends JPanel, but within the Canvas class I also have a KeyListener to take input, shown here:
private class myKeyListener implements KeyListener
{
public void keyPressed(KeyEvent keyEvent)
{
if(keyEvent.getKeyCode() == KeyEvent.VK_ESCAPE){System.exit (0);}
Thread thread3 = new Thread()
{
public void run() {
if(keyEvent.getKeyCode() == KeyEvent.VK_RIGHT){moveX(5, player1);}
if(keyEvent.getKeyCode() == KeyEvent.VK_LEFT){moveX(-5, player1);}
if(keyEvent.getKeyCode() == KeyEvent.VK_UP){moveY(-5, player1);}
if(keyEvent.getKeyCode() == KeyEvent.VK_DOWN){moveY (5, player1);}
}
};
Thread thread4 = new Thread()
{
public void run() {
if(keyEvent.getKeyCode() == KeyEvent.VK_D){moveX(5, player2);}
if(keyEvent.getKeyCode() == KeyEvent.VK_A){moveX(-5, player2);}
if(keyEvent.getKeyCode() == KeyEvent.VK_W){moveY(-5, player2);}
if(keyEvent.getKeyCode() == KeyEvent.VK_S){ moveY(5, player2);}
}
};
Thread thread5 = new Thread()
{
public void run() {
repaint();
}
};
thread3.start();
thread4.start();
thread5.start();
try{
thread3.join();
thread4.join();
thread5.join();
}
catch (Exception e){System.out.println(e);}
repaint();
}
public void keyReleased(KeyEvent keyEvent)
{
}
public void keyTyped(KeyEvent keyEvent)
{
}
}
My goal is to have it so that one can move both players (which are Rectangles) at the same time on the canvas. Currently, one can only move them one at a time, but never both at the same time. This is my first time dealing with multithreading so I apologize in advance if I am making a rookie mistake.
Here is the code.
You need just one thread, to do the "game loop".
import java.awt.*;
import java.awt.event.*;
import javax.swing.JPanel;
import java.util.ArrayList;
public class Canvas2 extends JPanel {
// attributes
private Rectangle player1;
private Rectangle player2;
private ArrayList<KeyEvent> log;
private boolean player1left = false;
private boolean player1right = false;
private boolean player1up = false;
private boolean player1down = false;
private boolean player2left = false;
private boolean player2right = false;
private boolean player2up = false;
private boolean player2down = false;
// constructor
public Canvas2() {
// initialize object
player1 = new Rectangle(50, 50, 50, 50);
player2 = new Rectangle(50, 50, 50, 50);
log = new ArrayList<KeyEvent>();
// set canavs background colour
setBackground(Color.white);
// add the key listener in the constructor of your canavas/panel
addKeyListener(new myKeyListener());
// ensure focus is on this canavas/panel for key operations.
setFocusable(true);
Thread gameLoop = new Thread() {
public void run() {
while (true) {
updatePlayers();
repaint();
pause(10);
}
}
};
gameLoop.start();
}
private void updatePlayers() {
if (player1left) {
moveX(-5, player1);
}
if (player1right) {
moveX(5, player1);
}
if (player1up) {
moveY(-5, player1);
}
if (player1down) {
moveY(5, player1);
}
if (player2left) {
moveX(-5, player2);
}
if (player2right) {
moveX(5, player2);
}
if (player2up) {
moveY(-5, player2);
}
if (player2down) {
moveY(5, player2);
}
}
// painting
public void paintComponent(Graphics graphics) {
super.paintComponent(graphics);
Graphics2D graphics2d = (Graphics2D) graphics;
graphics.setColor(Color.blue);
graphics2d.fill(player1);
graphics2d.fill(player2);
}
// function which essentially re-creates rectangle with varying x
// orientations. (x-movement)
public void moveX(int mutationDistance, Rectangle sampleObject) {
sampleObject.setBounds(sampleObject.x + mutationDistance,
sampleObject.y, sampleObject.width, sampleObject.height);
}
// function which essentially re-creates rectangle with varying y
// orientations. (y-movement)
public void moveY(int mutationDistance, Rectangle sampleObject) {
sampleObject.setBounds(sampleObject.x, sampleObject.y
+ mutationDistance, sampleObject.width, sampleObject.height);
}
// listener
private class myKeyListener implements KeyListener {
// implement all the possible actions on keys
public void keyPressed(final KeyEvent keyEvent) {
if (keyEvent.getKeyCode() == KeyEvent.VK_ESCAPE) {
System.exit(0);
}
if (keyEvent.getKeyCode() == KeyEvent.VK_RIGHT) {
player1right = true;
}
if (keyEvent.getKeyCode() == KeyEvent.VK_LEFT) {
player1left = true;
}
if (keyEvent.getKeyCode() == KeyEvent.VK_UP) {
player1up = true;
}
if (keyEvent.getKeyCode() == KeyEvent.VK_DOWN) {
player1down = true;
}
if (keyEvent.getKeyCode() == KeyEvent.VK_D) {
player2right = true;
}
if (keyEvent.getKeyCode() == KeyEvent.VK_A) {
player2left = true;
}
if (keyEvent.getKeyCode() == KeyEvent.VK_W) {
player2up = true;
}
if (keyEvent.getKeyCode() == KeyEvent.VK_S) {
player2down = true;
}
}
public void keyReleased(KeyEvent keyEvent) {
if (keyEvent.getKeyCode() == KeyEvent.VK_RIGHT) {
player1right = false;
}
if (keyEvent.getKeyCode() == KeyEvent.VK_LEFT) {
player1left = false;
}
if (keyEvent.getKeyCode() == KeyEvent.VK_UP) {
player1up = false;
}
if (keyEvent.getKeyCode() == KeyEvent.VK_DOWN) {
player1down = false;
}
if (keyEvent.getKeyCode() == KeyEvent.VK_D) {
player2right = false;
}
if (keyEvent.getKeyCode() == KeyEvent.VK_A) {
player2left = false;
}
if (keyEvent.getKeyCode() == KeyEvent.VK_W) {
player2up = false;
}
if (keyEvent.getKeyCode() == KeyEvent.VK_S) {
player2down = false;
}
}
public void keyTyped(KeyEvent keyEvent) {
}
}
public static void pause(int secs) {
try {
Thread.sleep(secs);
} catch (Exception e) {
e.printStackTrace();
}
}
}
import java.awt.*;
import java.awt.event.*;
import javax.swing.JPanel;
import java.util.ArrayList;
/**
* This code was originally by the user "UniBrain" from the website:
* http://forum.codecall.net/topic/74377-moving-graphics-across-up-and-down-a-jpanel/?p=652384
*
* but has been modified by me for my own purposes
*/
public class Canvas2 extends JPanel
{
//attributes
private Rectangle player1;
private Rectangle player2;
private ArrayList<KeyEvent> log;
//constructor
public Canvas2()
{
//initialize object
player1 = new Rectangle (50, 50, 50, 50);
player2 = new Rectangle (50, 50, 50, 50);
log = new ArrayList<KeyEvent>();
//set canavs background colour
setBackground (Color.white);
//add the key listener in the constructor of your canavas/panel
addKeyListener(new myKeyListener());
//ensure focus is on this canavas/panel for key operations.
setFocusable(true);
}
//painting
public void paintComponent(Graphics graphics)
{
super.paintComponent(graphics);
Graphics2D graphics2d =(Graphics2D)graphics;
graphics.setColor(Color.blue);
graphics2d.fill(player1);
graphics2d.fill(player2);
}
//function which essentially re-creates rectangle with varying x orientations. (x-movement)
public void moveX(int mutationDistance, Rectangle sampleObject)
{
sampleObject.setBounds(sampleObject.x + mutationDistance, sampleObject.y, sampleObject.width, sampleObject.height);
}
//function which essentially re-creates rectangle with varying y orientations. (y-movement)
public void moveY(int mutationDistance, Rectangle sampleObject)
{
sampleObject.setBounds(sampleObject.x, sampleObject.y + mutationDistance, sampleObject.width, sampleObject.height);
}
public void move(){
/*
* This method of keeping track of key events and using a loop is taken from the user Michael Meyers at
* http://stackoverflow.com/questions/752999/how-do-i-handle-multiple-key-presses-in-java
*/
Thread thread1 = new Thread()
{
public void run() {
for(KeyEvent keyEvent: log){
if(keyEvent.getKeyCode() == KeyEvent.VK_RIGHT){moveX(5, player1);}
if(keyEvent.getKeyCode() == KeyEvent.VK_LEFT){moveX (-5, player1);}
if(keyEvent.getKeyCode() == KeyEvent.VK_UP){moveY (-5, player1);}
if(keyEvent.getKeyCode() == KeyEvent.VK_DOWN){moveY (5, player1);}
}
}
};
Thread thread2 = new Thread()
{
public void run() {
for(KeyEvent keyEvent: log){
if(keyEvent.getKeyCode() == KeyEvent.VK_D){moveX(5, player2);}
if(keyEvent.getKeyCode() == KeyEvent.VK_A){moveX(-5, player2);}
if(keyEvent.getKeyCode() == KeyEvent.VK_W){moveY(-5, player2);}
if(keyEvent.getKeyCode() == KeyEvent.VK_S){moveY(5, player2);}
}
}
};
//Starts the threads
thread1.start();
thread2.start();
//Waits for them to finish
try{
thread1.join();
thread2.join();
log = new ArrayList<KeyEvent>();
}
catch (Exception e){System.out.println(e);}
}
//listener
private class myKeyListener implements KeyListener
{
//implement all the possible actions on keys
public void keyPressed(KeyEvent keyEvent)
{
if(keyEvent.getKeyCode() == KeyEvent.VK_ESCAPE){System.exit (0);}
Thread thread3 = new Thread()
{
public void run() {
if(keyEvent.getKeyCode() == KeyEvent.VK_RIGHT){moveX(5, player1);}
if(keyEvent.getKeyCode() == KeyEvent.VK_LEFT){moveX(-5, player1);}
if(keyEvent.getKeyCode() == KeyEvent.VK_UP){moveY(-5, player1);}
if(keyEvent.getKeyCode() == KeyEvent.VK_DOWN){moveY (5, player1);}
}
};
Thread thread4 = new Thread()
{
public void run() {
if(keyEvent.getKeyCode() == KeyEvent.VK_D){moveX(5, player2);}
if(keyEvent.getKeyCode() == KeyEvent.VK_A){moveX(-5, player2);}
if(keyEvent.getKeyCode() == KeyEvent.VK_W){moveY(-5, player2);}
if(keyEvent.getKeyCode() == KeyEvent.VK_S){ moveY(5, player2);}
}
};
Thread thread5 = new Thread()
{
public void run() {
repaint();
}
};
thread3.start();
thread4.start();
thread5.start();
try{
thread3.join();
thread4.join();
thread5.join();
}
catch (Exception e){System.out.println(e);}
repaint();
}
public void keyReleased(KeyEvent keyEvent)
{
}
public void keyTyped(KeyEvent keyEvent)
{
}
}
public static void pause(int secs){
try{Thread.sleep(secs*0);} catch(Exception e){}
}
}
which is then executed by this class
import javax.swing.JFrame;
import java.awt.Dimension;
/**
* This code was taken from the user "UniBrain" from the website:
* http://forum.codecall.net/topic/74377-moving-graphics-across-up-and-down-a-jpanel/?p=652384
*/
public class Display
{
public static void main ( String [ ] arguments )
{
JFrame frame = new JFrame("key listener demo");
Canvas2 panel = new Canvas2();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel);
frame.setContentPane(panel);
frame.setPreferredSize(new Dimension(800, 600));
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.pack();
}
}
I am programming a game and when he go left the image should rotate left but it is not it is giving me and error:
Exception in thread "Thread-2" java.lang.NullPointerException
at Schoo.NewGame.TheRealGame.turnPlayer(TheRealGame.java:365)
at Schoo.NewGame.TheRealGame$2.run(TheRealGame.java:154)
at java.lang.Thread.run(Unknown Source)
Yes, i know that java.lang.NullPointerException means something is null but nothing should be null anyway here is the code on line 365:
g2.rotate(90.0+90.0+90.0);
line 154 just runs the method:
public static void turnPlayer(Direction d){
Graphics g = playerImage.getGraphics();
Graphics2D g2 = (Graphics2D) g;
if (d == Direction.LEFT){
if (p.getDirection() == Direction.LEFT){
return;
}
if (p.getDirection() == Direction.UP){
g2.rotate(90.0);
}
if (p.getDirection() == Direction.RIGHT){
g2.rotate(90.0+90.0);
}
if (p.getDirection() == Direction.DOWN){
g2.rotate(90.0+90.0+90.0);
}
p.setDirection(d);
playerImage.repaint();
}
if (d == Direction.UP){
if (p.getDirection() == Direction.UP){
return;
}
if (p.getDirection() == Direction.RIGHT){
g2.rotate(90.0);
}
if (p.getDirection() == Direction.DOWN){
g2.rotate(90.0+90.0);
}
if (p.getDirection() == Direction.LEFT){
g2.rotate(90.0+90.0+90.0);
}
p.setDirection(d);
playerImage.repaint();
}
if (d == Direction.RIGHT){
if (p.getDirection() == Direction.RIGHT){
return;
}
if (p.getDirection() == Direction.DOWN){
g2.rotate(90.0);
}
if (p.getDirection() == Direction.LEFT){
g2.rotate(90.0+90.0);
}
if (p.getDirection() == Direction.UP){
g2.rotate(90.0+90.0+90.0);
}
p.setDirection(d);
playerImage.repaint();
}
if (d == Direction.DOWN){
if (p.getDirection() == Direction.DOWN){
return;
}
if (p.getDirection() == Direction.LEFT){
g2.rotate(90.0);
}
if (p.getDirection() == Direction.UP){
g2.rotate(90.0+90.0);
}
if (p.getDirection() == Direction.RIGHT){
g2.rotate(90.0+90.0+90.0);
}
p.setDirection(d);
playerImage.repaint();
}
RepaintPlayer();
f.repaint();
playerImage.repaint();
}
and if you need the whole class:
public class TheRealGame{
private static boolean running = false;
private static boolean paused = false;
private static boolean right = false, left = false, up = false, down = false;
private static JFrame f;
private static ArrayList<JLabel> ae = new ArrayList<JLabel>();
private static Player p;
private static Playere pt;
private static JLabel playerImage;
private static boolean info = false;
private static JLabel iy, ix, im, in, iu;
public static void main(Playere playertype){
pt = playertype;
p = new Player(pt);
f = new JFrame();
f.setVisible(true);
f.setSize(700, 700);
f.setResizable(false);
f.setLocationRelativeTo(null);
f.addKeyListener(new KeyListener(){
#Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_UP || e.getKeyChar() == KeyEvent.VK_W){
up = true;
}
if (e.getKeyCode() == KeyEvent.VK_LEFT || e.getKeyChar() == KeyEvent.VK_A){
left = true;
}
if (e.getKeyCode() == KeyEvent.VK_DOWN || e.getKeyChar() == KeyEvent.VK_S){
down = true;
}
if (e.getKeyCode() == KeyEvent.VK_RIGHT || e.getKeyChar() == KeyEvent.VK_D){
right = true;
}
if (e.getKeyCode() == KeyEvent.VK_SPACE || e.getKeyCode() == KeyEvent.VK_ENTER){
p.attack();
}
if (e.getKeyCode() == KeyEvent.VK_F3){
if (info == true){
info = false;
iy.setVisible(false);
ix.setVisible(false);
im.setVisible(false);
in.setVisible(false);
iu.setVisible(false);
}else if (info == false){
info = true;
iy.setVisible(true);
ix.setVisible(true);
im.setVisible(true);
in.setVisible(true);
iu.setVisible(true);
}
}
}
#Override
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_UP || e.getKeyChar() == KeyEvent.VK_W){
up = false;
}
if (e.getKeyCode() == KeyEvent.VK_LEFT || e.getKeyChar() == KeyEvent.VK_A){
left = false;
}
if (e.getKeyCode() == KeyEvent.VK_DOWN || e.getKeyChar() == KeyEvent.VK_S){
down = false;
}
if (e.getKeyCode() == KeyEvent.VK_RIGHT || e.getKeyChar() == KeyEvent.VK_D){
right = false;
}
if (e.getKeyCode() == KeyEvent.VK_SPACE || e.getKeyCode() == KeyEvent.VK_ENTER){
p.attack();
}
}
#Override
public void keyTyped(KeyEvent e) {
}
});
iy = new JLabel();
ix = new JLabel();
im = new JLabel();
in = new JLabel();
iu = new JLabel();
iy.setLocation(0, 10);
ix.setLocation(0, 20);
im.setLocation(0, 30);
in.setLocation(0, 40);
iu.setLocation(0, 50);
iy.setBounds((int) iy.getLocation().getX(), (int) iy.getLocation().getY(), 100, 15);
ix.setBounds((int) ix.getLocation().getX(), (int) ix.getLocation().getY(), 100, 15);
im.setBounds((int) im.getLocation().getX(), (int) im.getLocation().getY(), 100, 15);
in.setBounds((int) in.getLocation().getX(), (int) in.getLocation().getY(), 100, 15);
iu.setBounds((int) iu.getLocation().getX(), (int) iu.getLocation().getY(), 100, 15);
f.add(ix);
f.add(iy);
f.add(im);
f.add(in);
f.add(iu);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("free play - tokyo ghoul");
Start();
p.Paint();
}
public static void resume(){
if (paused == false){
return;
}
}
public static void pause(){
if (paused == true){
return;
}
}
public static void Stop(){
if (running == false){
return;
}
running = false;
}
public static void Start(){
running = true;
new Thread(new Runnable(){
#Override
public void run() {
int last = 0, u = 0;
while (running == true){
if (paused != true){
if (up == true){
p.move(p.getX(), p.getY()-1);
if (p.getDirection() != Direction.UP){
turnPlayer(Direction.UP);
}
}
if (down == true){
p.move(p.getX(), p.getY()+1);
if (p.getDirection() != Direction.DOWN){
turnPlayer(Direction.DOWN);
}
}
if (left == true){
p.move(p.getX()-1, p.getY());
if (p.getDirection() != Direction.LEFT){
turnPlayer(Direction.LEFT);
}
}
if (right == true){
p.move(p.getX()+1, p.getY());
if (p.getDirection() != Direction.RIGHT){
turnPlayer(Direction.RIGHT);
}
}
if (info == true){
int l = 10-last;
iy.setText("y: "+p.getY());
ix.setText("x: "+p.getX());
im.setText("enemys: "+ae.size());
in.setText("next enemy: "+l);
iu.setText("Updated "+u+" times.");
RefreshInfo();
}
if (p.getY() == -337){
p.move(p.getX(), 337);
}
if (p.getY() == 337){
p.move(p.getX(), -337);
}
if (p.getX() == -349){
p.move(349, p.getY());
}
if (p.getX() == 349){
p.move(-349, p.getY());
}
RepaintAllLabels();
Enemy.UpdateAll();
if (info != true){
f.repaint();
}
if (last == 10){
Random r = new Random();
int x = 1+r.nextInt(2), y = 1+r.nextInt(2), distance = 1+r.nextInt(570), nx = 0, ny = 0;
if (x == 1){
}
last = 0;
}
last++;
u++;
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
public static void RefreshInfo(){
f.remove(iy);
f.remove(ix);
f.remove(im);
f.remove(in);
f.remove(iu);
f.add(ix);
f.add(iy);
f.add(im);
f.add(in);
f.add(iu);
iy.setLocation(0, 10);
ix.setLocation(0, 20);
im.setLocation(0, 30);
in.setLocation(0, 40);
iu.setLocation(0, 50);
iu.setBounds((int) iu.getLocation().getX(), (int) iu.getLocation().getY(), 100, 15);
iy.setBounds((int) iy.getLocation().getX(), (int) iy.getLocation().getY(), 100, 15);
ix.setBounds((int) ix.getLocation().getX(), (int) ix.getLocation().getY(), 100, 15);
im.setBounds((int) im.getLocation().getX(), (int) im.getLocation().getY(), 100, 15);
in.setBounds((int) in.getLocation().getX(), (int) in.getLocation().getY(), 100, 15);
f.repaint();
}
public static void UpdateAll(){
}
public static void Paint(JLabel imgs, int x, int y, File file){
ImageIcon img = new ImageIcon(file.getPath());
imgs.setBounds(x, y, img.getIconWidth(), img.getIconHeight());
imgs.setLocation(x, y);
imgs.setVisible(true);
f.add(imgs);
imgs.setVisible(true);
}
public static void Repaint(JLabel l){
f.remove(l);
l.setBounds((int)l.getLocation().getX(), (int)l.getLocation().getY(), l.getWidth(), l.getHeight());
f.add(l);
}
public static void addAE(JLabel l){
ae.add(l);
}
public static void RepaintAllLabels(){
for (int i = 0; i < ae.size(); i++){
Repaint(ae.get(i));
}
}
public static void MovePlayer(int x, int y){
playerImage.setLocation(x, y);
playerImage.repaint();
f.repaint();
}
public static void RepaintPlayer(){
if (p.isAttacking()){
if (pt == Playere.Kaneki){
ImageIcon img = new ImageIcon(StartMenu.class.getResource("/Schoo/NewGame/Kaneki_hit.png"));
playerImage = new JLabel(img);
}
if (pt == Playere.Touka){
ImageIcon img = new ImageIcon(StartMenu.class.getResource("/Schoo/NewGame/touka_hit.png"));
playerImage = new JLabel(img);
}
}else{
if (pt == Playere.Kaneki){
ImageIcon img = new ImageIcon(StartMenu.class.getResource("/Schoo/NewGame/Kaneki_walk.png"));
playerImage = new JLabel(img);
}
if (pt == Playere.Touka){
ImageIcon img = new ImageIcon(StartMenu.class.getResource("/Schoo/NewGame/touka_walk.png"));
playerImage = new JLabel(img);
}
}
playerImage.setVisible(false);
playerImage.repaint();
playerImage.setVisible(true);
playerImage.repaint();
playerImage.setVisible(true);
MovePlayer(p.getX(), p.getY());
f.repaint();
}
public static void paintplayer(){
if (pt == Playere.Kaneki){
playerImage = new JLabel(new ImageIcon(StartMenu.class.getResource("/schoo/NewGame/kaneki_walk.png")));
if (playerImage == null){
System.out.println("[ERROR THIS WAS THE ERROR THE WHOLE TIME!!");
return;
}
ImageIcon imgs = new ImageIcon(StartMenu.class.getResource("/schoo/NewGame/kaneki_walk.png"));
playerImage.setBounds(p.getX(), p.getY(), imgs.getIconWidth(), imgs.getIconHeight());
playerImage.setLocation(0, 0);
playerImage.setVisible(true);
f.add(playerImage);
playerImage.setVisible(true);
}
if (pt == Playere.Touka){
playerImage = new JLabel(new ImageIcon(StartMenu.class.getResource("/schoo/NewGame/touka_walk.png")));
playerImage.setBounds(p.getX(), p.getY(), new ImageIcon(StartMenu.class.getResource("/schoo/NewGame/touka_walk.png")).getIconWidth(), new ImageIcon(StartMenu.class.getResource("/schoo/NewGame/touka_walk.png")).getIconHeight());
playerImage.setLocation(p.getX(), p.getY());
playerImage.setVisible(true);
f.add(playerImage);
playerImage.setVisible(true);
}
}
public static void turnPlayer(Direction d){
Graphics g = playerImage.getGraphics();
Graphics2D g2 = (Graphics2D) g;
if (d == Direction.LEFT){
if (p.getDirection() == Direction.LEFT){
return;
}
if (p.getDirection() == Direction.UP){
g2.rotate(90.0);
}
if (p.getDirection() == Direction.RIGHT){
g2.rotate(90.0+90.0);
}
if (p.getDirection() == Direction.DOWN){
g2.rotate(90.0+90.0+90.0);
}
p.setDirection(d);
playerImage.repaint();
}
if (d == Direction.UP){
if (p.getDirection() == Direction.UP){
return;
}
if (p.getDirection() == Direction.RIGHT){
g2.rotate(90.0);
}
if (p.getDirection() == Direction.DOWN){
g2.rotate(90.0+90.0);
}
if (p.getDirection() == Direction.LEFT){
g2.rotate(90.0+90.0+90.0);
}
p.setDirection(d);
playerImage.repaint();
}
if (d == Direction.RIGHT){
if (p.getDirection() == Direction.RIGHT){
return;
}
if (p.getDirection() == Direction.DOWN){
g2.rotate(90.0);
}
if (p.getDirection() == Direction.LEFT){
g2.rotate(90.0+90.0);
}
if (p.getDirection() == Direction.UP){
g2.rotate(90.0+90.0+90.0);
}
p.setDirection(d);
playerImage.repaint();
}
if (d == Direction.DOWN){
if (p.getDirection() == Direction.DOWN){
return;
}
if (p.getDirection() == Direction.LEFT){
g2.rotate(90.0);
}
if (p.getDirection() == Direction.UP){
g2.rotate(90.0+90.0);
}
if (p.getDirection() == Direction.RIGHT){
g2.rotate(90.0+90.0+90.0);
}
p.setDirection(d);
playerImage.repaint();
}
RepaintPlayer();
f.repaint();
playerImage.repaint();
}
public static enum Direction{
LEFT, UP, RIGHT, DOWN;
}
}
Thank you for taking your time to help me!
You can use the Rotated Icon. This class does all the rotation logic for you. You just need to specify the degrees of rotation.
So the basic code to create the label would be:
RotatedIcon icon = new RotatedIcon( new ImageIcon(...) );
JLabel player = new JLabel( icon );
Then when you want to rotate the Icon you can use:
icon.setDegrees(...);
player.repaint();
That's not how you do Swing Graphics -- you shouldn't be calling getGraphics() on a component since there is great risk that the object will either be null or non-functioning. Instead if this were my program, I'd get the actual image used, rotate it in all 4 directions (3 plus the original), make ImageIcons out of these images, store them in a collection, or better a HashMap<Direction, Icon>, say called playerDirectionIconMap, and then use them without fear. Then to get the proper icon, I'd just call something like,
// this method should probably not be static
public void turnPlayer(Direction d){
playerImage.setIcon(playerDirectionIconMap.get(p.getDirection()));
// .... other code?
}
Note that the turnPlayer(...) method should not be static as this suggests a broken design that needs to be fixed.
Also note that:
The rotate method uses radians and not degrees, so instead of 90.0, use Math.PI / 2.
You will want to use the rotate method that takes a center point so that your rotation isn't around 0, 0.