I'm a novice programmer, I'm make my first game in Java, and I just implemented a target AI, and now whenever I run it, always lags at start, I would like a explanation on why please or a way to do this better, Thank you in advance.
Code:(for what is most Likely causing the lag)
public class Handler {
//Use Linked Lists
private Animator a;
private boolean renderMini;
private int x, y;
public LinkedList<GameObject> object = new LinkedList<GameObject>();
public LinkedList<EntityObject> entity = new LinkedList<EntityObject>();
public LinkedList<Faction> faction = new LinkedList<Faction>();
public Handler(){
a = new Animator();
this.renderMini = false;
}
public void render(Graphics g){
///if(GameMain.numFrames > 5){
if(renderMini){
a.AnimateMini(g, x, y, 32, 32);
}
for(int i = 0; i < entity.size(); i++){
EntityObject tempObject = entity.get(i);
tempObject.render(g);
}
for(int i = 0; i < object.size(); i++){
GameObject tempObject = object.get(i);
tempObject.render(g);
}
//}
}
public void tick(){
//if(GameMain.numFrames > 5){
for(int i = 0; i < entity.size(); i++){
EntityObject tempObject = entity.get(i);
tempObject.tick();
}
for(int i = 0; i < object.size(); i++){
GameObject tempObject = object.get(i);
tempObject.tick();
}
for(int i = 0; i < faction.size(); i++){
Faction tempObject = faction.get(i);
tempObject.tick();
}
//}
}
public void addEntity(EntityObject o){
this.entity.add(o);
}
public void removeEntity(EntityObject o){
this.entity.remove(o);
}
public void addObject(GameObject o){
this.object.add(o);
}
public void removeObject(GameObject o){
if(o instanceof NpcLaser){
x = o.getX();
y = o.getY();
renderMini = true;
}
if(o instanceof PlayerLaser){
x = o.getX();
y = o.getY();
renderMini = true;
}
this.object.remove(o);
}
public void addFaction(Faction f){
this.faction.add(f);
}
public void removeFaction(Faction f){
this.faction.remove(f);
}
}
public class StandardShip extends EntityObject{
private Handler h;
private Random r;
private Animator a;
private Faction ef;
private EntityObject object;
private int desX, desY;
private int lx, ly, targetX, targetY; //target;
private boolean animateReady;
public static int isDead, ran, ra, rn;
public static boolean thisDeath;
public static boolean choAttack, choDefense, choSpeed, choShealth, choCommanding;
public StandardShip(int x, int y, int width, int height, Handler h, Faction f) {
super(x, y, width, height, h);
r = new Random();
a = new Animator();
this.setDeath(false);
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.h = h;
/*this.isDead = 0;
this.thisDeath = false;
this.p = p;*/
this.health = 100;
this.animateReady = false;
//this.target = 1;
this.killLim = r.nextInt(4) + 1;
EntityObject.f = f;
EntityObject.f.addMember(this);
this.attackLim = 20;
this.defenseLim = 20;
this.speedLim = 20;
this.shealthLim = 20;
this.commandingLim = 20;
this.currency = 0;
this.attack = r.nextInt(attackLim);
this.defense = r.nextInt(defenseLim) + 1;
this.speed = r.nextInt(speedLim) + 2;
this.shealth = r.nextInt(shealthLim);
this.commanding = r.nextInt(commandingLim);
this.velX = 1;
this.velY = 1;
this.SearchTime = 1000;
this.desX = r.nextInt(Window.screensize.width + 1000);
this.desY = r.nextInt(Window.screensize.height + 1000);
//this.vectW = 5;
rn = r.nextInt(5);
if(rn == 0){
if(attack < 15){
attack = r.nextInt(attackLim) + 15;
}
}
if(rn == 1){
if(defense < 15){
defense = r.nextInt(defenseLim) + 15;
}
}
if(rn == 2){
if(speed < 15){
speed = r.nextInt(speedLim) + 15;
}
}
if(rn == 3){
if(shealth < 15){
shealth = r.nextInt(shealthLim) + 15;
}
}
if(rn == 4){
if(commanding < 15){
commanding = r.nextInt(commandingLim) + 15;
}
}
if(choAttack){
if(attack < 15){
attack = r.nextInt(attackLim) + 15;
}
}
if(choDefense){
if(defense < 15){
defense = r.nextInt(defenseLim) + 15;
}
}
if(choSpeed){
if(speed < 15){
speed = r.nextInt(speedLim) + 15;
}
}
if(choShealth){
if(shealth < 15){
shealth = r.nextInt(shealthLim) + 15;
}
}
if(choCommanding){
if(commanding < 15){
commanding = r.nextInt(commandingLim) + 15;
}
}
}
public void tick() {
x = GameMain.clamp(0, Window.screensize.width + 1000, x);
y = GameMain.clamp(0, Window.screensize.height + 1000, y);
x += velX;
y += velY;
EnemySize = f.isEnemy.size();
if(coolDown > 0){
coolDown--;
coolDown = GameMain.clamp(0, 1000, coolDown);
}
if(this.target == null){
for(int i = 0; i < EnemySize; i++){
ef = EntityObject.f.isEnemy.get(i);
memberSize = ef.members.size();
}
}
for(int i = 0; i < ef.members.size(); i++){
object = ef.members.get(i);
if(object.getX() >= this.x && object.getX() <= this.x + 300){
this.setTarget(object);
System.out.println("TargetSS");
i = ef.members.size();
}
if(object.getY() >= this.y && object.getY() <= this.y + 300){
this.setTarget(object);
System.out.println("TargetSS");
i = ef.members.size();
}
}
if(this.target != null && coolDown <= 0){
targetX = this.target.getX();
targetY = this.target.getY();
attack(targetX, targetY);
coolDown = 500;
}
if(this.target == null){
wander();
}
/*rand = r.nextInt(100);
if(kills == killLim){
level++;
levelUp();
kills = 0;
killLim += killLim/2;
}
x += velX;
y += velY;
if(y < vectY && velY == -1){velY *= -1;}
if(y > vectY && velY == 1){velY *= -1;}
if(x < vectX && velX == -1){velX *= -1;}
if(x > vectX && velX == 1){velX *= -1;}
if(x == vectX){
if(r.nextInt(2) == 0){
vectX = r.nextInt(Window.screensize.width);
}else{
velX = 0;
}
}
if(y == vectY){
if(r.nextInt(2) == 0){
vectY = r.nextInt(Window.screensize.height);
}else{
velY = 0;
}
}*/
if(this.isDamage > 0 && this.isDamage > defense){
health -= isDamage - (defense / 2);
isDamage = 0;
//System.out.println("HELLO");
}
}
public void wander(){
if(y < desY && velY == -1){velY *= -1;}
if(y > desY && velY == 1){velY *= -1;}
if(x < desX && velX == -1){velX *= -1;}
if(x > desX && velX == 1){velX *= -1;}
System.out.println("desY: "+desY+" desX: "
+desX+" Y: "+y+" X: "+x+" velX: "+velX+" velY: "+velY);
if(x == desX){
//if(r.nextInt(2) == 0){
desX = r.nextInt(Window.screensize.width + 1000);
//}else{
velX = 0;
//}
}
if(y == desY){
//if(r.nextInt(2) == 0){
desY = r.nextInt(Window.screensize.height + 1000);
//}else{
velY = 0;
//}
}
}
public void levelUp(){
this.health += r.nextInt(300) + 100;
this.attack += r.nextInt(attackLim);
this.defense += r.nextInt(defenseLim) + 1;
this.speed += r.nextInt(speedLim) + 2;
this.shealth += r.nextInt(shealthLim);
this.commanding += r.nextInt(commandingLim);
if(choAttack){
attack += (r.nextInt(attackLim) + 15)/2;
}
if(choDefense){
defense += (r.nextInt(defenseLim) + 15)/2;
}
if(choSpeed){
speed += (r.nextInt(speedLim) + 15)/2;
}
if(choShealth){
shealth += (r.nextInt(shealthLim) + 15)/2;
}
if(choCommanding){
commanding += (r.nextInt(commandingLim) + 15)/2;
}
}
public void Collision(Graphics g){
/*for(int i = 0; i < h.object.size(); i++){
GameObject tempObject = h.object.get(i);
if(tempObject.getId() == ID.Money){
Money m = (Money) tempObject;
if(getBounds().intersects(tempObject.getBounds())){
currency += m.getCashValue();
h.removeObject(tempObject);
}
}
if(tempObject.getId() == ID.ShipPart){
ShipPart s = (ShipPart) tempObject;
if(getBounds().intersects(tempObject.getBounds())){
numShipParts++;
h.removeObject(tempObject);
}
}
if(tempObject.getId() == ID.Meteor){
Meteor m = (Meteor) tempObject;
if(getBounds().intersects(tempObject.getBounds())){
Rectangle OverLap = getBounds().intersection(tempObject.getBounds());
if(OverLap.height >= OverLap.width){
if(m.isDoesDamage() && !m.isExplodes() && !m.isOnFire()){
this.health -= m.getDamage();
velX *= -2;
}
if(m.isDoesDamage() && m.isExplodes() || m.isDoesDamage() && m.isOnFire()){
if(m.isExplodes()){
a.AnimateExplosion(g, tempObject.getX(), tempObject.getY(), 32, 32);
this.health -= m.getDamage();
if(a.isFin[0]){
h.removeObject(tempObject);
a.isFin[0] = false;
}
}
if(m.isOnFire()){
this.health -= m.getDamage();
velX *= -2;
}
}else{
velX *= -2;
}
}
if(OverLap.width >= OverLap.height){
if(m.isDoesDamage() && !m.isExplodes() && !m.isOnFire()){
this.health -= m.getDamage();
velY *= -2;
}
if(m.isDoesDamage() && m.isExplodes() || m.isDoesDamage() && m.isOnFire()){
if(m.isExplodes()){
this.health -= m.getDamage();
m.setExplodeNow(true);
}
if(m.isOnFire()){
this.health -= m.getDamage();
velY *= -2;
}
}else{
velY *= -2;
}
}
}
}
if(tempObject.getId() == ID.Player){
p = (Player) tempObject;
if(getBounds().intersects(tempObject.getBounds())){
Rectangle OverLap = getBounds().intersection(tempObject.getBounds());
health -= r.nextInt(10) + 10;
p.setDamage(r.nextInt(10) + 10);
if(OverLap.height >= OverLap.width){
tempObject.setVelX(0);
}
if(OverLap.width >= OverLap.height){
tempObject.setVelY(0);
}
}
}
}*/
}
public void attack(int targetX, int targetY){
System.out.println("Hello");
h.addObject(new NpcLaser(x + 60, y + 60, 5, 9, h, f, targetX, targetY, this.attack));
}
public void render(Graphics g) {
a.AnimateEnemy(g, this.x, this.y, this.width, this.height, f);
if(animateReady){
a.AnimateMini(g, lx, ly, ran, ran);
}
if(health <= 0){
setDeath(true);
StandardShip.thisDeath = true;
a.AnimateExplosion(g, x, y, width, height);
if(Animator.isFin[0]){
ra = r.nextInt(10);
isDead++;
if(ra <= 7){
h.addObject(new Money(x, y, 32, 32, ID.Money, h, currency));
}else{
for(int i = 0; i < numShipParts; i++){
h.addObject(new ShipPart(x, y, 32, 32, ID.ShipPart, h));
}
}
h.removeEntity(this);
Animator.isFin[0] = false;
}
}
g.setColor(Color.red);
}
public Rectangle getBounds() {
return new Rectangle(x + 40, y + 37, 50, 50);
}
}
public class NpcLaser extends GameObject{
private Handler h;
private Faction f, ef;
private int laserAim;
private int currentTarget;
private int vectorX, vectorY;
private int damage;
public NpcLaser(int x, int y, int width, int height, Handler h, Faction f, int targetX, int targetY, int attack) {
super(x, y, width, height, h);
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.h = h;
this.f = f;
this.vectorX = targetX;
this.vectorY = targetY;
this.damage = attack;
new Animator();
aimAI();
}
public void tick() {
System.out.println("Hello");
//Collision(g);
x += velX;
y += velY;
if(velX == 0 && velY == 0){
h.object.remove();
}
for(int i = 0; i < f.isEnemy.size(); i++){
ef = f.isEnemy.get(i);
}
for(int u = 0; u < ef.members.size(); u++){
EntityObject eo = ef.members.get(u);
if(getBounds().intersects(eo.getBounds())){
eo.setDamage(damage);
h.removeObject(this);
}
}
if(x > Window.screensize.getWidth() + 1200 || x < 0 - 1200){
h.removeObject(this);
}
if(y > Window.screensize.getHeight() + 1200 || y < 0 - 1200){
h.removeObject(this);
}
}
public void aimAI(){
if(x < vectorX){velX = 10;}
if(x > vectorX){velX = -10;}
if(y < vectorY){velY = 10;}
if(y > vectorY){velY = -10;}
if(x <= vectorX + 60 && x >= vectorX - 60){velX = 0;}
if(y <= vectorY + 60 && y >= vectorY - 60){velY = 0;}
}
public void render(Graphics g) {
/*if(p.isRemoveShot()){
h.removeObject(this);
p.setRemoveShot(false);
}*/
if(velX == 10 && velY == 10 || velX == -10 && velY == -10){
laserAim = 3;
}
if(velX == 10 && velY == -10 || velX == -10 && velY == 10){
laserAim = 2;
}
if(velX == 10 && velY == 0 || velX == -10 && velY == 0){
laserAim = 1;
}
if(velX == 0 && velY == 10 || velX == 0 && velY == -10){
laserAim = 0;
}
if(laserAim == 0){
g.drawImage(Assets.playerLaser, x, y, width, height, null);
}
if(laserAim == 1){
g.drawImage(Assets.playerLaser1, x, y, width, height, null);
}
if(laserAim == 2){
g.drawImage(Assets.playerLaser2, x, y, width, height, null);
}
if(laserAim == 3){
g.drawImage(Assets.playerLaser3, x, y, width, height, null);
}
}
public int getDamage() {
return damage;
}
public void setDamage(int damage) {
this.damage = damage;
}
public int getCurrentTarget() {
return currentTarget;
}
public void setCurrentTarget(int currentTarget) {
this.currentTarget = currentTarget;
}
public Rectangle getBounds() {
return new Rectangle(x, y, width, height);
}
}
Full Source Code Here
for(int i = 0; i < entity.size(); i++){
EntityObject tempObject = entity.get(i);
tempObject.render(g);
}
Your code includes several loops that look like this, and each take quadratic time, because they're running over LinkedList, which requires O(n) time for get. You should almost certainly be using an ArrayList, or at minimum, using a for-each loop, e.g.
for (EntityObject tempObject : entity) {
tempObject.render(g);
}
Related
I need to do a Minesweeper game. I have most of the methods down, but I cannot figure out a way to draw the number of mines around a given tile. I have a method that returns the number of mines around that tile, but no such method to actually display that number inside the tile in the game.
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Insets;
import java.net.URL;
import java.util.Random;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
public class MyPanel extends JPanel {
private static final long serialVersionUID = 3426940946811133635L;
private static final int GRID_X = 25;
private static final int GRID_Y = 25;
private static final int INNER_CELL_SIZE = 29;
private static final int TOTAL_COLUMNS = 9;
private static final int TOTAL_ROWS = 10; //Last row has only one cell
public int x = -1;
public int y = -1;
public int mouseDownGridX = 0;
public int mouseDownGridY = 0;
private ImageIcon icon;
private static char minefield[][];
public Color[][] colorArray = new Color[TOTAL_COLUMNS][TOTAL_ROWS];
public MyPanel() { //This is the constructor... this code runs first to initialize
if (INNER_CELL_SIZE + (new Random()).nextInt(1) < 1) { //Use of "random" to prevent unwanted Eclipse warning
throw new RuntimeException("INNER_CELL_SIZE must be positive!");
}
if (TOTAL_COLUMNS + (new Random()).nextInt(1) < 2) { //Use of "random" to prevent unwanted Eclipse warning
throw new RuntimeException("TOTAL_COLUMNS must be at least 2!");
}
if (TOTAL_ROWS + (new Random()).nextInt(1) < 3) { //Use of "random" to prevent unwanted Eclipse warning
throw new RuntimeException("TOTAL_ROWS must be at least 3!");
}
for (int x = 0; x < TOTAL_COLUMNS; x++) { //Top row
colorArray[x][0] = Color.LIGHT_GRAY;
}
for (int y = 0; y < TOTAL_ROWS; y++) { //Left column
colorArray[0][y] = Color.LIGHT_GRAY;
}
for (int x = 1; x < TOTAL_COLUMNS; x++) { //The rest of the grid
for (int y = 1; y < TOTAL_ROWS; y++) {
colorArray[x][y] = Color.LIGHT_GRAY;
}
}
minefield = new char [TOTAL_COLUMNS][TOTAL_ROWS];
}
Random rando = new Random();
public static int mines = 10;
public int flags = 10;
public static int flagged = 0;
public void paintComponent(Graphics g) {
super.paintComponent(g);
//Compute interior coordinates
Insets myInsets = getInsets();
int x1 = myInsets.left;
int y1 = myInsets.top;
int x2 = getWidth() - myInsets.right - 1;
int y2 = getHeight() - myInsets.bottom - 1;
int width = x2 - x1;
int height = y2 - y1;
//Paint the background
g.setColor(Color.LIGHT_GRAY);
g.fillRect(x1, y1, width + 1, height + 1);
//Draw the grid minus the bottom row (which has only one cell)
//By default, the grid will be 10x10 (see above: TOTAL_COLUMNS and TOTAL_ROWS)
g.setColor(Color.BLACK);
for (int y = 0; y <= TOTAL_ROWS - 1; y++) {
g.drawLine(x1 + GRID_X, y1 + GRID_Y + (y * (INNER_CELL_SIZE + 1)), x1 + GRID_X + ((INNER_CELL_SIZE + 1) * TOTAL_COLUMNS), y1 + GRID_Y + (y * (INNER_CELL_SIZE + 1)));
}
for (int x = 0; x <= TOTAL_COLUMNS; x++) {
g.drawLine(x1 + GRID_X + (x * (INNER_CELL_SIZE + 1)), y1 + GRID_Y, x1 + GRID_X + (x * (INNER_CELL_SIZE + 1)), y1 + GRID_Y + ((INNER_CELL_SIZE + 1) * (TOTAL_ROWS - 1)));
}
//Paint cell colors
for (int x = 0; x < TOTAL_COLUMNS; x++) {
for (int y = 0; y < TOTAL_ROWS; y++) {
if ((x == 0) || (y != TOTAL_ROWS - 1)) {
Color c = colorArray[x][y];
g.setColor(c);
g.fillRect(x1 + GRID_X + (x * (INNER_CELL_SIZE + 1)) + 1, y1 + GRID_Y + (y * (INNER_CELL_SIZE + 1)) + 1, INNER_CELL_SIZE, INNER_CELL_SIZE);
}
}
}
}
// Places the mines in the field
public void placeMines() {
int minesPlaced = 1;
while (minesPlaced <= mines) {
int x = rando.nextInt(TOTAL_COLUMNS);
int y = rando.nextInt(TOTAL_ROWS-1);
if (minefield[x][y] != '*') {
minefield[x][y] = '*';
minesPlaced++;
}
}
for (int i=0; i<9; i++) {
for (int j=0; j<9; j++) {
bombCheck(i, j);
if (bombCheck(i, j) == 1) {
System.out.println(i + "," + j); // for debugging purposes
}
}
}repaint();
}
//checks a tile, white if there were no mines
public void check (int x, int y) {
colorArray[x][y] = Color.WHITE ;
repaint();
}
// Checks whether this place in the field has a bomb (1) or not (0).
public int bombCheck(int x, int y) {
if (!(x == -1 || y == -1)) {
if (minefield[x][y] == '*') {
return 1;
}
else {
minefield[x][y] = 'c';
return 0;
}
}
else{
return 0;
}
}
// Checks for mines on the 8 other tiles around the target location and returns the number of mines there are.
public int minesAround(int x, int y) {
int mines = 0;
mines += bombCheck(x-1, y-1);
mines += bombCheck(x-1, y);
mines += bombCheck(x-1, y+1);
mines += bombCheck(x, y-1);
mines += bombCheck(x, y+1);
mines += bombCheck(x+1, y-1);
mines += bombCheck(x+1, y);
mines += bombCheck(x+1, y+1);
if (mines > 0) {
return mines;
}
else{
return 0;
}
}
//What I've come up with so far for drawing the number in the tile. Does not work.
public void draw (Graphics g, int n, int x, int y) {
super.paintComponent(g);
g.drawString("" + n + "", x, y);
}
//Recursive method
public void checkAround(int x, int y) {
int minx, miny, maxx, maxy;
check(x,y);
minx = (x <= 0 ? 0 : x - 1);
miny = (y <= 0 ? 0 : y - 1);
maxx = (x >= TOTAL_COLUMNS - 1 ? TOTAL_COLUMNS - 1 : x + 1);
maxy = (y >= TOTAL_ROWS - 2 ? TOTAL_ROWS - 2 : y + 1);
for (int i = minx; i < maxx; i ++) {
for (int j = miny; j <= maxy; j ++) {
if (bombCheck(i,j) == 0 && colorArray[i][j] != Color.WHITE) {
check(i,j);
if (minesAround(i,j) == 0) {
checkAround(i,j);
}
if (minesAround(i,j) == 1) {
draw(getGraphics(),1,i,j); // Does not work.
repaint();
}
}
}
}
}
//Flag
public int checkflag(int x, int y){
int status = 0;
if (!(x == -1 || y == -1)) {
if (colorArray[x][y] == Color.RED) {
status += 1;
}else {
status += 0;
}
}
return status;
}
//Resets field
public void reset() {
for (int i = 0; i < TOTAL_COLUMNS; i++) {
for (int j = 0 ;j < TOTAL_ROWS; j++) {
colorArray[i][j] = Color.LIGHT_GRAY;
minefield[i][j] = ' ';
MyMouseAdapter.f = 1;
repaint();
}
}
placeMines();
}
public int getGridX(int x, int y) {
Insets myInsets = getInsets();
int x1 = myInsets.left;
int y1 = myInsets.top;
x = x - x1 - GRID_X;
y = y - y1 - GRID_Y;
if (x < 0) { //To the left of the grid
return -1;
}
if (y < 0) { //Above the grid
return -1;
}
if ((x % (INNER_CELL_SIZE + 1) == 0) || (y % (INNER_CELL_SIZE + 1) == 0)) { //Coordinate is at an edge; not inside a cell
return -1;
}
x = x / (INNER_CELL_SIZE + 1);
y = y / (INNER_CELL_SIZE + 1);
if (x == 0 && y == TOTAL_ROWS - 1) { //The lower left extra cell
return x;
}
if (x < 0 || x > TOTAL_COLUMNS - 1 || y < 0 || y > TOTAL_ROWS - 2) { //Outside the rest of the grid
return -1;
}
return x;
}
public int getGridY(int x, int y) {
Insets myInsets = getInsets();
int x1 = myInsets.left;
int y1 = myInsets.top;
x = x - x1 - GRID_X;
y = y - y1 - GRID_Y;
if (x < 0) { //To the left of the grid
return -1;
}
if (y < 0) { //Above the grid
return -1;
}
if ((x % (INNER_CELL_SIZE + 1) == 0) || (y % (INNER_CELL_SIZE + 1) == 0)) { //Coordinate is at an edge; not inside a cell
return -1;
}
x = x / (INNER_CELL_SIZE + 1);
y = y / (INNER_CELL_SIZE + 1);
if (x == 0 && y == TOTAL_ROWS - 1) { //The lower left extra cell
return y;
}
if (x < 0 || x > TOTAL_COLUMNS - 1 || y < 0 || y > TOTAL_ROWS - 2) { //Outside the rest of the grid
return -1;
}
return y;
}
public ImageIcon getIcon() {
return icon;
}
public void setIcon(ImageIcon icon) {
this.icon = icon;
}
}
-
import java.awt.Color;
import java.awt.Component;
import java.awt.Insets;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Random;
import javax.swing.JFrame;
public class MyMouseAdapter extends MouseAdapter {
public static int f = 1;
public void mousePressed(MouseEvent e) {
switch (e.getButton()) {
case 1: //Left mouse button
Component c = e.getComponent();
while (!(c instanceof JFrame)) {
c = c.getParent();
if (c == null) {
return;
}
}
JFrame myFrame = (JFrame) c;
MyPanel myPanel = (MyPanel) myFrame.getContentPane().getComponent(0);
Insets myInsets = myFrame.getInsets();
int x1 = myInsets.left;
int y1 = myInsets.top;
e.translatePoint(-x1, -y1);
int x = e.getX();
int y = e.getY();
myPanel.x = x;
myPanel.y = y;
myPanel.mouseDownGridX = myPanel.getGridX(x, y);
myPanel.mouseDownGridY = myPanel.getGridY(x, y);
myPanel.repaint();
break;
case 3: //Right mouse button
Component c1 = e.getComponent();
while (!(c1 instanceof JFrame)) {
c = c1.getParent();
if (c == null) {
return;
}
}
JFrame myFrame1 = (JFrame)c1;
MyPanel myPanel1 = (MyPanel) myFrame1.getContentPane().getComponent(0); //Can also loop among components to find MyPanel
Insets myInsets1 = myFrame1.getInsets();
int x2 = myInsets1.left;
int y2 = myInsets1.top;
e.translatePoint(-x2, -y2);
int x3 = e.getX();
int y3 = e.getY();
myPanel1.x = x3;
myPanel1.y = y3;
myPanel1.mouseDownGridX = myPanel1.getGridX(x3, y3);
myPanel1.mouseDownGridY = myPanel1.getGridY(x3, y3);
break;
default: //Some other button (2 = Middle mouse button, etc.)
//Do nothing
break;
}
}
public void mouseReleased(MouseEvent e) {
switch (e.getButton()) {
case 1: //Left mouse button
Component c = e.getComponent();
while (!(c instanceof JFrame)) {
c = c.getParent();
if (c == null) {
return;
}
}
JFrame myFrame = (JFrame)c;
MyPanel myPanel = (MyPanel) myFrame.getContentPane().getComponent(0); //Can also loop among components to find MyPanel
Insets myInsets = myFrame.getInsets();
int x1 = myInsets.left;
int y1 = myInsets.top;
e.translatePoint(-x1, -y1);
int x = e.getX();
int y = e.getY();
myPanel.x = x;
myPanel.y = y;
int gridX = myPanel.getGridX(x, y);
int gridY = myPanel.getGridY(x, y);
if ((myPanel.mouseDownGridX == -1) || (myPanel.mouseDownGridY == -1)) {
//Had pressed outside
//Do nothing
} else {
if ((gridX == -1) || (gridY == -1)) {
//Do nothing
}else if (gridX == 0 && gridY == 9) {
myPanel.reset();
} else {
if ((myPanel.mouseDownGridX != gridX) || (myPanel.mouseDownGridY != gridY)) {
//Released the mouse button on a different cell where it was pressed
//Do nothing
} else {
//Released the mouse button on the same cell where it was pressed
if (!(myPanel.mouseDownGridX == -1) || (myPanel.mouseDownGridY == -1)) {
if (!(myPanel.colorArray[gridX][gridY] == Color.RED)) {
if (myPanel.bombCheck(gridX, gridY) == 0) {
myPanel.checkAround(gridX, gridY);
}
else{
myPanel.colorArray[gridX][gridY] = Color.BLACK ;
System.out.println("You've Lost!");
myPanel.reset();
myPanel.repaint();
}
}
}
}
}
}
myPanel.repaint();
break;
case 3: //Right mouse button
Component c1 = e.getComponent();
while (!(c1 instanceof JFrame)) {
c = c1.getParent();
if (c == null) {
return;
}
}
JFrame myFrame1 = (JFrame)c1;
MyPanel myPanel1 = (MyPanel) myFrame1.getContentPane().getComponent(0); //Can also loop among components to find MyPanel
Insets myInsets1 = myFrame1.getInsets();
int x2 = myInsets1.left;
int y2 = myInsets1.top;
e.translatePoint(-x2, -y2);
int x3 = e.getX();
int y3 = e.getY();
myPanel1.x = x3;
myPanel1.y = y3;
int gridX1 = myPanel1.getGridX(x3, y3);
int gridY1 = myPanel1.getGridY(x3, y3);
int flags = 10;
if ((myPanel1.mouseDownGridX == -1) || (myPanel1.mouseDownGridY == -1)) {
//Had pressed outside
//Do nothing
} else {
if ((gridX1 == -1) || (gridY1 == -1)) {
//Is releasing outside
//Do nothing
} else {
if ((myPanel1.mouseDownGridX != gridX1) || (myPanel1.mouseDownGridY != gridY1)) {
}else{
if (!(myPanel1.colorArray[gridX1][gridY1] == Color.WHITE)) {
if (myPanel1.checkflag(gridX1, gridY1) == 0) {
if (!(f > flags)) {
if (myPanel1.bombCheck(gridX1, gridY1) == 1) {
MyPanel.flagged ++;
if (MyPanel.flagged == 10) {
System.out.println("You've Won! Congratulations!");
myPanel1.reset();
myPanel1.colorArray[gridX1][gridY1] = Color.LIGHT_GRAY ;
myPanel1.repaint();
}
}
myPanel1.colorArray[gridX1][gridY1] = Color.RED ;
myPanel1.repaint();
f ++;
}
}
else {
myPanel1.colorArray[gridX1][gridY1] = Color.LIGHT_GRAY ;
myPanel1.repaint();
f --;
}
}
}
}
}
break;
default: //Some other button (2 = Middle mouse button, etc.)
//Do nothing
break;
}
}
}
-
import javax.swing.JFrame;
public class Main {
public static void main(String[] args) {
JFrame myFrame = new JFrame("Color Grid");
myFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
myFrame.setLocation(400, 150);
myFrame.setSize(400, 400);
MyPanel myPanel = new MyPanel();
myFrame.add(myPanel);
MyMouseAdapter myMouseAdapter = new MyMouseAdapter();
myFrame.addMouseListener(myMouseAdapter);
myFrame.setVisible(true);
myPanel.placeMines();
}
}
This is only my first year studying Computer science, but if my intuition is correct, my draw method is drawing the number behind the tiles. These are just my thoughts, I have relatively little to no experience with Java.
In your paintComponent() add something like this:
Font f = new Font("Dialog", Font.PLAIN, 12); // choose a font for the numbers
g.setFont(f);
// Draw cell numbers
for (int x = 0; x < TOTAL_COLUMNS; x++) {
for (int y = 0; y < TOTAL_ROWS; y++) {
if (/* check if the (x,y) cell is uncovered */) {
int around = minesAround(x, y);
g.drawString(String.valueOf(around), /*cell x coord*/, /*cell y coord*/);
}
}
}
Alternatively, you can use an image for each cell number instead of using a string.
**Edited still not getting the right response **
I am not quite understanding how to figure out the intersection aspect of my project. So far I have determined the top, bottom, left and right but I am not sure where to go from there.
The main driver should call to check if my moving rectangles are intersecting and if the rectangle is froze the moving one intersecting with it should unfreeze it and change its color. I understand how to unfreeze it and change the color but for whatever the reason it isn't returning the value as true when they are intersecting and I know this code is wrong. Any helpful tips are appreciated.
*CLASS CODE*
import edu.princeton.cs.introcs.StdDraw;
import java.util.Random;
import java.awt.Color;
public class MovingRectangle {
Random rnd = new Random();
private int xCoord;
private int yCoord;
private int width;
private int height;
private int xVelocity;
private int yVelocity;
private Color color;
private boolean frozen;
private int canvas;
public MovingRectangle(int x, int y, int w, int h, int xv, int yv, int canvasSize) {
canvas = canvasSize;
xCoord = x;
yCoord = y;
width = w;
height = h;
xVelocity = xv;
yVelocity = yv;
frozen = false;
int c = rnd.nextInt(5);
if (c == 0) {
color = StdDraw.MAGENTA;
}
if (c == 1) {
color = StdDraw.BLUE;
}
if (c == 2) {
color = StdDraw.CYAN;
}
if (c == 3) {
color = StdDraw.ORANGE;
}
if (c == 4) {
color = StdDraw.GREEN;
}
}
public void draw() {
StdDraw.setPenColor(color);
StdDraw.filledRectangle(xCoord, yCoord, width, height);
}
public void move() {
if (frozen == false) {
xCoord = xCoord + xVelocity;
yCoord = yCoord + yVelocity;
}
else {
xCoord +=0;
yCoord +=0;
}
if (xCoord >= canvas || xCoord < 0) {
xVelocity *= -1;
this.setRandomColor();
}
if (yCoord >= canvas || yCoord < 0) {
yVelocity *= -1;
this.setRandomColor();
}
}
public void setColor(Color c) {
StdDraw.setPenColor(color);
}
public void setRandomColor() {
int c = rnd.nextInt(5);
if (c == 0) {
color = StdDraw.MAGENTA;
}
if (c == 1) {
color = StdDraw.BLUE;
}
if (c == 2) {
color = StdDraw.CYAN;
}
if (c == 3) {
color = StdDraw.ORANGE;
}
if (c == 4) {
color = StdDraw.GREEN;
}
}
public boolean containsPoint(double x, double y) {
int bottom = yCoord - height / 2;
int top = yCoord + height / 2;
int left = xCoord - width / 2;
int right = xCoord + width / 2;
if (x > left && x < right && y > bottom && y < top) {
color = StdDraw.RED;
return true;
} else {
return false;
}
}
public boolean isFrozen() {
if (frozen) {
return true;
} else {
return false;
}
}
public void setFrozen(boolean val) {
frozen = val;
}
public boolean isIntersecting(MovingRectangle r) {
int top = xCoord + height/2;
int bottom = xCoord - height/2;
int right = yCoord + width/2;
int left = yCoord - width/2;
int rTop = r.xCoord + r.height/2;
int rBottom = r.xCoord - r.height/2;
int rRight = r.yCoord + r.width/2;
int rLeft = r.yCoord - r.width/2;
if(right <= rRight && right >= rLeft || bottom <= rBottom && bottom
>= rTop){
return true;
} else {
return false;
}
}
}
Here is my main driver as well, because I might be doing something wrong here too.
import edu.princeton.cs.introcs.StdDraw;
import java.util.Random;
public class FreezeTagDriver {
public static final int CANVAS_SIZE = 800;
public static void main(String[] args) {
StdDraw.setCanvasSize(CANVAS_SIZE, CANVAS_SIZE);
StdDraw.setXscale(0, CANVAS_SIZE);
StdDraw.setYscale(0, CANVAS_SIZE);
Random rnd = new Random();
MovingRectangle[] recs;
recs = new MovingRectangle[5];
boolean frozen = false;
for (int i = 0; i < recs.length; i++) {
int xv = rnd.nextInt(4);
int yv = rnd.nextInt(4);
int x = rnd.nextInt(400);
int y = rnd.nextInt(400);
int h = rnd.nextInt(100) + 10;
int w = rnd.nextInt(100) + 10;
recs[i] = new MovingRectangle(x, y, w, h, xv, yv, CANVAS_SIZE);
}
while (true) {
StdDraw.clear();
for (int i = 0; i < recs.length; i++) {
recs[i].draw();
recs[i].move();
}
if (StdDraw.mousePressed()) {
for (int i = 0; i < recs.length; i++) {
double x = StdDraw.mouseX();
double y = StdDraw.mouseY();
if (recs[i].containsPoint(x, y)) {
recs[i].setFrozen(true);
}
}
}
for (int i = 0; i < recs.length; i++) {
//for 0
if(recs[0].isFrozen() && recs[0].isIntersecting(recs[1])){
recs[0].setFrozen(false);
}
if(recs[0].isFrozen() && recs[0].isIntersecting(recs[2])){
recs[0].setFrozen(false);
}
if(recs[0].isFrozen() && recs[0].isIntersecting(recs[3])){
recs[0].setFrozen(false);
}
//for 1
if(recs[1].isFrozen() && recs[1].isIntersecting(recs[2])){
recs[1].setFrozen(false);
}
if(recs[1].isFrozen() && recs[1].isIntersecting(recs[3])){
recs[1].setFrozen(false);
}
if(recs[1].isFrozen() && recs[1].isIntersecting(recs[4])){
recs[1].setFrozen(false);
}
//for 2
if(recs[2].isFrozen() && recs[2].isIntersecting(recs[0])){
recs[2].setFrozen(false);
}
if(recs[2].isFrozen() && recs[2].isIntersecting(recs[1])){
recs[2].setFrozen(false);
}
if(recs[2].isFrozen() && recs[2].isIntersecting(recs[3])){
recs[2].setFrozen(false);
}
if(recs[2].isFrozen() && recs[2].isIntersecting(recs[4])){
recs[2].setFrozen(false);
}
//for 3
if(recs[3].isFrozen() && recs[3].isIntersecting(recs[0])){
recs[3].setFrozen(false);
}
if(recs[3].isFrozen() && recs[3].isIntersecting(recs[1])){
recs[3].setFrozen(false);
}
if(recs[3].isFrozen() && recs[3].isIntersecting(recs[2])){
recs[3].setFrozen(false);
}
if(recs[3].isFrozen() && recs[3].isIntersecting(recs[4])){
recs[3].setFrozen(false);
}
//for 4
if(recs[4].isFrozen() && recs[4].isIntersecting(recs[0])){
recs[4].setFrozen(false);
}
if(recs[4].isFrozen() && recs[4].isIntersecting(recs[1])){
recs[4].setFrozen(false);
}
if(recs[4].isFrozen() && recs[4].isIntersecting(recs[3])){
recs[4].setFrozen(false);
}
if(recs[4].isFrozen() && recs[4].isIntersecting(recs[2]))
recs[4].setFrozen(false);
}
if (recs[0].isFrozen() && recs[1].isFrozen() &&
recs[2].isFrozen() && recs[3].isFrozen()
&& recs[4].isFrozen()) {
StdDraw.text(400, 400, "YOU WIN");
}
StdDraw.show(20);
}
}
}
Keep in mind you're using the OR operator here. So if right is less than rLeft, your intersector will return true. This isn't how it should work.
You need to check if right is INSIDE the rectangles bounds so to speak.
if(right <= rRight && right >= rLeft || the other checks here)
The above code checks if right is less than the rectangle's right, but also that the right is bigger than rectangle's left, which means it's somewhere in middle of the rectangle's left and right.
If this becomes too complicated you can simply use java's rectangle class, as it has the methods contains and intersects
I am working on a GUI for a game of life implementation using javaFX. I am trying to draw each generation on the canvas after a one second delay, but my code does not do that. What happens is it gets a random zero generation, waits a second, generates the first generation, then waits another second generates the next one, and so on until it reaches the determined number of generations. Then after this whole proccess is done it draws the last generation only. I tried some experimenting with no luck, and now I am out of ideas. How can I get the program to draw after the calculatiion of each generation?
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class gui extends Application {
/////////////////////GUI SETUP PART/////////////////////////////////////////////
public int SquareSize = 16;
public int oldgrid [][];
public int newgrid [][];
public int ngens=5;
public int width = 10;
public int height = 10;
public int currentgen = 0;
public Group root;
public void start(Stage primaryStage) {
primaryStage.setTitle("Game of Life");
root = new Group();
oldgrid = new int [height][width];
newgrid = new int [height][width];
randomize();
Canvas canvas = new Canvas(500, 500);
GraphicsContext gc = canvas.getGraphicsContext2D();
run(gc);
root.getChildren().add(canvas);
primaryStage.setScene(new Scene(root));
primaryStage.show();
}
public void draw(GraphicsContext gc)
{
for(int y =0 ; y < getY() ; y++ )
{
for (int x = 0; x < getX() ; x++)
{
if(oldgrid[y][x] == 0)
{
gc.setFill(Color.WHITE);
gc.fillRect(x*SquareSize, y*SquareSize, SquareSize, SquareSize);
}
else if(oldgrid[y][x] == 1)
{
gc.setFill(Color.BLACK);
gc.fillRect(x*SquareSize, y*SquareSize, SquareSize, SquareSize);
}
}
}
}
////////////////////game of life rules part////////////////////////
public int getcurrentgen() {
return currentgen;
}
public int getX() {
return oldgrid[0].length;
}
public int getY() {
return oldgrid.length;
}
int Neighbours(int x, int y) //calculating neighbours
{
int neighbours = 0;
if (x > 0 && oldgrid[y][x - 1] == 1) {
neighbours++;
}
if (x < getX() - 1 && oldgrid[y][x + 1] == 1) {
neighbours++;
}
if (y < getY() - 1 && x > 0 && oldgrid[y + 1][x - 1] == 1) {
neighbours++;
}
if (y < getY() - 1 && x < getX() - 1 && oldgrid[y + 1][x + 1] == 1) {
neighbours++;
}
if (y < getY() - 1 && oldgrid[y + 1][x] == 1) {
neighbours++;
}
if (y > 0 && x > 0 && oldgrid[y - 1][x - 1] == 1) {
neighbours++;
}
if (y > 0 && x < getX() - 1 && oldgrid[y - 1][x + 1] == 1) {
neighbours++;
}
if (y > 0 && oldgrid[y - 1][x] == 1) {
neighbours++;
}
return neighbours;
}
public void setup() // applying the rules
{
for (int y = 0; y < getY(); y++) {
for (int x = 0; x < getX(); x++) {
if (oldgrid[y][x] == 1) {
if (Neighbours(x, y) < 2) {
newgrid[y][x] = 0;
}
if (Neighbours(x, y) > 3) {
newgrid[y][x] = 0;
}
if (Neighbours(x, y) == 3 || Neighbours(x, y) == 2) {
newgrid[y][x] = 1;
}
}
if (oldgrid[y][x] == 0) {
if (Neighbours(x, y) == 3) {
newgrid[y][x] = 1;
}
}
}
}
}
public void run(GraphicsContext gc)
{
draw(gc);
while(currentgen < ngens)
{
try {
Thread.sleep(1000);
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
setup();
for (int y = 0; y < getY(); y++) {
for (int x = 0; x < getX(); x++) {
oldgrid[y][x] = newgrid[y][x];
}
}
currentgen++;
draw(gc);
}
}
public void randomize() {
// randomizing dead(0) and live(1) cells
for (int y = 0; y < getY(); y++) {
for (int x = 0; x < getX(); x++) {
double tmp = Math.random();
if (tmp < 0.5) {
oldgrid[y][x] = 0;
} else {
oldgrid[y][x] = 1;
}
}
}
}
}
I am making a game in java and I have most of it done. However, one of the last bugs i need to fix is that enemy sprites can overlap each other and spawn on top of one another off screen. I want to make it so if enemy sprites collide they can only touch but not overlap. here is the code for the enemy class.
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Rectangle;
import java.util.ArrayList;
import javax.swing.ImageIcon;
public class Enemy extends Base {
int x;
int y;
int velx = -2;
int vely = 0;
public Enemy(int x, int y) {
super(x,y);
this.x = x;
this.y = y;
}
public void update() {
movement();
x += velx;
y += vely;
if (x < - 15) {
x = -15;
movement();
}
if (x > 1100) {
x = 1100;
movement();
}
if (y > 660) {
y = 660;
movement();
}
if (y < 10) {
y = 10;
movement();
}
}
public void draw(Graphics g) {
g.drawImage(getEnemyImage(), x, y, null);
}
public static Image getEnemyImage(){
ImageIcon ic = new ImageIcon("enemy.gif");
return ic.getImage();
}
public Rectangle getBounds(){
return new Rectangle(x, y, getEnemyImage().getWidth(null), getEnemyImage().getHeight(null));
}
public void checkColision(){
ArrayList<Base> enemies = GamePanel.getEnemyList();
if (x <= 0) {
velx = 2;
}
if (x >= 1096) {
velx = -2;
}
for (int a = 0; a < enemies.size(); a++) {
Base temp = GamePanel.enemy.get(a);
if (getBounds().intersects(temp.getBounds())) {
// where the collision check should happen.
}
}
}
public void movement(){
if (y > 16) {
if (x > GamePanel.p.getX()) {
velx = - 2;
}
if (x < GamePanel.p.getX()) {
velx = 2;
}
if (y > GamePanel.p.getY()) {
vely = -2;
}
if (y < GamePanel.p.getY()) {
vely = 2;
}
}
}
}
and this is where the enemies are spawned.
for (int a = 0; a < enemy_amount; a++) {
space += 50;
int rand = (int)(Math.random() * 2) + 1;
if (rand == 1) {
int randp = (int)(Math.random() * 2) + 1;
int x = 0;
int y = 0;
if (randp == 1) {
x = 1250 + space;
y = 500;
}
if (randp == 2) {
x = 1250 + space;
y = 100;
}
enemy.add(new Enemy(x,y));
}
if (rand == 2) {
int randp = (int)(Math.random() * 2) + 1;
int x = 0;
int y = 0;
if (randp == 1) {
x = 250;
y = -100 - space;
}
if (randp == 2) {
x = 850;
y = -100 - space;
}
enemy.add(new Enemy2(x,y));
}
}
any help would be great because i am really stuck.
So I'm trying to implement collision detection in my game and for some reason the collision isnt working properly.
public class ArenaKeys extends KeyAdapter {
arenaScreenBuild arena;
int xPos = 0, playerFace = 4;
int xPPos = 200, yPPos = 150;
int pX = 40, pY = 30;
AttackAshe aAtk = new AttackAshe();
int[][] mask = new int[400][92];
#SuppressWarnings("static-access")
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();// Get key pressed
if (keyCode == e.VK_RIGHT) {
playerFace = 4;
xPos += 5;
pX = (xPos + xPPos) / 5;
if (checkBoundary(pX, pY) == (false))
xPos -= 5;
} else if (keyCode == e.VK_LEFT) {
playerFace = 3;
xPos -= 5;
pX = (xPos + xPPos) / 5;
if (checkBoundary(pX, pY) == (false))
xPos += 5;
} else if (keyCode == e.VK_UP) {
playerFace = 2;
yPPos -= 5;
pY = yPPos / 5;
if (checkBoundary(pX, pY) == (false))
yPPos += 5;
} else if (keyCode == e.VK_DOWN) {
playerFace = 1;
yPPos += 5;
pY = yPPos / 5;
if (checkBoundary(pX, pY) == (false))
yPPos -= 5;
}
if (keyCode == e.VK_SPACE) {
aAtk.regArrow(arena.xPosition(), arena.yPosition());
arena.shoot(playerFace);
arena.xArrow = xPPos;
arena.yArrow = yPPos;
} else if (keyCode == e.VK_ESCAPE)
System.exit(0);
arena.moveArena(xPos);
arena.turnPlayer(playerFace);
arena.updateScreen(xPPos, yPPos);
}
public boolean checkBoundary(int x, int y) {
Rectangle t1 = new Rectangle(Turret.x, Turret.y, Turret.WIDTH,
Turret.HEIGHT);
Rectangle p = new Rectangle(pX, pY, Player.WIDTH, Player.HEIGHT);
if (t1.intersects(p))
// if (mask[x][y] == 0)
return false;
else
return true;
}
public static class Turret {
static int x = 168;
static int y = 40;
static final int WIDTH = 50;
static final int HEIGHT = 50;
}
public static class Player {
static final int WIDTH = 25;
static final int HEIGHT = 25;
}
public ArenaKeys(arenaScreenBuild arena) throws Exception {
this.arena = arena;
}
}
Approximately 20 units before the actual turret, the sprite stops being able to move any further. The sprite cannot go above or below the turret even if you go really high or really low.
What seems to be going wrong is that the sprite is colliding into the turret rectangle too early but I don't understand how that it possible. I draw the turret exactly 50 wide, 50 high at 168,40. The player is moving so it's x, y is different everytime but it's dimensions are 25 wide and 25 high.
The original turret is 126x111 approximately but I draw it as 50x50
25x25
public class arenaScreenBuild extends JPanel implements ActionListener {
String picPath = "pictures/";
String[] fileName = { "stageBridge.png", "turret.png", "Ashe.png",
"regArrow.png", "arenaScreen.png" };
ClassLoader cl = arenaScreenBuild.class.getClassLoader();
URL imgURL[] = new URL[5];
Toolkit tk = Toolkit.getDefaultToolkit();
Image imgBG, imgTurret, imgPlayer, imgRegArrow, imgBorder;
Boolean[] ptFunc = new Boolean[3];
int PLAYER_INITIAL_X = 200, PLAYER_INITIAL_Y = 150;
int xPos = 0, xPFace = 150, yPFace = 0;
int xPPos = 200, yPPos = 150;
int xVal, yVal, xArrow, yArrow, xTemp, yTemp;
Timer space;
int counter, facePosition = 1;
public arenaScreenBuild() throws Exception {
for (int x = 0; x < 5; x++) {
imgURL[x] = cl.getResource(picPath + fileName[x]);
}
imgBG = tk.createImage(imgURL[0]);
imgTurret = tk.createImage(imgURL[1]);
imgPlayer = tk.createImage(imgURL[2]);
imgRegArrow = tk.createImage(imgURL[3]);
imgBorder = tk.createImage(imgURL[4]);
for (int x = 0; x < 3; x++)
ptFunc[x] = true;
space = new Timer(100, this);
}
public void updateScreen() {
repaint();
}
public void moveArena(int x) {
xPos = x;
}
public void updateScreen(int x, int y) {
xPPos = x;
yPPos = y;
repaint();
}
public boolean arrow() {
return (true);
}
public void turnPlayer(int face) {
if (face == 4) {
xPFace = 150;
} else if (face == 3) {
xPFace = 100;
} else if (face == 2) {
xPFace = 50;
} else if (face == 1) {
xPFace = 0;
}
if (yPFace == 50)
yPFace = 0;
else if (yPFace == 0)
yPFace = 50;
}
public void paintComponent(Graphics g) {
g.drawImage(imgBG, 10, 30, 610, 490, xPos, 0, xPos + 600, 460, this);
g.drawImage(imgTurret, 850 - xPos, 200, 950 - xPos, 300, 0, 0, 126,
110, this);
g.drawImage(imgTurret, 1350 - xPos, 200, 1450 - xPos, 300, 0, 0, 126,
110, this);
g.drawImage(imgPlayer, xPPos, yPPos, 50 + (xPPos),
50 + (yPPos), xPFace, yPFace, xPFace + 50, yPFace + 50, this);
if (counter <= 5000 && counter > 0)
g.drawImage(imgRegArrow, xArrow, yArrow, this);
g.drawImage(imgBorder, 0, 0, 620, 600, 0, 0, 620, 600, this);
g.setColor(Color.WHITE);
g.drawString("x:" + (xPPos + xPos), 535, 525);
g.drawString("y:" + yPPos, 535, 545);
}
public int xPosition() {
xVal = xPPos + xPos;
return (xVal);
}
public int yPosition() {
yVal = yPPos;
return (yVal);
}
public void shoot(int i) {
facePosition = i;
xTemp = xPosition();
yTemp = yPosition();
space.start();
}
public void actionPerformed(ActionEvent e) {
counter++;
if (facePosition == 4) {
if (counter <= 5000) {
xArrow += 50;
}
}
else if (facePosition == 3) {
if (counter <= 5000) {
xArrow -= 50;
}
}
else if (facePosition == 2) {
if (counter <= 5000) {
yArrow -= 50;
}
}
else if (facePosition == 1) {
if (counter <= 5000) {
yArrow += 50;
}
}
if (xArrow == (xTemp + 100)) {
counter = 0;
space.stop();
}
updateScreen();
}
}
Turns out that my values for the x position were wrong. Also due to my previous boundary code, there were still remenants of it which messed me up therefore not allowing me to see the problem sooner.
For any one looking for how to make the collision detection boundary, just make 2 rectangles and use the
Rectangle rect1 = new Rectangle(topLeftX, topLeftY, rectangleWidth,rectangleHeight);
Rectangle rect2 = new Rectangle(topLeftX, topLeftY, rectangleWidth, rectangleHeight);
if (rect1.intersects(rect2))
//enter code to do if it intersects here