Results 1 to 14 of 14
  1. #1
    Bgreen7887 is offline Senior Member
    Join Date
    Oct 2010
    Location
    Newark,nj
    Posts
    111
    Rep Power
    0

    Default Call to main() twice ??

    Have made a basic 2d alien shooting game in java. Besides the dirty way i thought of in my mind of called the main method , through another method, is there a way to run all my code over again. I simply want to replay the game without recompiling it.

  2. #2
    awinston is offline Student
    Join Date
    Jul 2012
    Location
    United States
    Posts
    328
    Rep Power
    2

    Default Re: Call to main() twice ??

    It sounds like you should have something like a playGame() method inside of a while() statement. At the end of your playGame() method you could ask the user if he or she wants to play again, and if he says yes, the condition of your while statement is set to true. If he says no, the condition of the while statement is set to false. Like this:

    Java Code:
    public static void main(String[] args)
    {
        while(playAgain)
        {
            playGame();
        }
    }
    "Success is not final, failure is not fatal: it is the courage to continue that counts." - Winston Churchill

  3. #3
    jfabian is offline Member
    Join Date
    Jun 2012
    Posts
    22
    Rep Power
    0

    Default Re: Call to main() twice ??

    Of course you can, using Threads.

  4. #4
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default Re: Call to main() twice ??

    Quote Originally Posted by jfabian View Post
    Of course you can, using Threads.
    Sorry, but your answer makes no sense whatsoever.

  5. #5
    jfabian is offline Member
    Join Date
    Jun 2012
    Posts
    22
    Rep Power
    0

    Default Re: Call to main() twice ??

    What I'm trying to say is that, he wants run the game again without recompile it. He could use threads to run it again, everytime he wants, just launching a new thread.

  6. #6
    Bgreen7887 is offline Senior Member
    Join Date
    Oct 2010
    Location
    Newark,nj
    Posts
    111
    Rep Power
    0

    Default Re: Call to main() twice ??

    Hi fubarable, it's not exactly as you said ... I have a board which is a JPanel, which i add to a jframe. Here are the 2 of the 5 classes.

    Java Code:
    Board.java
    package com.danger87.shoot;
    
    import java.awt.Color;
    import java.awt.Font;
    import java.awt.FontMetrics;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Rectangle;
    import java.awt.Toolkit;
    import java.awt.event.*;
    
    import java.util.ArrayList;
    
    import javax.swing.JPanel;
    import javax.swing.Timer;
    import javax.swing.JTextField;
    public class Board extends JPanel implements ActionListener{
    	/**
    	 * 
    	 */
    	private static final long serialVersionUID = 1L;
    	/**
    	 * 
    	 */
    	//private static final long serialVersionUID = 1L;
    	private Timer timer;
    	JTextField jf = new JTextField();
    	private Ufo ufo;
    	private ArrayList<Alien>aliens;
    	private boolean in_game;
    	private int B_WIDTH;
    	private int B_HEIGHT;
    	
    	private int[][] pos = {
    			{2380, 29}, {2500, 59}, {1380, 89},
    			{780, 109}, {580, 139}, {680, 239},
    			{790, 259}, {760, 50},  {790, 150}, 
    			{980, 209}, {560, 45},  {510,  70}, 
    			{930, 159}, {590, 80},  {530, 60}, 
    			{940, 59}, {990, 30},   {920, 200}, 
    			{900, 259}, {660, 50},  {540, 90},
    			{810, 220}, {860, 20},  {740, 180}, 
    			{820, 128}, {490, 170}, {700, 30}, 
    	};
    	
    	public Board() {
    		addKeyListener(new TAdapter());
    		setFocusable(true);
    		setBackground(Color.BLACK);
    		setDoubleBuffered(true);
    		in_game = true;
    		
    		setSize(400, 300);
    		
    		ufo = new Ufo();
    		
    		initAliens();
    		
    		timer = new Timer(8, this);
    		timer.start();
    	}
    	
    
    	public void addNotify() {
    		super.addNotify();
    		B_WIDTH = getWidth();
    		B_HEIGHT = getHeight();
    	}
    	
    	public void initAliens() {
    		aliens = new ArrayList<Alien>();
    		
    		for (int i=0; i <pos.length; i++) {
    			aliens.add(new Alien(pos[i][0], pos[i][1]));
    		}
    	}
    	
    	public void paint (Graphics g) {
    		
    		super.paint(g);
    		
    		if (in_game) {
    			Graphics2D g2d = (Graphics2D)g;
    			
    			if (ufo.isVisible()) 
    				g2d.drawImage(ufo.getImage(), ufo.getX(), ufo.getY(), this);
    			
    			ArrayList<Missile> ms = ufo.getMissiles();
    			
    			for (int i = 0; i < ms.size(); i++) {
    				Missile m = (Missile)ms.get(i);
    				g2d.drawImage(m.getImage(),m.getX(),m.getY(),this);
    			}
    			
    			for (int i = 0; i < aliens.size(); i++) {
    				Alien a = (Alien)aliens.get(i);
    				if (a.isVisible())
    					g2d.drawImage(a.getImage(),a.getX(),a.getY(),this);
    				}
    			g2d.setColor(Color.WHITE);
    			g2d.drawString("Aliens left: " + aliens.size(), 5, 15);
    			
    		} else {
    			String msg = "Game Over";
    			Font small = new Font("Helvetica", Font.BOLD, 14);
    			FontMetrics metr = this.getFontMetrics(small);		
    			
    			g.setColor(Color.white);
    			g.setFont(small);
    			g.drawString(msg, (B_WIDTH - metr.stringWidth(msg))/2,B_HEIGHT /2);
    			jf.setText("Play again?");
    			//g.drawString(msg1, (B_WIDTH - metr.stringWidth(msg))/2,B_HEIGHT/3);
    		}
    		
    		Toolkit.getDefaultToolkit().sync();
    		g.dispose();
    	}
    	
    	public void actionPerformed(ActionEvent e) {
    		
    		if (aliens.size() == 0) {
    			in_game = false;
    		}
    		
    		ArrayList<Missile> ms = ufo.getMissiles();
    		
    		for (int i = 0; i < ms.size(); i++) {
    			Missile m = (Missile) ms.get(i);
    			if (m.isVisible())
    				m.move();
    			else ms.remove(i);
    		}
    		for (int i = 0; i < aliens.size(); i++) {
    			Alien a = (Alien) aliens.get(i);
    			if (a.isVisible())
    				a.move();
    			else aliens.remove(i);
    		}
    		ufo.move();
    		checkCollison();
    		repaint();
    		
    	}
    	
    	public void checkCollison() {
    		Rectangle r3 = ufo.getBounds();
    		
    		for (int j = 0; j <aliens.size(); j++) {
    			Alien a = (Alien) aliens.get(j);
    			Rectangle r2 = a.getBounds();
    			
    			if(r3.intersects(r2)) {
    				ufo.setVisible(false);
    				a.setVisible(false);
    				in_game = false;
    			}
    		}
    		
    		ArrayList<Missile> ms = ufo.getMissiles();
    		
    		for (int i = 0; i < ms.size(); i++) {
    			Missile m = (Missile) ms.get(i);
    			
    			Rectangle r1 = m.getBounds();
    			
    			for (int j = 0; j <aliens.size(); j++) {
    				Alien a = (Alien) aliens.get(j);
    				Rectangle r2 = a.getBounds();
    				
    				if (r1.intersects(r2)) {
    					m.setVisible(false);
    					a.setVisible(false);
    				}			
    			}
    		}
    	}
    	private class TAdapter extends KeyAdapter {
    		public void keyReleased(KeyEvent e) {
    			ufo.keyReleased(e);
    		}
    		public void keyPressed(KeyEvent e) {
    			ufo.keyPressed(e);
    		}
    	}
    }
    Java Code:
    Collision.java
    
    package com.danger87.shoot;
    
    
    import javax.swing.JFrame;
    
    public class Collision extends JFrame {
    
        /**
    	 * 
    	 */
    	private static final long serialVersionUID = 1L;
    
    	public Collision() {
            add(new Board());
    
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setSize(400, 300);
            setLocationRelativeTo(null);
            setTitle("Collision");
            setResizable(true);
            setVisible(true);
        }
    
        public static void main(String[] args) {
            new Collision();
        }
    }
    I am a beginner at graphics in this project im specifically understanding collision detection and animation. Any tips would be helpful.

  7. #7
    kammce's Avatar
    kammce is offline Senior Member
    Join Date
    Dec 2010
    Location
    California
    Posts
    194
    Rep Power
    4

    Default Re: Call to main() twice ??

    Quote Originally Posted by Bgreen7887 View Post
    I am a beginner at graphics in this project im specifically understanding collision detection and animation. Any tips would be helpful.
    Well, my suggestion for this would be to, A) create your own collision detection function using x,y,width and height calculations in order to detect when two objects have intersected each other. Creating your own can make your program more powerful if you do it that way. or B) you can go the easy route (probably better for a beginner), to use Rectangle Java Class the intersects(Rectangle r); method to figure out if they intersect.
    My API:
    Java Code:
    cat > a.out || cat > main.class

  8. #8
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default Re: Call to main() twice ??

    Quote Originally Posted by jfabian View Post
    What I'm trying to say is that, he wants run the game again without recompile it. He could use threads to run it again, everytime he wants, just launching a new thread.
    No. There's simply no need to do this, and in fact since we see his program is a Swing GUI program, then this answer is out and out wrong, since all Swing GUI's must run on one thread and one thread alone, the EDT.
    Last edited by Fubarable; 07-18-2012 at 06:30 PM.

  9. #9
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default Re: Call to main() twice ??

    • Don't draw in a JPanel's paint(...) method but rather in its paintComponent(...) method.
    • When you make this correction, be sure to call the super's paintComponent(...) method inside similar to what you're currently doing with paint.
    • Don't dispose of a Graphics object that you don't create yourself. You're disposing the one given to you by the JVM as the paint method's parameter and this can cause problems with the program's ability to draw components.

  10. #10
    Bgreen7887 is offline Senior Member
    Join Date
    Oct 2010
    Location
    Newark,nj
    Posts
    111
    Rep Power
    0

    Default Re: Call to main() twice ??

    Hi Fubarable,
    Are you suggesting this for the current code because it is more correct way of doing it in general. Or are you suggesting to lead up to my goal of replaying the game, which is why i was thinking about calling main twice.

  11. #11
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default Re: Call to main() twice ??

    Quote Originally Posted by Bgreen7887 View Post
    Hi Fubarable,
    Are you suggesting this for the current code because it is more correct way of doing it in general.
    It is general recommendations for your current code.

    Or are you suggesting to lead up to my goal of replaying the game, which is why i was thinking about calling main twice.
    No, you most definitely do not want to "call main twice". You want to give your GUI a reset() method that calls reset() methods in all component classes you've written that resets everything to initial condition and allows the game to restart. The main method should only be called once and that by the JVM.

  12. #12
    Bgreen7887 is offline Senior Member
    Join Date
    Oct 2010
    Location
    Newark,nj
    Posts
    111
    Rep Power
    0

    Default Re: Call to main() twice ??

    Sorry for the delay .... Im changing the painting to be done in the paint component method and also reading up on it. I still can't understand how one method will call all other methods in other classes as i have 5. Alien.java,Ufo.java,Missile.java,Board.java(extend s JPanel),and Collision.java. That's where i add the board to a class extending the JFrame and main is also within that class. Once game is over it just displays "game over", maybe i can add a button with reset in it and make that button call the other methods.. Once i figure out how to do that lol .

  13. #13
    kammce's Avatar
    kammce is offline Senior Member
    Join Date
    Dec 2010
    Location
    California
    Posts
    194
    Rep Power
    4

    Cool Re: Call to main() twice ??

    The way that one program can interact with another has to do with object orientation.
    For example. For my game, I have a program called GINIT.java it creates an object Scene s = new Scene();. What ever is inside of the object's public method is initiated. The public method within Scene creates a JFrame, which is why I named it scene. (there should only be one JFrame, for the most part).

    So GINIT can call any method, function, variable etc that exists within Scene as long as it is public. And Scene, is some way, shape, or form, holds objects to every single object in my project.

    For scene, I have objects for my MainMenu title = new MainMenu(); and my game object Field fieldv = new Field(); and what ever is inside of those, Scene can access and use.
    NOTE: That GINIT can use the methods from MainMenu and Field via Scene. But Scene handles everything for me, so there is no reason to have GINIT do anything except initiate the game, but it still CAN if I wanted it too!! Just as long as the variables are public

    So think of it as either owning an a class as an object or making a copy of a class to use as an Object (if you can understand that).

    So the order of ownership should be like this:
    • GINIT -> Scene ~> MainMenu && Field
    • Scene -> MainMenu && Field


    Thus;
    GINIT can call field's variable "gameSTART" like so:
    Java Code:
    s.fieldv.gameSTART = true;
    Also, another tip would be to have one main Scene (your JFrame) everything else be a JPanel, and have the class with the JFrame control the Runnable Thread. This allows you to have one central area where everything is done. This is at least what I do. An example would be:

    Java Code:
    public void run()
    {
    	while ( runner == Thread.currentThread() )
    	{
    	//calls a frame variable that is global.
    	frame.repaint();
    	try
    	{
    		//this will detect if a variable in title equals true
    		if(title.changeSTATE == true)  {
    			load_difficulty();
    			cl.show(stage, "store");
    			title.changeSTATE = false;
    		}
    		//Same as above but with the ingame store
    		if(store.changeSTATE == true)  {
    			cl.show(stage, "field");
    			load_field();
    			fieldv.gameSTART = true;
    			store.changeSTATE = false;
    		}
    		//this will detect if a variable in field has been put to true and thus the game starts
    		if(fieldv.gameSTART == true) {
    			//This is the method starts all of the game changes, like motion, calculations, lifebar && text refreshes
    			fieldv.gameUpdate();
    		}
    		//Detects if the user pressed the keys that makes the variable "quit" == true
    		if(fieldv.quit == true) {
    			//This is all of the clean up stuff I do
    			cl.show(stage, "title");
    			fieldv.gameSTART = false;
    			short[] flush_units = {0,0,0,0,0,0,0,0};
    			System.arraycopy(flush_units, 0, store.amount, 0, flush_units.length);
    			store.resetText();
    			fieldv.GRESET();
    			fieldv.wl.changeSTATE = false;
    		}
    		//This is also similar to the others.
    		if(fieldv.wl.changeSTATE == true) {
    			cl.show(stage, "title");
    			fieldv.gameSTART = false;
    			fieldv.GRESET();
    			fieldv.wl.changeSTATE = false;
    		}
    		//10 frames per-second
    		Thread.sleep(100);
    	}
    	catch (InterruptedException event) { System.out.println("Sorry! You can't interrupt this thread B*******! "); }
    	}
    }
    notice that most of the statements start with fieldv, cl, title, store or something else that is not a normal Java Class. The reason is because, they are classes that I have created.

    I hope this is the answer you were looking for. If not, I guess you might have learned something about game design.
    My API:
    Java Code:
    cat > a.out || cat > main.class

  14. #14
    Bgreen7887 is offline Senior Member
    Join Date
    Oct 2010
    Location
    Newark,nj
    Posts
    111
    Rep Power
    0

    Default Re: Call to main() twice ??

    Kammce ! thank you btw, i will have to absorb this in the a.m and respond to let you no how it goes. Im to sleepy right now ... (great sense of humor), one need that after long days of coding.

Similar Threads

  1. how can main call other methods?
    By rahuld.exe in forum New To Java
    Replies: 1
    Last Post: 04-06-2012, 01:19 PM
  2. Unable to call classe constructor from main
    By serdimay in forum New To Java
    Replies: 13
    Last Post: 08-30-2011, 10:38 AM
  3. How to Call servlet through Java client (from main)
    By akbjavauser in forum Java Servlet
    Replies: 3
    Last Post: 01-20-2010, 06:15 PM
  4. Rewrite as a function so it can call from main.
    By thangli in forum New To Java
    Replies: 2
    Last Post: 11-30-2008, 06:26 AM
  5. Replies: 1
    Last Post: 08-07-2007, 06:16 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •