for-each loop in Java for different objects - java

i created a pacman game with everything in it but the problem is that the ghosts and their animation require a lot of code.
example:
every ghost needs 3 if statements at the moment that is 20 lines of code per ghost and if i have 3 ghosts in the game that is 3 x 20 = 60 lines of useless coding..
with my php experience i would say.. use a foreach loop or something similar.. but how should i do this in Java? can someone give me an example? the way i do it now is published below:
creating ghost objects;
DrawPacMan ghost1 = new DrawPacMan();
DrawPacMan ghost2 = new DrawPacMan();
and the painting goes like:
int g1x = 0;
boolean g1r = true;
public void paintComponent(Graphics g) {
super.paintComponent(g);
// pacman movement
diameter = 75;
pacman.drawPacMan(g, getHorPlaats(), getVerPlaats(), diameter, getView(), Color.yellow);
// ghosts movement
if(g1r == true) {
g1x += ghostSpeed;
}
if(g1r == false) {
g1x -= ghostSpeed;
}
if(g1x == 500 || g1x == 0) {
g1r = !g1r;
}
System.out.println(g1r);
ghost1.drawGhost(g, g1x, 40, diameter, Color.red);
ghost2.drawGhost(g, 170, 70, diameter, Color.blue);
}

It looks to me like you're not approaching this in a object-oriented fashion. Why not use a collection of ghosts eg. List<Ghost> and define a Ghost object with it's location, colour etc?
This line:
ghost1.drawGhost(g, g1x, 40, diameter, Color.red);
would then be replace with
ghost.draw(g);
and you'd iterate through the list, calling draw() for each.
for(Ghost ghost : ghosts) {
ghost.draw(g); // pass in the graphics context
}
Each ghost knows it's location, colour, state etc. and you can create as many as you like:
List<Ghost> ghosts = new ArrayList<Ghost>();
for (int i = 0; i < 10; i++) {
ghosts.add(new Ghost());
}

Since you seem to be new to Java and still getting to know the best idioms, I'll advise on something that is not directly an answer to your question, but is so in a more general sense. Your code
if(g1r == true) {
g1x += ghostSpeed;
}
if(g1r == false) {
g1x -= ghostSpeed;
}
can be rewritten as just
g1x += ghostSpeed * (g1r? 1 : -1);
A general note: never compare booleans to literal values. b == true is the same as just b and b == false is the same as !b.
This code
if (g1x == 500 || g1x == 0) {
g1r = !g1r;
}
will probably result in a bug at runtime as you don't precede it with fencing-in code: g1x can easily step over your limits. You should write instead
if (g1x >= 500) { g1x = 500; g1r = false; }
else if (g1x <= 0) { g1x = 0; g1r = true; }

Pass the ghost object as another parameter in the same function paintComponent(Graphics g, Ghost gr)
You can make the conditional statements inline, e.g. g1r == true ? g1x += ghostSpeed : g1x -= ghostSpeed

Related

Java how to check if an object in an arraylist contains a certain value

