keeping sprites from colliding java - java

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.

Related

Minesweeper draw number of nearby mines

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.

Unusual bad program performance in Java

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);
}

Stuck with JavaFX GUI, how to draw/print after each state/calculation?

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;
}
}
}
}
}

How can I make the image move in a random position?

I have an image inside the panel and it moves in a clockwise direction. Now, I want it to move in a random direction and that is my problem.
Could someone give me an idea how to do it?
Here's what I've tried :
private int xVelocity = 1;
private int yVelocity = 1;
private int x, y;
private static final int RIGHT_WALL = 400;
private static final int UP_WALL = 1;
private static final int DOWN_WALL = 400;
private static final int LEFT_WALL = 1;
public void cycle()
{
x += xVelocity;
if (x >= RIGHT_WALL)
{
x = RIGHT_WALL;
if (y >= UP_WALL)
{
y += yVelocity;
}
}
if (y > DOWN_WALL)
{
y = DOWN_WALL;
if (x >= LEFT_WALL)
{
xVelocity *= -1;
}
}
if (x <= LEFT_WALL)
{
x = LEFT_WALL;
if (y <= DOWN_WALL)
{
y -= yVelocity;
}
}
if (y < UP_WALL)
{
y = UP_WALL;
if (x <= RIGHT_WALL)
{
xVelocity *= -1;
}
}
}
Call a method like this to set a random direction:
public void setRandomDirection() {
double direction = Math.random()*2.0*Math.PI;
double speed = 10.0;
xVelocity = (int) (speed*Math.cos(direction));
yVelocity = (int) (speed*Math.sin(direction));
}
Just noticed that you're cycle method will need a little fixing for this to work.
public void cycle() {
x += xVelocity;
y += yVelocity; //added
if (x >= RIGHT_WALL) {
x = RIGHT_WALL;
setRandomDirection();//bounce off in a random direction
}
if (x <= LEFT_WALL) {
x = LEFT_WALL;
setRandomDirection();
}
if (y >= DOWN_WALL) {
y = DOWN_WALL;
setRandomDirection();
}
if (y <= UP_WALL) {
y = UP_WALL;
setRandomDirection();
}
}
(It works, but this is not the most efficient/elegant way to do it)
And if you want some sort of 'random walk' try something like this:
public void cycle() {
//move forward
x += xVelocity;
y += yVelocity;
if (Math.random() < 0.1) {//sometimes..
setRandomDirection(); //..change course to a random direction
}
}
You can increase 0.1 (max 1.0) to make it move more shaky.
Change
y -= yVelocity;
To
if (y>0) {
y = -1*Random.nextInt(3);
} else {
y = Random.nextInt(3);
}

Can anyone help me understand how to simulate fluids?

