Chess Code Split [closed] - java

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
right now I am developing a chess game in java and have been writing the whole game in one java file without doing subclasses and I was hoping I could get some help with that
I want to separate the moves of all the pieces into a new file
can someone show me how to do that
This is the whole file below it is called ChessFrame,
I need help putting all the piece moves in a separate file called ChessMovement.java
I have tryed just taken out the movement but then that breaks everything I could really do with someone showing me
ChessFrame.java
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
public class ChessFrame extends JFrame implements MouseListener, MouseMotionListener {
JLayeredPane layeredPane;
JPanel chessBoard;
JLabel chessPiece;
int xAdjustment;
int yAdjustment;
int startX;
int startY;
int initialX;
int initialY;
JPanel panels;
JLabel pieces;
public ChessFrame() {
Dimension boardSize = new Dimension(600, 600);
// Use a Layered Pane for this application
layeredPane = new JLayeredPane();
getContentPane().add(layeredPane);
layeredPane.setPreferredSize(boardSize);
layeredPane.addMouseListener(this);
layeredPane.addMouseMotionListener(this);
//Add a chess board to the Layered Pane
chessBoard = new JPanel();
layeredPane.add(chessBoard, JLayeredPane.DEFAULT_LAYER);
chessBoard.setLayout(new GridLayout(8, 8));
chessBoard.setPreferredSize(boardSize);
chessBoard.setBounds(0, 0, boardSize.width, boardSize.height);
for (int i = 0; i < 64; i++) {
JPanel square = new JPanel(new BorderLayout());
chessBoard.add(square);
int row = (i / 8) % 2;
if (row == 0) {
square.setBackground(i % 2 == 0 ? Color.white : Color.gray);
} else {
square.setBackground(i % 2 == 0 ? Color.gray : Color.white);
}
}
// Setting up the Initial Chess board.
for (int i = 8; i < 16; i++) {
pieces = new JLabel(new ImageIcon("WhitePawn.png"));
panels = (JPanel) chessBoard.getComponent(i);
panels.add(pieces);
}
pieces = new JLabel(new ImageIcon("WhiteRook.png"));
panels = (JPanel) chessBoard.getComponent(0);
panels.add(pieces);
pieces = new JLabel(new ImageIcon("WhiteKnight.png"));
panels = (JPanel) chessBoard.getComponent(1);
panels.add(pieces);
pieces = new JLabel(new ImageIcon("WhiteKnight.png"));
panels = (JPanel) chessBoard.getComponent(6);
panels.add(pieces);
pieces = new JLabel(new ImageIcon("WhiteBishup.png"));
panels = (JPanel) chessBoard.getComponent(2);
panels.add(pieces);
pieces = new JLabel(new ImageIcon("WhiteBishup.png"));
panels = (JPanel) chessBoard.getComponent(5);
panels.add(pieces);
pieces = new JLabel(new ImageIcon("WhiteKing.png"));
panels = (JPanel) chessBoard.getComponent(3);
panels.add(pieces);
pieces = new JLabel(new ImageIcon("WhiteQueen.png"));
panels = (JPanel) chessBoard.getComponent(4);
panels.add(pieces);
pieces = new JLabel(new ImageIcon("WhiteRook.png"));
panels = (JPanel) chessBoard.getComponent(7);
panels.add(pieces);
for (int i = 48; i < 56; i++) {
pieces = new JLabel(new ImageIcon("BlackPawn.png"));
panels = (JPanel) chessBoard.getComponent(i);
panels.add(pieces);
}
pieces = new JLabel(new ImageIcon("BlackRook.png"));
panels = (JPanel) chessBoard.getComponent(56);
panels.add(pieces);
pieces = new JLabel(new ImageIcon("BlackKnight.png"));
panels = (JPanel) chessBoard.getComponent(57);
panels.add(pieces);
pieces = new JLabel(new ImageIcon("BlackKnight.png"));
panels = (JPanel) chessBoard.getComponent(62);
panels.add(pieces);
pieces = new JLabel(new ImageIcon("BlackBishup.png"));
panels = (JPanel) chessBoard.getComponent(58);
panels.add(pieces);
pieces = new JLabel(new ImageIcon("BlackBishup.png"));
panels = (JPanel) chessBoard.getComponent(61);
panels.add(pieces);
pieces = new JLabel(new ImageIcon("BlackKing.png"));
panels = (JPanel) chessBoard.getComponent(59);
panels.add(pieces);
pieces = new JLabel(new ImageIcon("BlackQueen.png"));
panels = (JPanel) chessBoard.getComponent(60);
panels.add(pieces);
pieces = new JLabel(new ImageIcon("BlackRook.png"));
panels = (JPanel) chessBoard.getComponent(63);
panels.add(pieces);
}
private Boolean piecePresent(int x, int y) {
Component c = chessBoard.findComponentAt(x, y);
if (c instanceof JPanel) {
return false;
} else {
return true;
}
}
//Check if a piece is a Black piece.
private Boolean checkWhiteOponent(int newX, int newY) {
Boolean oponent;
Component c1 = chessBoard.findComponentAt(newX, newY);
JLabel awaitingPiece = (JLabel) c1;
String tmp1 = awaitingPiece.getIcon().toString();
if (((tmp1.contains("Black")))) {
oponent = true;
} else {
oponent = false;
}
return oponent;
}
//Check if a piece is a White piece.
private Boolean checkBlackOponent(int newX, int newY) {
Boolean oponent;
Component c1 = chessBoard.findComponentAt(newX, newY);
JLabel awaitingPiece = (JLabel) c1;
String tmp1 = awaitingPiece.getIcon().toString();
if (((tmp1.contains("White")))) {
oponent = true;
} else {
oponent = false;
}
return oponent;
}
public void mousePressed(MouseEvent e) {
chessPiece = null;
Component c = chessBoard.findComponentAt(e.getX(), e.getY());
if (c instanceof JPanel) {
return;
}
Point parentLocation = c.getParent().getLocation();
xAdjustment = parentLocation.x - e.getX();
yAdjustment = parentLocation.y - e.getY();
chessPiece = (JLabel) c;
initialX = e.getX();
initialY = e.getY();
startX = (e.getX() / 75);
startY = (e.getY() / 75);
chessPiece.setLocation(e.getX() + xAdjustment, e.getY() + yAdjustment);
chessPiece.setSize(chessPiece.getWidth(), chessPiece.getHeight());
layeredPane.add(chessPiece, JLayeredPane.DRAG_LAYER);
}
public void mouseDragged(MouseEvent me) {
if (chessPiece == null) {
return;
}
chessPiece.setLocation(me.getX() + xAdjustment, me.getY() + yAdjustment);
}
public void mouseReleased(MouseEvent e) {
if (chessPiece == null) {
return;
}
chessPiece.setVisible(false);
Boolean success = false;
Component c = chessBoard.findComponentAt(e.getX(), e.getY());
String tmp = chessPiece.getIcon().toString();
String pieceName = tmp.substring(0, (tmp.length() - 4));
Boolean validMove = false;
//Pawn Moves
//White Pawn
if (pieceName.equals("WhitePawn")) {
if (startY == 1) {
if ((startX == (e.getX() / 75)) && ((((e.getY() / 75) - startY) == 1) || ((e.getY() / 75) - startY) == 2)) {
if ((((e.getY() / 75) - startY) == 2)) {
if ((!piecePresent(e.getX(), (e.getY()))) && (!piecePresent(e.getX(), (e.getY() + 75)))) {
validMove = true;
} else {
validMove = false;
}
} else {
if ((!piecePresent(e.getX(), (e.getY())))) {
validMove = true;
} else {
validMove = false;
}
}
} else {
validMove = false;
}
} else {
int newY = e.getY() / 75;
int newX = e.getX() / 75;
if ((startX - 1 >= 0) || (startX + 1 <= 7)) {
if ((piecePresent(e.getX(), (e.getY()))) && ((((newX == (startX + 1) && (startX + 1 <= 7))) || ((newX == (startX - 1)) && (startX - 1 >= 0))))) {
if (checkWhiteOponent(e.getX(), e.getY())) {
validMove = true;
if (startY == 6) {
success = true;
}
} else {
validMove = false;
}
} else {
if (!piecePresent(e.getX(), (e.getY()))) {
if ((startX == (e.getX() / 75)) && ((e.getY() / 75) - startY) == 1) {
if (startY == 6) {
success = true;
}
validMove = true;
} else {
validMove = false;
}
} else {
validMove = false;
}
}
} else {
validMove = false;
}
}
}
//Black Pawn
if (pieceName.equals("BlackPawn")) {
if (startY == 6) {
if ((startX == (e.getX() / 75)) && ((((e.getY() / 75) - startY) == -1) || ((e.getY() / 75) - startY) == -2)) {
if ((((e.getY() / 75) - startY) == -2)) {
if ((!piecePresent(e.getX(), (e.getY()))) && (!piecePresent(e.getX(), (e.getY() + 75)))) {
validMove = true;
} else {
validMove = false;
}
} else {
if ((!piecePresent(e.getX(), (e.getY())))) {
validMove = true;
} else {
validMove = false;
}
}
} else {
validMove = false;
}
} else {
int newY = e.getY() / 75;
int newX = e.getX() / 75;
if ((startX - 1 >= 0) || (startX + 1 <= 7)) {
if ((piecePresent(e.getX(), (e.getY()))) && ((((newX == (startX + 1) && (startX + 1 <= 7))) || ((newX == (startX - 1)) && (startX - 1 >= 0))))) {
if (checkBlackOponent(e.getX(), e.getY())) {
validMove = true;
if (startY == 1) {
success = true;
}
} else {
validMove = false;
}
} else {
if (!piecePresent(e.getX(), (e.getY()))) {
if ((startX == (e.getX() / 75)) && ((e.getY() / 75) - startY) == -1) {
if (startY == 2) {
success = true;
}
validMove = true;
} else {
validMove = false;
}
} else {
validMove = false;
}
}
} else {
validMove = false;
}
}
}
//End of Pawn Moves
//Knight Moves
//White Knight Code
else if (pieceName.contains("WhiteKnight")) {
// next we need to get the new coordinates for where the piece is being dropped.
int newY = e.getY() / 75;
int newX = e.getX() / 75;
// We need to make sure that the piece is being put back on the board...if its not being on
// the board why would we want to check anything else!
if (((newX < 0) || (newX > 7)) || ((newY < 0) || (newY > 7))) {
validMove = false;
} else {
if (((newX == startX + 1) && (newY == startY + 2)) || ((newX == startX - 1) && (newY == startY + 2)) || ((newX == startX + 2) && (newY == startY + 1)) || ((newX == startX - 2) && (newY == startY + 1)) || ((newX == startX + 1) && (newY == startY - 2)) || ((newX == startX - 1) && (newY == startY - 2)) || ((newX == startX + 2) && (newY == startY - 1)) || ((newX == startX - 2) && (newY == startY - 1))) {
validMove = true;
if (piecePresent(e.getX(), (e.getY()))) {
if (pieceName.contains("White")) {
if (checkWhiteOponent(e.getX(), e.getY())) {
validMove = true;
} else {
validMove = false;
}
} else {
if (checkBlackOponent(e.getX(), e.getY())) {
validMove = true;
} else {
validMove = false;
}
}
}
} else {
validMove = false;
}
}
} //Black Knight Code
else if (pieceName.contains("BlackKnight")) {
// next we need to get the new coordinates for where the piece is being dropped.
int newY = e.getY() / 75;
int newX = e.getX() / 75;
// We need to make sure that the piece is being put back on the board...if its not being on
// the board why would we want to check anything else!
if (((newX < 0) || (newX > 7)) || ((newY < 0) || (newY > 7))) {
validMove = false;
} else {
if (((newX == startX + 1) && (newY == startY + 2)) || ((newX == startX - 1) && (newY == startY + 2)) || ((newX == startX + 2) && (newY == startY + 1)) || ((newX == startX - 2) && (newY == startY + 1)) || ((newX == startX + 1) && (newY == startY - 2)) || ((newX == startX - 1) && (newY == startY - 2)) || ((newX == startX + 2) && (newY == startY - 1)) || ((newX == startX - 2) && (newY == startY - 1))) {
validMove = true;
if (piecePresent(e.getX(), (e.getY()))) {
if (pieceName.contains("Black")) {
if (checkBlackOponent(e.getX(), e.getY())) {
validMove = true;
} else {
validMove = false;
}
} else {
if (checkWhiteOponent(e.getX(), e.getY())) {
validMove = true;
} else {
validMove = false;
}
}
}
} else {
validMove = false;
}
}
}
//End of Knight Code
//Bishop Code
//White Bishup
else if (pieceName.contains("WhiteBishup")) {
int newY = e.getY() / 75;
int newX = e.getX() / 75;
boolean inTheWay = false;
int distance = Math.abs(startX - newX);
if (((newX < 0) || (newX > 7)) || ((newY < 0) || (newY > 7))) {
validMove = false;
} else {
validMove = true;
if (Math.abs(startX - newX) == Math.abs(startY - newY)) {
if ((startX - newX < 0) && (startY - newY < 0)) {
for (int i = 0; i < distance; i++) {
if (piecePresent((initialX + (i * 75)), (initialY + (i * 75)))) {
inTheWay = true;
}
}
} else if ((startX - newX < 0) && (startY - newY > 0)) {
for (int i = 0; i < distance; i++) {
if (piecePresent((initialX + (i * 75)), (initialY - (i * 75)))) {
inTheWay = true;
}
}
} else if ((startX - newX > 0) && (startY - newY > 0)) {
for (int i = 0; i < distance; i++) {
if (piecePresent((initialX - (i * 75)), (initialY - (i * 75)))) {
inTheWay = true;
}
}
} else if ((startX - newX > 0) && (startY - newY < 0)) {
for (int i = 0; i < distance; i++) {
if (piecePresent((initialX - (i * 75)), (initialY + (i * 75)))) {
inTheWay = true;
}
}
}
if (inTheWay) {
validMove = false;
} else {
if (piecePresent(e.getX(), (e.getY()))) {
if (pieceName.contains("White")) {
if (checkWhiteOponent(e.getX(), e.getY())) {
validMove = true;
} else {
validMove = false;
}
} else {
if (checkBlackOponent(e.getX(), e.getY())) {
validMove = true;
} else {
validMove = false;
}
}
} else {
validMove = true;
}
}
} else { // the move that is being tried is not a diagonal move...
validMove = false;
}
}
} //Black Bishup
else if (pieceName.contains("BlackBishup")) {
int newY = e.getY() / 75;
int newX = e.getX() / 75;
boolean inTheWay = false;
int distance = Math.abs(startX - newX);
if (((newX < 0) || (newX > 7)) || ((newY < 0) || (newY > 7))) {
validMove = false;
} else {
validMove = true;
if (Math.abs(startX - newX) == Math.abs(startY - newY)) {
if ((startX - newX < 0) && (startY - newY < 0)) {
for (int i = 0; i < distance; i++) {
if (piecePresent((initialX + (i * 75)), (initialY + (i * 75)))) {
inTheWay = true;
}
}
} else if ((startX - newX < 0) && (startY - newY > 0)) {
for (int i = 0; i < distance; i++) {
if (piecePresent((initialX + (i * 75)), (initialY - (i * 75)))) {
inTheWay = true;
}
}
} else if ((startX - newX > 0) && (startY - newY > 0)) {
for (int i = 0; i < distance; i++) {
if (piecePresent((initialX - (i * 75)), (initialY - (i * 75)))) {
inTheWay = true;
}
}
} else if ((startX - newX > 0) && (startY - newY < 0)) {
for (int i = 0; i < distance; i++) {
if (piecePresent((initialX - (i * 75)), (initialY + (i * 75)))) {
inTheWay = true;
}
}
}
if (inTheWay) {
validMove = false;
} else {
if (piecePresent(e.getX(), (e.getY()))) {
if (pieceName.contains("Black")) {
if (checkBlackOponent(e.getX(), e.getY())) {
validMove = true;
} else {
validMove = false;
}
} else {
if (checkWhiteOponent(e.getX(), e.getY())) {
validMove = true;
} else {
validMove = false;
}
}
} else {
validMove = true;
}
}
} else { // the move that is being tried is not a diagonal move...
validMove = false;
}
}
}
//End of Bishup Code
//Changes to new pawn Piece and Validates Move
if(!validMove){
int location=0;
if(startY ==0){
location = startX;
}
else{
location = (startY*8)+startX;
}
String pieceLocation = pieceName+".png";
pieces = new JLabel( new ImageIcon(pieceLocation) );
panels = (JPanel)chessBoard.getComponent(location);
panels.add(pieces);
}
else{
if(success){
if (c instanceof JLabel){
Container parent = c.getParent();
parent.remove(0);
String promoteTo;
do {
promoteTo = (String) JOptionPane.showInputDialog(null,
"Promote Pawn to :", "Pawn Promotion",
JOptionPane.QUESTION_MESSAGE, null,
new String[]{"Queen", "Bishup", "Knight", "Rook"}, "Queen");
} while (promoteTo == null);
String newPiece = null;
int location = 0;
if (pieceName.contains("White"))
{
location = 56 + (e.getX()/75);
newPiece = "White"+promoteTo;
}
else
{
location = (e.getX()/75);
newPiece = "Black"+promoteTo;
}
pieces = new JLabel( new ImageIcon(newPiece+".png") );
parent = (JPanel)chessBoard.getComponent(location);
parent.add(pieces);
validate();
repaint();
}
}
else{
if (c instanceof JLabel){
Container parent = c.getParent();
parent.remove(0);
parent.add( chessPiece );
}
else {
Container parent = (Container)c;
parent.add( chessPiece );
}
chessPiece.setVisible(true);
}
}
}
public void mouseClicked(MouseEvent e) {
}
public void mouseMoved(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public static void main(String[] args) {
JFrame frame = new ChessFrame();
frame.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
frame.pack();
frame.setResizable(true);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
Any help would be great the code currently has no errors but I dont want to go any further til I have it separated out
thanks for any help

You need to create a Piece class, which has subclasses for all the piece types. Then create a FactoryPieceFactory.getPiece(pieceName, x pos, y pos, chessboard) to get those pieces, and implement a move() method on it which takes your new position, and does all the validation. This leaves your UI logic for rendering the moves here, but pushes the move logic down into the piece objects.
You will probably change this later to create a ChessBoard object, which will allow you to get a piece by it's x,y coordinates, and thus not know the piece's name. chessBoard.getPiece(x,y).move(newX, newY); That will allow you validate moves, plus deal with captures etc, calling back to the board to remove opposing pieces.

You mixed game-logic with GUI elements. You should use the concept of MVC. To refractor your program at this state is a question too unspecific.

Related

Intersect function stops working after the first intersect

im making a game, but i ran into a problem while working with the function "intersect".
the senario looks like this; i've made a game where the player is a rectangle were the objective is to kill the enemy rectangle. The enemy "boss" rectangle has two "simulations" that simulate a movement and an attack these simulations are driven by vectors. The movement is horizantally back and forth and the attack is in a vertical maner, a charge type of deal. The boss also has a rectangular target area where if itersected the "boss" will charge across the screen.
now the problem comes when i tried to make it so that if the player intersects with the rectangular target area the "boss" will attack/charge. The boss attack/charge the first time the player intersects but not after that. I want the boss to follow the same pantern, is that he should only be able to go from side to side horizantaly and if Target area intersected; attack/charge verticaly.
( i will include some code bellow. sorry if my english is bad. )
first comes the main:
boss b;
Character C;
void setup(){
C = new Character();
b = new boss();
}
void draw(){
if (play) {
b.simulate(); //horizantal movement
}
if (b.start) {
b.sim(); //boss vertical attack
}
if (b.intersects(C)){
play = false;
b.start = true;
}
C.character(); //player
b.bounce(); //makes it bounce if horizantal. and stop if vertical
b.Display(); //boss
b.display(); //boss target area
}
Next comes the boss:
class boss {
int x = 10 ;
int y = 10 ;
boolean start = false;
int RW = 50;
int RH = 700;
boolean up = false;
boolean down = true;
boss() {
Location = new PVector( x+25, y ); //vector for the location of the boss
Velocity = new PVector( 5, 0 ); // vector for horizaltal movement
speed = new PVector( 0, 10 ); // vector for vertical down movement
speed2 = new PVector(0, -10); // vector for vertical up movement
}
void bounce() {
if ((Location.x == width) ||(Location.x == 0)) { //horizantal movement bounce on screen edge
Velocity.x = Velocity.x * -1;
}
if ((Location.y == 650) || (Location.y == 0)) {
start = false; //makes boss stop if reaches botton or top of the screen
play = true;
if (Location.y == 650) {
RH = -700;
up = true;
down = false; //specificly if it reaches top of screen
}
if (Location.y == 0) {
RH = 700;
down = true; //specificly if it reaches bottom of screen
up = false;
}
}
}
void simulate() {
Location.add(Velocity); //simulates horizantal movement
}
void sim() {
if (down) {
Location.add(speed); //simulates up and down attacking movemnet
}
if (up) {
Location.add(speed2);
}
}
boolean intersects(Character C) {
return Location.x < C.x + C.w && C.x < Location.x + RW &&
Location.y < C.y + C.h && C.y < Location.y + RH; //intersect between player and boss targeting area
}
void Display() {
rect( Location.x, Location.y, 50, 50 ); //boss
}
void display() {
rect( Location.x, Location.y+50, RW, RH ); //boss targeting area
}
}
if anything is unclear i will gladly clear up any confusion. :)
Thanks for sharing the code. It made it much easier.
When I comment this piece (not the if-condition the reset of start after the if)
if ((Location.y == 650) || (Location.y == 0)) {
// start = false;
then the boss starts going back up top and still calls intersects the Character when the co-ordinates match. However, post this the boss keeps bouncing up and down.
There is surely more work to be done on this to take account of the bullets fired and the hits to boss.
Hope this helps. :) It was fun debugging this code. I had never used PDE before this.
ok, here is the "edit"..
Now,
Good News: I can make it go in both directions only when it intersects
Bad News: It keeps going to the other side as long as it is intersecting. So if the Character is stationary then boss keeps intersecting and passing to the other side at least 8-10 times in the current speed.
Anyways, here is the summary. I added and isAttacking flag that tells the program to not stop the boss from crossing over if it has reached the bottom of the frame. The other thing I changed was the intersection condition. Now it just checks for intersection on the X-Axis. If you must compare intersection on the Y-Axis too then intersects is where you need to change & test.
After the long explanation :P Here is the code. Hope this is better.
Main
boss b;
Character C;
Inventory I;
Bullet B;
int previousKey = 0;
int lastKey;
int lastKeyCode;
void setup() {
C = new Character();
b = new boss();
I = new Inventory();
background(128, 128, 128);
size( 700, 700 );
strokeWeight( 10 );
frameRate( 30 );
}
void keyPressed() {
if (key == CODED) {
previousKey = keyCode;
if (keyCode == UP) {
C.MoveUP();
}
if (keyCode == LEFT) {
C.MoveLEFT();
}
if (keyCode == DOWN) {
C.MoveDOWN();
}
if (keyCode == RIGHT) {
C.MoveRIGHT();
}
}
if (key == 'w' || key == 'W') {
attack();
}
if ( key == 'q' || key == 'Q' ) {
if (I.Shoot == true) {
B = new Bullet(C.x, C.y);
this.Shoot();
}
} else if (key == 'e' || key == 'E') {
I.changePop();
}
if (keyPressed) {
if (key == 'a' || key == 'A') {
//play = false;
//b.start = true;
}
}
}
void attack() {
if (I.Attack == true) {
if (previousKey == UP) {
C.AttackUP();
}
if (previousKey == LEFT) {
C.AttackLEFT();
}
if (previousKey == DOWN) {
C.AttackDOWN();
}
if (previousKey == RIGHT) {
C.AttackRIGHT();
}
}
}
void Shoot() {
if (I.Shoot == true) {
if (previousKey == UP) {
B.ShootUP();
}
if (previousKey == LEFT) {
B.ShootLEFT();
}
if (previousKey == DOWN) {
B.ShootDOWN();
}
if (previousKey == RIGHT) {
B.ShootRIGHT();
}
}
}
boolean play = true;
void keyReleased() {
lastKey = 0;
lastKeyCode = 0;
}
void draw() {
background(128, 128, 128);
if (play) {
b.simulate();//side to side
}
if (b.start) {
b.sim(); //boss rush
}
if (b.intersects(C)) {
b.isAttacking = true;
play = false;
b.start = true;
} else {
b.isAttacking= false;
}
C.character();
b.bounce();
b.Display();//boss
b.display();//rush area
C.HPbar();
I.popUp();
if ( key == 'q' || key == 'Q' ) {
if (I.Shoot == true) {
B.bullet();
B.Simulate();
}
}
}
Enemies or Boss
class boss {
PVector Location;
PVector Velocity;
PVector speed;
PVector speed2;
int x = 10 ;
int y = 10 ;
boolean start = false;
int RW = 50;
int RH = 700;
boolean up = false;
boolean down = true;
boolean isAttacking = false;
boss() {
Location = new PVector( x+25, y );
Velocity = new PVector( 5, 0 );
speed = new PVector( 0, 10 );
speed2 = new PVector(0, -10);
}
void bounce() {
if ((Location.x == width) ||(Location.x == 0)) {
Velocity.x = Velocity.x * -1;
}
if ((Location.y == 650) || (Location.y == 0)) {
if (!isAttacking) {
start = false;
}
play = true;
if (Location.y == 650) {
RH = -700;
up = true;
down = false;
}
if (Location.y == 0) {
RH = 700;
down = true;
up = false;
}
}
}
void simulate() {
Location.add(Velocity);
}
void sim() {
//print("\n In Sim UP: [" + up + "] Down: [" + down + "] Location [" + Location + "]");
if (down) {
Location.add(speed);
}
if (up) {
Location.add(speed2);
}
}
boolean intersects(Character C) {
//print ("\nUP: [" + up + "] Down: [" + down + "] X: [" + (Location.x < (C.x + C.w) && (Location.x + RW) > C.x)
//+ "] Y: [" + (Location.y < (C.y + C.h) && (Location.y + RH) > C.y) + "]");
return Location.x < (C.x + C.w) && (Location.x + RW) > C.x;
//&&
// Location.y < (C.y + C.h) && (Location.y + RH) > C.y ;
}
void Display() {
pushStyle();
stroke(0);
fill(255, 0, 0);
rect( Location.x, Location.y, 50, 50 );
popStyle();
}
void display() {
pushStyle();
stroke(0);
strokeWeight(0);
fill(255, 0, 0, 20);
rect( Location.x, Location.y+50, RW, RH );
popStyle();
}
}

Ball going through paddle when increasing velocity

I am trying to create a Pong game and so far I have everything working for me other than the ball. At first I had the ball's x and y axis move up by one space each time. It was working fine until i decided to increase it to 2. I cant figure out what is wrong with my code and I need help.
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Pong extends JPanel implements KeyListener{
int x = 90;
int y = 90;
int rectytop = 30;
int rectytop2 = 30;
int rectybottom = rectytop + 100;
int rectybottom2 = rectytop2 + 100;
int border = 30;
boolean balldown = true;
boolean ballright = true;
boolean playerborderup = false;
boolean playerborderdown = false;
boolean balltouch1 = false;
boolean balltouch2 = false;
private void moveball() {
if (balldown == true){
y = y + 2;
}
if (y == getHeight()-border){
balldown = false;
}
if (balldown == false){
y = y - 2;
}
if (ballright == true){
x = x + 2;
}
if (x == getWidth()-border){
ballright = false;
}
if (ballright == false){
x = x - 2;
}
if (y == 0){
balldown = true;
}
if (x == 0){
ballright = true;
}
if (balltouch1 == false){
if (x == 75){
if(y < rectybottom && y > rectytop){
ballright = true;
}
}
}
if (balltouch2 == false){
if (x == 390 && y < rectybottom2 && y > rectytop2){
ballright = false;
}
}
}
#Override
public void paint(Graphics g){
super.paint(g);
//drawing ball and paddles
g.fillOval(x, y, 30, 30);
g.fillRect(45 , rectytop, 30, 100);
g.fillRect(425, rectytop2, 30, 100);
}
public static void main(String[] args) throws InterruptedException {
//making the window
JFrame f = new JFrame("Pong Game");
Pong game = new Pong();
f.setVisible(true);
f.setSize(500, 500);//1024, 724
f.setResizable(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.addKeyListener(game);
//game code
f.add(game);
while (true){
game.repaint();
game.moveball();
Thread.sleep(10);
}
}
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
//player one
if (e.getKeyCode() == KeyEvent.VK_W){
if (rectytop == 0){
playerborderup = true;
}
if (rectytop != 0){
playerborderup = false;
}
if (playerborderup == true){
rectytop = rectytop + 0;
rectybottom = rectytop + 100;
repaint();
}
if (playerborderup == false){
rectytop = rectytop - 5;
rectybottom = rectytop + 100;
repaint();
}
}
if (e.getKeyCode() == KeyEvent.VK_S){
if (rectytop == 585){
playerborderdown = true;
}
if (rectytop != 585){
playerborderdown = false;
}
if (playerborderdown == true){
rectytop = rectytop - 0;
rectybottom = rectytop + 100;
repaint();
}
if (playerborderdown == false){
rectytop = rectytop + 5;
rectybottom = rectytop + 100;
repaint();
}
}
//player two
if (e.getKeyCode() == KeyEvent.VK_UP){
if (rectytop2 == 0){
playerborderup = true;
}
if (rectytop2 != 0){
playerborderup = false;
}
if (playerborderup == true){
rectytop2 = rectytop2 + 0;
rectybottom2 = rectytop2 + 100;
repaint();
}
if (playerborderup == false){
rectytop2 = rectytop2 - 5;
rectybottom2 = rectytop2 + 100;
repaint();
}
}
if (e.getKeyCode() == KeyEvent.VK_DOWN){
if (rectytop2 == 585){
playerborderdown = true;
}
if (rectytop2 != 585){
playerborderdown = false;
}
if (playerborderdown == true){
rectytop2 = rectytop2 - 0;
rectybottom2 = rectytop2 + 100;
repaint();
}
if (playerborderdown == false){
rectytop2 = rectytop2 + 5;
rectybottom2 = rectytop2 + 100;
repaint();
}
}
}
#Override
public void keyReleased(KeyEvent e) {
}
}
Since you are moving by 2 every time, it may "skip" over some coordinates. Thus when you say
if (y == getHeight()-border){
balldown = false;
}
y might go from getHeight()-border + 1 to getHeight()-border - 1 and never meet this condition. Thus, change it to a range or a less than. Your new code should be
if (y <= getHeight()-border +1){
balldown = false; //change the +1 and -1 to have difference at least speed number
}
Note that you must do the same for the other ifs with ==, change
if (x == getWidth()-border){
ballright = false;
}
if (y == 0){
balldown = true;
}
if (x == 0){
ballright = true;
}
to
if (x <= getWidth()-border +1){
ballright = false;
}
if (y <= 1){
balldown = true;
}
if (x <= 1){
ballright = true;
}
Note that you can resolve the problem also by saying if the position is eer exactly one away from the border, temporarily decrement position by 1 instead of 2.
You are using if (x == 75) to detect collision with the left paddle. But if speed is 2 than the ball's x is always even and never equals 75. For a quick fix, check x against a range: if (x > 60 && x < 75)

How to make a player jump on an object in java without velocity

My problem is that I want to make my character (Player) jump on objects which I will add later. I was thinking that Tile Collision would work but I don't understand the aspect of it. Besides my game is just one level at a time, not one whole game.
Here is what I have so far. (I didn't write the code to make The Player to jump on anything because I have no idea where to start):
Game.java:
public class Game extends gameLoop{
public void init()
{
setSize(854,480);
Thread th = new Thread(this);
th.start();
offscreen = createImage(854, 480);
d = offscreen.getGraphics();
addKeyListener(this);
}
public void paint(Graphics g){
d.clearRect(0, 0, 854, 480);
d.drawImage(background, 0 , 0 , this);
d.drawImage(Player, x, y, this);
g.drawImage(offscreen, 0 , 0, this);
}
public void update(Graphics g){
paint(g);
}
}
gameLoop.java:
public class gameLoop extends Applet implements Runnable, KeyListener {
public int x ,y;
public Image offscreen;
public Graphics d;
public boolean up, down, left, right;
public BufferedImage background, run1, run2, run3, run4, run5, run6, run7, run8, runL1, runL2, runL3, runL4, runL5, stand, Player;
public int counter;
public int counterLeft;
public double counter2 = 4;
public void run(){
x = 100;
y = 100;
try {
background = ImageIO.read(new File("background2.png"));
stand = ImageIO.read(new File("stick.gif"));
run1 = ImageIO.read(new File("Runner.png"));
run2 = ImageIO.read(new File("Runner1.png"));
run3 = ImageIO.read(new File("Runner2.png"));
run4 = ImageIO.read(new File("Runner3.png"));
run5 = ImageIO.read(new File("Runner4.png"));
runL1 = ImageIO.read(new File("Runner(1).png"));
runL2 = ImageIO.read(new File("Runner1(1).png"));
runL3 = ImageIO.read(new File("Runner2(1).png"));
runL4 = ImageIO.read(new File("Runner3(1).png"));
runL5 = ImageIO.read(new File("Runner4(1).png"));
} catch (IOException e1) {
e1.printStackTrace();
}
Player = stand;
while(true){
if(y <= 319 && up != true){
y+=10;
}
counter++;
counterLeft ++;
if (counter >= 90){
counter = 0;
}
if (counter >= 10 && right == true && left == false){
Player = run1;
}
if (counter >= 20 && right == true && left == false){
Player = run2;
}
if (counter >= 30 && right == true && left == false){
Player = run3;
}
if (counter >= 40 && right == true && left == false){
Player = run4;
}
if (counter >= 50 && right == true && left == false){
Player = run5;
}
if (counter >= 60 && right == true && left == false){
Player = run1;
}
if (counter >= 70 && right == true && left == false){
Player = run2;
}
if(counter >= 80 && right == true && left == false){
Player = run3;
}
// LEFT
if (counterLeft >= 55){
counterLeft = 0;
}
if (counterLeft >= 10 && left == true && right == false){
Player = runL1;
}
if (counterLeft >= 20 && left == true && right == false){
Player = runL2;
}
if (counterLeft >= 30 && left == true && right == false){
Player = runL3;
}
if (counterLeft >= 40 && left == true && right == false){
Player = runL4;
}
if (counterLeft >= 50 && left == true && right == false){
Player = runL5;
}
if (left == true){
x--;
}
if (right == true){
x++;
}
if (up == true){
counter2 += 0.05;
y = y + (int) ((Math.sin(counter2) + Math.cos(counter2))* 5);
if(counter2 >= 7){
counter2 = 4;
}
}
if(down == true){
y++;
}
if(y >= 319){
y = 319;
}
repaint();
try {
Thread.sleep(5);
}catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == 37 && e.getKeyCode() != 38){ //left
left = true;
}
if (e.getKeyCode() == 38 && e.getKeyCode() != 37){ //up or jump
up = true;
}
if (e.getKeyCode() == 39){ //right
right = true;
}
if (e.getKeyCode() == 40){ //down
down = true;
}
}
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == 37){
left = false;
Player = stand;
}
if (e.getKeyCode() == 38){
up = false;
Player = stand;
}
if (e.getKeyCode() == 39){
right = false;
Player = stand;
}
if (e.getKeyCode() == 40){
down = false;
Player = stand;
}
}
public void keyTyped(KeyEvent e) {}
}
So far all he can do is run and jump.

Java Applet Grid Game Flashing On Refresh/Keypress

I made a simple game on a grid in java that involves controlling a white square with the WASD keys. Whenever I press W,S,A, or D, the screen sometimes flickers before drawing the grid again. I am fairly new to coding, so the more you can dumb it down for me, the better.
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/**
* DotGame.applet
*
* A simple game where the player controls a white circle with the WASD keys.
* - If the user moves his circle over a green circle, his score will go up by 1, and another red circle will spawn.
* - If the user moves his circle over a red circle, his score will go down by 1, and one less red circle will be generated.
* - There is no win condition, it is just a test game.
*
* #author -----------
* #version 11-9-2014
*/
public class DotGame extends Applet
implements KeyListener, MouseListener
{
int width,height;
int powerup = 1;
int click = 0;
int x,y;
final int size = 40;
int ox = size,oy = size;
int rx = 0, ry = 0;
int reddots = 0;
int red[][] = new int[1000][2];
String s = "";
int score = 0;
int DrawGrid = 0;
String sc = "";
int powerupdots = 1;
int yellow[][] = new int[1][2];
int powerupcounter = 0;
int shield = 0;
int blue[][] = new int[1][2];
public void init()
{
this.setSize(740,500);
width = 640;
height = 480;
setBackground( Color.black );
x = width/2;
y = height/2;
s = "CLICK TO START";
addMouseListener( this );
addKeyListener( this );
}
public void keyPressed( KeyEvent e ) { }
public void keyReleased ( KeyEvent e ) { }
public void keyTyped( KeyEvent e )
{
char c = e.getKeyChar();
String t = c+"";
//This will change the coordinates of the user-controlled circle by the size of the circle based on what button is pressed
if(powerupcounter > 0)
{
powerup = 2;
}
else if(powerupcounter == 0)
{
powerup = 1;
}
if( t.equalsIgnoreCase("w" )&& oy > 0+((powerup-1)*size))
{
oy = oy-(size*powerup);
}
else if( t.equalsIgnoreCase("s") && oy < height-(size*powerup))
{
oy = oy+(size*powerup);
}
else if( t.equalsIgnoreCase("a")&& ox > 0+((powerup-1)*size))
{
ox = ox-(size*powerup);
}
else if( t.equalsIgnoreCase("d") && ox < width-(size*powerup))
{
ox = ox+(size*powerup);
}
else if(t.equalsIgnoreCase("w" ) && oy == 0)
{
oy = height-(size*powerup);
}
else if(t.equalsIgnoreCase("s") && oy == height-size)
{
oy = 0+((powerup-1)*size);
}
else if(t.equalsIgnoreCase("a") && ox == 0)
{
ox = width-(size*powerup);
}
else if(t.equalsIgnoreCase("d") && ox == width-size)
{
ox = 0+((powerup-1)*size);
}
else if(t.equalsIgnoreCase("w") && oy == size && powerup ==2)
{
oy = height-size;
}
else if(t.equalsIgnoreCase("s") && oy == height -(size*powerup) && powerup ==2)
{
oy = 0;
}
else if(t.equalsIgnoreCase("a") && ox == size && powerup ==2)
{
ox = width-size;
}
else if(t.equalsIgnoreCase("d") && ox == width -(size*powerup) && powerup ==2)
{
ox = 0;
}
if(powerupcounter > 0)
{
powerupcounter--;
}
repaint();
e.consume();
}
public void mouseEntered( MouseEvent e) {}
public void mouseExited( MouseEvent e) {}
public void mousePressed( MouseEvent e) {}
public void mouseReleased( MouseEvent e) {}
public void mouseClicked( MouseEvent e)
{
if(click == 0)
{
randomYellow();
randomBlue();
DrawRandom();
x = e.getX();
y = e.getY();
s = "";
repaint();
e.consume();
click = 1;
}
}
public void CheckScore()
{
if(ox == rx && oy == ry)
{
score++;
reddots+=10;
DrawRandom();
}
}
public void DrawRandom()
{
//The reason we divide by the size and then multiply after it is an int is to
//make sure that the random circle drawn is in the same base as the size of the circle,
//so that the player's circle can move directly over it, and not be of by a fraction
//of the predetermined size.
rx = (int)(Math.random()*width/size)*size;
ry = (int)(Math.random()*height/size)*size;
while(rx == ox && ry == oy)
{
rx = (int)(Math.random()*width/size)*size;
ry = (int)(Math.random()*height/size)*size;
}
for(int y = 0 ; y < reddots ; y++)
{
red[y][0] = (int)(Math.random()*width/size)*size;
red[y][1] = (int)(Math.random()*height/size)*size;
while(red[y][0] == rx && red[y][1] == ry || red[y][0] == yellow[0][0] && red[y][1] == yellow[0][1]
|| red[y][0] == ox && red[y][1] == oy || red[y][0] == blue[0][0] && red[y][1] == blue[0][1])
{
red[y][0] = (int)(Math.random()*width/size)*size;
red[y][1] = (int)(Math.random()*height/size)*size;
}
}
}
public void randomYellow()
{
yellow[0][0] = (int)(Math.random()*width/size)*size;
yellow[0][1] = (int)(Math.random()*height/size)*size;
while(yellow[0][0] == rx && yellow[0][1] == ry)
{
yellow[0][0] = (int)(Math.random()*width/size)*size;
yellow[0][1] = (int)(Math.random()*height/size)*size;
}
}
public void randomBlue()
{
blue[0][0] = (int)(Math.random()*width/size)*size;
blue[0][1] = (int)(Math.random()*height/size)*size;
while(blue[0][0] == rx && blue[0][1] == ry || blue[0][0] == yellow[0][0] && blue[0][1] == yellow[0][1])
{
blue[0][0] = (int)(Math.random()*width/size)*size;
blue[0][1] = (int)(Math.random()*height/size)*size;
}
}
public void CheckDeath()
{
for(int y = 0 ; y < reddots ; y++)
{
if(ox == red[y][0] && oy == red[y][1] && shield == 0)
{
score--;
reddots--;
DrawRandom();
}
else if(ox == red[y][0] && oy == red[y][1] && shield !=0)
{
shield--;
DrawRandom();
}
}
}
public void CheckPowerup()
{
for(int y = 0 ; y < powerupdots ; y++)
{
if(ox == yellow[y][0] && oy == yellow[y][1])
{
powerupcounter += 10;
randomYellow();
}
}
}
public void CheckShield()
{
if(ox == blue[0][0] && oy == blue[0][1] && shield < 5)
{
shield++;
randomBlue();
}
else if(ox == blue[0][0] && oy == blue[0][1] && shield >= 5)
{
randomBlue();
}
}
public void CheckWin( Graphics g )
{
g.setColor(Color.black);
g.fillRect(0,0,width,height);
while(1 == 1)
{
g.drawString( "YOU WIN" , width/2, height/2);
}
}
public void paint( Graphics g )
{
CheckScore();
if(score == 20)
{
CheckWin(g);
}
CheckDeath();
CheckPowerup();
CheckShield();
DrawGrid(g);
g.setColor(Color.yellow);
g.fillRect(yellow[0][0],yellow[0][1],size+1,size+1);
g.setColor(Color.red);
for(int y = 0; y < reddots ; y++)
{
g.fillRect(red[y][0],red[y][1],size+1,size+1);
}
sc = ""+score;
//Draw user
g.setColor(Color.white);
g.fillRect(ox,oy,size+1,size+1);
//Draw shield around user if they have shields (max 5)
if(shield >= 1)
{
g.setColor(Color.blue);
g.fillRect(ox,oy,size+1,5);
g.fillRect(ox,oy,5,size+1);
g.fillRect(ox,oy+size-4,size+1,5);
g.fillRect(ox+size-4,oy,5,size+1);
}
//Draw green tile
g.setColor(Color.green);
g.fillRect(rx,ry,size+1,size+1);
//Draw shield tile
g.setColor(Color.blue);
g.fillRect(blue[0][0],blue[0][1],size+1,size+1);
g.setColor( Color.green );
g.drawString( s, x, y );
g.drawString( "Score : "+sc, 650, 20);
g.drawString( "Powerups : "+powerupcounter, 650, 40);
g.drawString( "Red Dots : "+reddots, 650,60);
g.drawString( "Shield : "+shield,650,80);
}
public void DrawGrid( Graphics g )
{
g.setColor(Color.orange);
for(int x = 0 ; x <= width ; x += size)
{
g.drawLine(x,0,x,height);
}
for(int y = 0 ; y <= height ; y+= size)
{
g.drawLine(0,y,width,y);
}
}
}
My advice is to move as much of your calculation as possible into methods called from your keypress events, and keep your paint() method as short and direct as possible. Don't do math inside your paint() method if you can help it - use your keypress method to build the picture of everything you need to paint before you call repaint(), and make your paint() method's only job to be to draw the current state of the board. Also, don't redraw the whole board anytime you don't have to. For instance, when moving from the current square to an empty square, all you should draw is a black square over your previous position, and a new user square in the new position. When hitting a yellow or blue square, all you need to draw is the new yellow or blue square (and update the appropriate status messages). You only need to redraw the whole board when hitting a red or green square.

Buggy collision 2D platform game

I'm building my first big project and I'm having trouble with the collision.
At first I used a println command in the collision detection and it worked great,so the problem is not with the detection itself I think.
This the movement code:
public void update() {
// Moves Character or Scrolls Background accordingly.
if (speedX > 0 && centerX <= 400){
centerX += speedX;
}
if (speedX < 0 && centerX >= 400){
centerX += speedX;
}
if (speedX > 0 && centerX >= 400){
bg1.setSpeedX(-MOVESPEED);
bg2.setSpeedX(-MOVESPEED);
}
if (speedX < 0 && centerX <= 400){
bg1.setSpeedX(MOVESPEED);
bg2.setSpeedX(MOVESPEED);
}
if (speedX == 0){
bg1.setSpeedX(0);
bg2.setSpeedX(0);
}
if(movingRight == true && movingLeft == true ){
bg1.setSpeedX(0);
bg2.setSpeedX(0);
}
// Handles Jumping
if (jumped == true) {
speedY += 1;
}
// Prevents going beyond X coordinate of 0
if (centerX + speedX <= 60) {
centerX = 61;
}
rect.setRect(centerX - 47, centerY - 65, 32, 87);
centerY += speedY;
}
public void moveRight() {
speedX = MOVESPEED;
}
public void moveLeft() {
speedX = -MOVESPEED;
}
public void stopRight() {
movingRight = false;
stop();
}
public void stopLeft() {
movingLeft = false;
stop();
}
private void stop() {
if (movingRight == false && movingLeft == false) {
speedX = 0;
}
if (movingRight == false && movingLeft == true) {
moveLeft();
}
if (movingRight == true && movingLeft == false) {
moveRight();
}
}
public void jump() {
if (jumped == false) {
speedY = JUMPSPEED;
jumped = true;
}
}
and this is the collision code:
public void checkCollision(Rectangle rect){
if (rect.intersects(r)){
if(Player.movingRight){
Player.centerX = tileX + 11;
Player.speedX =0;
}
if(Player.movingLeft){
Player.centerX = tileX + 89;
Player.speedX = 0;
}
if(Player.speedY > 0){
Player.centerY = tileY - 25;
Player.speedY = 0;
Player.jumped = false;
}
}
}
The problem is that it is very buggy, sometimes the player "teleports" and even falls threw the wall.

Categories