Hello I have a programme where you place tiles to build houses and then you sell the houses. I only want to sell the houses if the building has a door an at least one window.
My arraylist looks like this:
public static ArrayList<block> b = new ArrayList<block>();
every type of tile has an id. the door tile is 1 and the windows tile is 2 and the wall tile is 3.
for(int i = 0; i < play.b.toArray().length;i++){
if(play.b.contains(play.b.get(i).id == 1)){
cansell= true;
}else{
cansell= false;
}
}
How can I check to see if an object in an arraylist contains a certain value , in this case the value 1.
here is the door class:
public class door extends block{
public cockpit(int x,int y,int rot){
this.x = x;
this.y = y;
this.rotate = rot;
r = new Rectangle(x - (int)play.camx,y - (int)play.camy,20,20);
id = 3;
}
public void tick(){
createCollisionRect();
if(Comp.mr && r.contains(new Point((Comp.mx ) ,(Comp.my) ))){
remove = true;
}
if(remove){
//play.gui.money +=800;
}
}
public void render(Graphics g){
Graphics2D g2 = (Graphics2D) g;
if (rotate == 0) {
ImageIcon i62 = new ImageIcon("res/tiles/cockpit.png");
img = i62.getImage();
g.drawImage(img, x - (int) play.camx, y - (int) play.camy,20,20, null);
}
if (rotate == 1) {
AffineTransform at = AffineTransform.getTranslateInstance(x, y);
at.rotate(Math.toRadians(90),10,10);
ImageIcon i62 = new ImageIcon("res/tiles/cockpit.png");
img = i62.getImage();
g2.drawImage(img,at, null);
}
if (rotate == 2) {
AffineTransform at = AffineTransform.getTranslateInstance(x, y);
at.rotate(Math.toRadians(180),10,10);
ImageIcon i62 = new ImageIcon("res/tiles/cockpit.png");
img = i62.getImage();
g2.drawImage(img, at, null);
}
if (rotate == 3) {
AffineTransform at = AffineTransform.getTranslateInstance(x, y);
at.rotate(Math.toRadians(-90),10,10);
ImageIcon i62 = new ImageIcon("res/tiles/cockpit.png");
img = i62.getImage();
g2.drawImage(img, at, null);
}
}
}
This seems quite straight forward.
Note there is no need to get "id" ... the ArrayList stores the values itself.
You simply need to check if the index placement value in the array contains the value you are looking for:
for(int i = 0; i < play.b.toArray().length;i++){
String valueID = play.b.get(i);
if(valueID.contains("1")){
cansell= true;
}else{
cansell= false;
}
}
That should answer your question, if not, this really does help: JArrayLists
Hope this answers your question.
Let me know of the outcome
if(play.b.contains(play.b.get(i).id == 1)){ will evaluate to something like if(play.b.contains(true)){ (or false respectively). So, since you have int in your ArrayList you should change the code following:
cansell = play.b.contains(1);
instead the whole loop.
Per the update in comments:
public void canSell () {
cansell = play.b.contains(1) && play.b.contains(2);
}
From: Oracle Java Docs on Lists

Creation of Bullets using objects in a game [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have some Processing code where I need to create a new rectangular box when a certain key is pressed and I need to have multiples of these on screen. I have all the code setup so that when I press a key something can happen, but I've tried to create new objects infinitely and I can't get it to work.
Code:
public float translateX = 0;
public float translateY = 260;
public float translateZ = 10000;
float bulletX, bulletY, bulletZ;
public int rotationBlue = 1;
public int rotationGreen = 1;
public int rotationRed = 1;
public boolean shootBool = false;
public boolean shootBoolVal = true;
void setup() {
size(1280, 720, P3D);
frameRate(60);
}
void draw() {
background(0);
translate(640, 360, -10000);
fill(0);
box(100000);
ship();
control();
}
void control() {
if (keyPressed) {
if (key == 'a' || key == 'A') {
translateX = translateX - 5;
}
if (key == 'd' || key == 'D') {
translateX = translateX + 5;
}
if ((key == 's' || key == 'S')) {
translateZ = translateZ + 5;
}
if ((key == 'w' || key == 'W')) {
translateZ = translateZ - 5;
}
if ((key == 'q' || key == 'Q')) {
translateY = translateY - 5;
}
if ((key == 'e' || key == 'E')) {
translateY = translateY + 5;
}
if (key == 'f' || key == 'F') {
}
}
}
public void ship() {
fill(0, 0, 255);
stroke(255);
strokeWeight(3);
translate(translateX, translateY, translateZ);
//translate(mouseX, mouseY, 0);
rotateX(radians(rotationBlue));
rotateY(radians(rotationBlue));
rotateZ(radians(rotationBlue));
rotationBlue++;
box(100);
fill(0, 255, 0);
rotateX(radians(rotationGreen));
rotateY(radians(rotationGreen));
rotateZ(radians(rotationGreen));
rotationGreen--;
box(100);
fill(255, 0, 0);
rotateX(radians(rotationRed));
rotateY(radians(rotationRed));
rotateZ(radians(rotationRed));
rotationRed = rotationRed + 2;
box(100);
//translateZ = translateZ - 5;
}
This is all the code that I have so far. I need to be able to have it so that when I press the "F" key (which is already defined in the function control), a new box is created at the coordinates of the ship which has it's own Z direction decreasing constantly. Remember, I must be able to have more than one of these boxes at once.
I would like someone to tell me what steps I must take to do this.
These are the steps required to obtain what you need:
define a custom Bullet object containing position, velocity and other required attributes, possibly also a draw function
declare a collection of these Bullet objects
when you want to shoot a bullet just add it to the collection
to draw all the bullets iterate over the collection in the draw() method
to update the attributes of all the bullets define an update() method which updates velocity, position etc. for every bullet, called by the draw() function too

Drawing mountains using 1px swing rectangles

I'm trying to draw mountains background using 1-width rectangles (something like integrals). I randomize the first point to the very left of the screen, randomize binary number and draw the first rectangle.
If binary number is 0, the next rectangle will be 1px lower. Else higher. And so on in the for loop.
There's a 95% chance that in the next loop the direction won't change and it will keep going higher/lower. And 5% chance the direction will change. For this I'm using randomized number from 1 to 1000.
public Landscape(Graphics g)
{
Graphics2D g2d = (Graphics2D)g;
Random rand = new Random();
int first = rand.nextInt((800 - 200) + 1) + 200;
g2d.fillRect(0, 800 - first, 1, first);
int d = first % 2;
for(int i = 1; i <= 800; i++) {
int choose = rand.nextInt((1000 - 1) + 1) + 1;
if(choose > 950) {
d = -(d);
}
if(d == -1) {
first += 1;
} else {
first -= 1;
}
g2d.fillRect(i, 800 - first, 1, first);
}
}
That's the effect I get in like half cases. Sometimes however I get something like this:
How is this possible? What's wrong here?
Here:
int d = first % 2;
d is either 1 or 0. If d is assigned 0, then if(d == -1) { is always false, and thus your graph will go monotonically downwards.
You are looking for a two state solution to decide whether the mountain goes up or down, so use a boolean. Perhaps something like:
boolean direction = rand.nextBoolean();
// 1 in 20 chance, same as 5 in 100, same as 50 in 1000 chance
if (rand.nextInt(20) == 0) {
direction = !direction;
}
if (direction) {
// ...
} else {
// ...
}
Myself, I'd look into using fractals.

Java game - Submarine killer - Launch the bomb anytime I press my down key

so I have this code, I'm trying to learn Java and this is basically my first game, it's similar to SubmarineKiller where you are a boat, launching bombs at the submarine.
My class below is the bomb. When I press the Down arrow, the bomb launches but I can't launch another one until it hits the submarine or it goes out of screen. My question is: How can I fire the next bomb as soon as the first one left the boat? Basically launch a bomb anytime I press my down key.
public void keyPressed(KeyEvent evt) {
int code = evt.getKeyCode();
if (code == KeyEvent.VK_DOWN) {
if (bomb.isFalling == false)
bomb.isFalling = true;
}
}
-
private class Bomb {
int centerX, centerY;
boolean isFalling;
Bomb() {
isFalling = false;
}
void updateForNewFrame() {
if (isFalling) {
if (centerY > height) {
isFalling = false;
}
else
if (Math.abs(centerX - sub.centerX) <= 36 && Math.abs(centerY - sub.centerY) <= 21) {
sub.isExploding = true;
sub.explosionFrameNumber = 1;
isFalling = false; // Bomba reapare in barca
}
else {
centerY += 10;
}
}
}
void draw(Graphics g) {
if ( !isFalling ) {
centerX = boat.centerX;
centerY = boat.centerY + 23;
}
g.setColor(Color.RED);
g.fillOval(centerX - 8, centerY - 8, 16, 16);
}
}
You need to rewrite your code in terms of a list of bombs rather than a single bomb. Then, your key pressed event needs to change to add a new bomb to the list rather than just setting the properties of the single bomb. Your processing code will then also need to change - you'll need to loop over the list and process each bomb in turn.

Java moving a image up and down, animated motion

I'm wondering how I can move an image after it has been drawn?
Heres my code for drawing the image:
public int probeX = 500;
public int Minerals = 400;
public int drawProbeA, drawProbe = 0;
public void init() {
// Images Call
probe = getImage(getDocumentBase(), "image/probe.png");
}
public void paint(Graphics g) {
if (drawProbe == 1) {
for (int k = 0; k < drawProbeA; k++) {
g.drawImage(probe, probeX, 474, 50, 50, this);
probeX += 50;
}
probeX = 500;
}
}
public boolean mouseDown(Event e, int x, int y) {
// Clicking on the probe icon
if (x > 1068 && x < 1119 && y > 785 && y < 832 && onNexus == 1
&& Minerals >= 50) {
drawProbeA += 1;
drawProbe = 1;
Minerals -= 50;
}
return true;
}
How can I make it so that after the images are drawn, that hitting an icon will cause the image to be auto moved down the y-axis (like 50 pixels)? Basically, like sliding the image down with an animation? And then stop and then move back up to the orginal spot.
I am using an Applet and would like the animation to loop repeatedly. Thanks.
You need to have a global variable, or another variable somewhere, that indicates that...
The image needs to move
How far in the Y direction it has moved already
Which direction it is going (up or down)
When you have this, you need to add code to your paint() method to draw the image in the correct spot.
You would also need a Timer or Thread that will tell the component to repaint() every few milliseconds, and change your global variables so that it will repaint it lower/higher.
So, as a bit of an example, you might have some global variables like this...
int yPosition = 0;
boolean goingDown = true;
When you need to start your animation, start a Timer that calls the following over and over...
if (goingDown == true){
// if we've gone down 50 pixels, start going up again
if (yPosition <= 0){
goingDown = false;
yPosition++;
}
else {
yPosition--; // move it down 1 pixel
}
}
else {
// if we're going up and we reach 0, go down again
if (yPosition >= 50){
goingDown = true;
yPosition--;
}
else {
yPosition++; // move it up1 pixel
}
}
component.repaint(); // this will call the paint() method
Not your paint method just need to draw your image at the different position. Just change the g.drawImage(probe,probeX,474,50,50,this); like to include the yPosition...
g.drawImage(probe,probeX,474+yPosition,50,50,this);
This should at least point you in the right direction.

Categories

Resources