I'm trying to make a program that simulates the physics of fluids in Processing. In the IDE there's an included example:
/**
* Fluid
* by Glen Murphy.
*
* Click and drag the mouse to move the simulated fluid.
* Adjust the "res" variable below to change resolution.
* Code has not been optimised, and will run fairly slowly.
*/
int res = 2;
int penSize = 30;
int lwidth;
int lheight;
int pnum = 30000;
vsquare[][] v;
vbuffer[][] vbuf;
particle[] p = new particle[pnum];
int pcount = 0;
int mouseXvel = 0;
int mouseYvel = 0;
void setup()
{
size(200, 200);
noStroke();
frameRate(30);
lwidth = width/res;
lheight = height/res;
v = new vsquare[lwidth+1][lheight+1];
vbuf = new vbuffer[lwidth+1][lheight+1];
for (int i = 0; i < pnum; i++) {
p[i] = new particle(random(res,width-res),random(res,height-res));
}
for (int i = 0; i <= lwidth; i++) {
for (int u = 0; u <= lheight; u++) {
v[i][u] = new vsquare(i*res,u*res);
vbuf[i][u] = new vbuffer(i*res,u*res);
}
}
}
void draw()
{
background(#666666);
int axvel = mouseX-pmouseX;
int ayvel = mouseY-pmouseY;
mouseXvel = (axvel != mouseXvel) ? axvel : 0;
mouseYvel = (ayvel != mouseYvel) ? ayvel : 0;
for (int i = 0; i < lwidth; i++) {
for (int u = 0; u < lheight; u++) {
vbuf[i][u].updatebuf(i,u);
v[i][u].col = 32;
}
}
for (int i = 0; i < pnum-1; i++) {
p[i].updatepos();
}
for (int i = 0; i < lwidth; i++) {
for (int u = 0; u < lheight; u++) {
v[i][u].addbuffer(i, u);
v[i][u].updatevels(mouseXvel, mouseYvel);
v[i][u].display(i, u);
}
}
}
class particle {
float x;
float y;
float xvel;
float yvel;
int pos;
particle(float xIn, float yIn) {
x = xIn;
y = yIn;
}
void updatepos() {
float col1;
if (x > 0 && x < width && y > 0 && y < height) {
int vi = (int)(x/res);
int vu = (int)(y/res);
vsquare o = v[vi][vu];
float ax = (x%res)/res;
float ay = (y%res)/res;
xvel += (1-ax)*v[vi][vu].xvel*0.05;
yvel += (1-ay)*v[vi][vu].yvel*0.05;
xvel += ax*v[vi+1][vu].xvel*0.05;
yvel += ax*v[vi+1][vu].yvel*0.05;
xvel += ay*v[vi][vu+1].xvel*0.05;
yvel += ay*v[vi][vu+1].yvel*0.05;
o.col += 4;
x += xvel;
y += yvel;
}
else {
x = random(0,width);
y = random(0,height);
xvel = 0;
yvel = 0;
}
xvel *= 0.5;
yvel *= 0.5;
}
}
class vbuffer {
int x;
int y;
float xvel;
float yvel;
float pressurex = 0;
float pressurey = 0;
float pressure = 0;
vbuffer(int xIn,int yIn) {
x = xIn;
y = yIn;
pressurex = 0;
pressurey = 0;
}
void updatebuf(int i, int u) {
if (i>0 && i<lwidth && u>0 && u<lheight) {
pressurex = (v[i-1][u-1].xvel*0.5 + v[i-1][u].xvel + v[i-1][u+1].xvel*0.5 - v[i+1][u-1].xvel*0.5 - v[i+1][u].xvel - v[i+1][u+1].xvel*0.5);
pressurey = (v[i-1][u-1].yvel*0.5 + v[i][u-1].yvel + v[i+1][u-1].yvel*0.5 - v[i-1][u+1].yvel*0.5 - v[i][u+1].yvel - v[i+1][u+1].yvel*0.5);
pressure = (pressurex + pressurey)*0.25;
}
}
}
class vsquare {
int x;
int y;
float xvel;
float yvel;
float col;
vsquare(int xIn,int yIn) {
x = xIn;
y = yIn;
}
void addbuffer(int i, int u) {
if (i>0 && i<lwidth && u>0 && u<lheight) {
xvel += (vbuf[i-1][u-1].pressure*0.5
+vbuf[i-1][u].pressure
+vbuf[i-1][u+1].pressure*0.5
-vbuf[i+1][u-1].pressure*0.5
-vbuf[i+1][u].pressure
-vbuf[i+1][u+1].pressure*0.5
)*0.25;
yvel += (vbuf[i-1][u-1].pressure*0.5
+vbuf[i][u-1].pressure
+vbuf[i+1][u-1].pressure*0.5
-vbuf[i-1][u+1].pressure*0.5
-vbuf[i][u+1].pressure
-vbuf[i+1][u+1].pressure*0.5
)*0.25;
}
}
void updatevels(int mvelX, int mvelY) {
if (mousePressed) {
float adj = x - mouseX;
float opp = y - mouseY;
float dist = sqrt(opp*opp + adj*adj);
if (dist < penSize) {
if (dist < 4) dist = penSize;
float mod = penSize/dist;
xvel += mvelX*mod;
yvel += mvelY*mod;
}
}
xvel *= 0.99;
yvel *= 0.99;
}
void display(int i, int u) {
float tcol = 0;
if (col > 255) col = 255;
if (i>0 && i<lwidth-1 && u>0 && u<lheight-1) {
tcol = (+ v[i][u+1].col
+ v[i+1][u].col
+ v[i+1][u+1].col*0.5
)*0.4;
tcol = (int)(tcol+col*0.5);
}
else {
tcol = (int)col;
}
fill(tcol, tcol, tcol);
rect(x,y,res,res);
}
}
It's not really commented and I'm somewhat new to programming, so I have no idea where to start as far as understanding it. Is there any good reading on fluid physics? I'm more interesting in the visual effect than the accuracy of the simulation.
A good starting point could be the paper Stable Fluids, it will show you the math behind the fluid simulation, and in the third chapter it describe the implementation of a fluid solver. There is also an open source implementation available in sourceforge (you will need to checkout the source with cvs).

Categories