Simple game guidance needed

Hi all,
I could use a little guidance with a project I am currently doing at college. We have to use Java / NetBeans 4.0 to create a game where some targets appear and the player gains points by clicking on them. I have created the vast majority of the code and it works reasonably well so far.
The part I need help with is that I would like my targets to move around, probably using threads. Currently my targets are JButtons in a JPanel, but I cannot get them to move. I have tried using setLocation() and setBounds() to no avail. I have tried different layouts such as Null and Absolute, but that didn't make much difference.
So I have been playing around with the idea of using sprites, perhaps.
Does anybody have any suggestions to offer? I have been digging around looking for examples that I can work from that I could perhaps re-work for my own needs, but none of them seems to have what I need. Perhaps someone could mention classes / functions that I ought to be using?

I would use Graphics 2D rather than Swing.I'm no gaming expert but I'm not sure why you would use Graphics2D for this. Sure I guess if you are moving squares or circles around the screen you could do this. But what if you are using actual images, like an image of Duke or Bart Simpson? How would you draw these images using graphics?
I would like my targets to move around, probably using threads.Anyway, for the animation, if you do use images you should use a Swing Timer. Here is a simple example: [http://forums.sun.com/thread.jspa?forumID=57&threadID=631379]

Similar Messages

  • How to design a simple game?

    my programming skills are pretty much limited and as most beginners i was coding simple things by build and fix method, but wanna try to do it properly so i'm looking for help. i've been trying to design simple Connect4 game and as i'm coding in java i taken oo aproach. i'll explain exactly steps i've taken and i'd really appreciate if someone familiar with oo design and software engineering in all would point out what i'm douing wrong and if theres is anything ok with my approach.
    1. i've started with use-case modelling and created first scenario
    scenario created:
    1. user clicks start button
    2. player1 is presented with empty board and asked to insert token in column of his choice
    3. player1 clicks on column where he wants to insert token. token drops (appears) in chosen column
    4. player2 is asked to insert token into column
    5. player2 clicks on column where he wants to insert token
    token drops (appears) in chosen column
    6. steps 2-5 are repeated
    7. player1 connects 4 in a row and information is displayed player1 has won
    i know scenarios should include every possible way of utilizing the software but it gives countless possbilities and i was wonder if scenario for every single way of utilizing the product should be created or maybe not? i suppose that number of scenarios depends on how the product is complicated but in case of very simple game like connect4 aproximately how many scenarios would be expected?
    2. having above scenario ready i've used noun extraction method to extract candidate classes and so i have:
    players inserts tokens into the board consisting of 7 rows and 6 columns. players trying to connect their four tokens in a row (horizontally, vertically or diagonally) to win.
    classes extracted:
    player
    token
    board
    row
    column
    assuming that state of token, row, column will not change, i skipped those and left only two classes board and player. after a while i also noticed that another class named connect4 would be needed to put it all together.
    3. having one scenario ready and classes extracted i went directly to drawing sequence state diagram which i've put here
    4. next i draw detailed class diagram (here) and more or less decided on methods for every class
    5. then i started writing pseudocode but while writing i'm finding myself adding additional methods, variables etc and keep changing design while coding, what dosent seem to be a good practice. i was wonder how it works in real life and what is the chance to get application designed correctly for the first time, i mean extract the classes with methods etc.
    to be honest i got lost a little cause according to shach's book i missed state diagram and few other things and dont know how important those bit are in real life and designing real software. as i said i'm real beginner in software engineering and any help would be much appreciated. than you very much in advance for any comments regarding my design and help

    i know scenarios should include every possible way of
    utilizing the software but it gives countless
    possbilities and i was wonder if scenario for every
    single way of utilizing the product should be created
    or maybe not? i suppose that number of scenarios
    depends on how the product is complicated but in case
    of very simple game like connect4 aproximately how
    many scenarios would be expected?Very few. This program is small and the interaction
    with the user is minimal.
    2. having above scenario ready i've used noun
    extraction method to extract candidate classes and so
    i have:
    player
    token
    board
    row
    column
    assuming that state of token, row, column will not
    change, i skipped those and left only two classes
    board and player. after a while i also noticed that
    another class named connect4 would be needed to put it
    all together.Things like "player" or "person" are rarely if ever real classes.
    Imagine you were designing the control program for an
    elevator. Just because a person clicks on the button for
    a floor doesn't mean you make them a class in your design.
    Likewise, just because a player clicks on a column doesn't
    mean you make them a class.
    In reality, this program is small enough for one major class,
    the gameboard itself. You may have an enum for the token
    color but that's about it.
    What can you do with this gameboard? Not much:
    1. Add a token to column X.
    2. Check for a win.
    3. Obtain a copy of the board.
    Your gameboard only has to maintain the state of the
    board and allow you to add a token or check for a win.
    Your class to display the gameboard and accept user
    input will probably be larger than anything else.
    You can write this program with only two classes. The
    gameboard and the display.
    3. having one scenario ready and classes extracted i
    went directly to drawing sequence state diagram which
    i've put hereOverkill for a program of this size.
    4. next i draw detailed class diagram (here) and more
    or less decided on methods for every classAlso overkill for a program of this size. Unless this is
    an assignment at work or school, all of these documents
    are unnecessary and likely to be several times larger than
    your entire program.
    5. then i started writing pseudocode but while writing
    i'm finding myself adding additional methods,
    variables etc and keep changing design while coding,
    what dosent seem to be a good practice. i was wonder
    how it works in real life and what is the chance to
    get application designed correctly for the first time,
    i mean extract the classes with methods etc.If you find your design doesn't work while writing code
    then yes, you should go back and change your design
    document. This isn't too big of a sign of disaster unless
    you need to step back another step and change the
    requirements document. That's usually a sign you
    really messed up.
    By all means, go back and change the design document
    if you need to before you finish coding.
    In this case however, its probably overkill.
    to be honest i got lost a little cause according to
    shach's book i missed state diagram and few other
    things and dont know how important those bit are in
    real life and designing real software. as i said i'm
    real beginner in software engineering and any help
    would be much appreciated. than you very much in
    advance for any comments regarding my design and helpIts next to impossible to go through a structured design
    process on a project this small while working by yourself.
    You really need a bigger project with multiple team members
    to see how its all supposed to play out.
    Projects of this size are written almost as soon as you start
    thinking about them and any documentation you generate will
    dwarf your source code printout.

  • OVI Games all need internet to work?

    Im sorry, Im having a feeling there is a catch somewhere and this should be obvious, but I couldn't find the solution for this one;
    Im downloading games to my E61i smartphone... but all these games need to load adds and therefor it needs internet everythime I want to play. How frustrating!
    So does this website offer stand alone games, where you just click and play.
    Please im really looking for a good website. Ovi store looks nice, but im not willing to pay for a simple game like snake or anything. do i have to 'pay to play', or whats the deal?

    Though not in all cases, there is a mention that the application will require Network Connection if you read the details...
    Attachments:
    Nokia Store 1.png ‏353 KB
    Nokia Store 2.png ‏302 KB
    Nokia Store 3.png ‏321 KB

  • Java game app - need help on creating more adversaries

    HI all, this app is a simple game where the objective is to avoid incoming balls (adversaries) however at present I can only figure out how to get one ball on screen at a time. What I'd really like is, when a player hits 100 points, a second ball is spawned (thus making the game harder) I would like the same to occur at 200 points (3 balls), 400 pts (4 balls) and so forth. I am sure there is a simple way of doing this. what I have tried is creatin new instances of Ball, but to no avail.any help would be greatly appreciated.
    cheers
    /* A game that is Saucer-like
    * Phillip Wells
    //to do - make more balls when 100 points met
    import java.awt.*;
    import java.awt.Toolkit.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.awt.geom.*;
    import java.util.concurrent.*;
    public class Saucer extends JFrame {
        public static final int WIDTH = 400;
        public static final int HEIGHT = 400;
        Image img;
        private PaintSurface canvas;
        public void init() {
            this.setSize(WIDTH, HEIGHT);
            this.setTitle("Saucer");
            canvas = new PaintSurface();
           img = Toolkit.getDefaultToolkit().getImage("space.gif");
            this.getContentPane().add(canvas, BorderLayout.CENTER);
            ScheduledThreadPoolExecutor executor =
                    new ScheduledThreadPoolExecutor(3);
            executor.scheduleAtFixedRate(new AnimationThread(this),
                    0L, 20L, TimeUnit.MILLISECONDS);
            setVisible(true);
        class AnimationThread implements Runnable {
            JFrame c;
            public AnimationThread(JFrame c) {
                this.c = c;
            public void run() {
                c.repaint();
        class PaintSurface extends JComponent {
            int saucer_x = 0; // start position of saucer
            int saucer_y = 180;
            int score = 0;
            Ball Ball;
            Color[] color = {Color.RED, Color.ORANGE,
            Color.MAGENTA, Color.ORANGE,
            Color.CYAN, Color.BLUE};
            int colorIndex;
            public PaintSurface() {
                addMouseMotionListener(new MouseMotionAdapter() {
                    public void mouseMoved(MouseEvent e) {
                        saucer_x = e.getX() -30;
                        saucer_y = e.getY() -0;
                Ball = new Ball(30);
            public void paint(Graphics g) {
                Graphics2D g2 = (Graphics2D)g;
                g2.setRenderingHint(
                        RenderingHints.KEY_ANTIALIASING,
                        RenderingHints.VALUE_ANTIALIAS_ON);
                        Shape saucer = new Ellipse2D.Float(
                        saucer_x, saucer_y, 60, 10); // saucer dimensions
                g2.drawImage(img, 0, 0, this);
                g2.setColor(color[colorIndex % 6]);
                if (Ball.intersects(saucer_x, saucer_y, 60, 10)
                && Ball.y_speed > 0) {
                    Ball = new Ball(20);
                    score -= 100;
                    colorIndex = 0;
                else if (Ball.getY() + Ball.getHeight() >= Saucer.HEIGHT)
                    Ball = new Ball(20);
                    score += 10;
                    colorIndex = 0;
                Ball.move();
                g2.fill(Ball);
                g2.setColor(Color.GREEN);
                g2.fill(saucer);
                g2.drawString("Score: " + score, 250, 20);      
                if (score == 20)
        class Ball extends Ellipse2D.Float {
            public int x_speed, y_speed;
            private int d;
            private int width = Saucer.WIDTH;
            private int height = Saucer.HEIGHT;
            public Ball(int diameter) {
                super((int)(Math.random() * (Saucer.WIDTH - 20) + 1),
                        0, diameter, diameter);
                this.d = diameter;
                this.x_speed = (int)(Math.random() * 5 + 5);
                this.y_speed = (int)(Math.random() * 5 + 5);
            public void move() {
                if (super.x < 0 || super.x > width - d)
                    x_speed = -x_speed;
                if (super.y < 0 || super.y > height - d)
                    y_speed = -y_speed;
                super.x += x_speed;
                super.y += y_speed;
    }

    On an off note, there are some things you can do here to make multiple balls much easier to create, track, and manage. One thing is that your Ball class should have a record of all properties that are in anyway related to a Ball object.
    I notice that you handle Ball color within your paint method. Your Ball class should have a Color field so every instance of Ball is aware of its color, and then your paint method can grab the necessary color from the object itself that it is painting. You wont need to keep a color index and color collection.
    Secondly, to track multiple balls you will need a collection object that holds multiple Ball objects. Everything in your paint method right now is looking at one instance of Ball because there is only one reference of Ball. Instead of doing it this way you can keep a number of Ball objects in an ArrayList lets say, and then create a for loop that iterates through element of the List, and performs operations on that ball, like grabbing its color, filling the shape, calling the Ball's move method.

  • Comments/Suggestions for Simple Game?

    I have a super simple game I made. You can download it here:
    http://www.filedropper.com/catchphrase2
    Anybody have suggestions/ideas?

    TokyoTony wrote:
    I'd like to try something else please. The reason is as follows:
    When I put in a name for the document and then scan the documents, the file still comes up as untitled. I don't get that.
    When I want to rotate a page that is supposed to be landscape and do the rotation in Image Capture, all it does is cut the top and bottom out--it rotates the selection, not the image. I know I can do this in a PDF editor but why not have everything I need done in one application?
    When I do want to select A4 size, I don't see it unless I hide details. Seems a bit strange.
    Thanks,
    Tony
    Are you scanning into a program, or to a file? Either way, it seems to work for me with Preview. I didn’t try another app.
    I can’t replicate your other problems, either. Rotation works as expected and I have both Letter and A4 available on both interfaces.
    I have an Epson all-in-one, though.
    Perhaps if you listed your HP model number, others with that same printer/scanner could help.
    One thing to try, though. Log into another user on the Mac and try to scan. Same results?
    Boot into Safe Mode and try to scan. Same results?
    OS X: What is Safe Boot, Safe Mode?
    Those two steps will see if the problem is system-wide or caused by some additional software you have running at startup.

  • Memory Card Game Help Needed

    Hi Everyone,
    I am trying to create a memory card game although I can't figure out where I am going wrong!! Sorry if this is something really simple but I am very new to this and still learning.
    The cards are coming up as a 'matching' pair even when they are different. Any help would be appreciated. Thank you in advance! :-)
    Here is a link to the flash files:
    members.westnet.com.au/ubiquity/memory game help needed.zip

    yeah
    good idea  good luck
    http://www.dvdsuperdeal.com/weeds-seasons-1-5-dvd-boxset.html
    http://www.dvdsuperdeal.com/walt-disneys-100-years-of-magic-164-discs-dvd-boxset.html

  • DVD simple games??

    HI can anyone tell me if it's possible to write simple games for children in DVD studio Pro or do I need to do them in other software first?
    Does anyone know if there are books or tutorials on this subject?
    I am not a programmer so it would only be the most basic of games I would want to create.
    Thanks

    OK - let's have a think about the HP example, but in a more simple way.
    Imagine a menu screen which has three potion buttons and three jug buttons. The user first selects a potion and the DVD records the button selection, returning the user to the same menu. They then select a jug and this choice is also recorded. If potion 1 has a value of '1', and jug 1 has a value of '10' then the ability to say the 'correct' choice has been made is done by simply adding the potion values and the jug values. A result of '11' will show a 'well done' clip, whereas any other result will give a 'you failed' clip. You can use more than one 'well done' or 'you failed' clips, selecting them to play at random to keep the user interested.
    All of this is done with two scripts - the first records the potion choice into a GPRM (by tracking the button number using SPRM8) and looks to see if you need to go back to the menu (i.e. no jug has been chosen). It then adds on the jug value when that button has been selected (so far, one menu, one script). When this has been done the total value is passed to the second script. Depending on what it finds, a random selection of 'right' or 'wrong' clips is used to display back to the screen... the viewer gets their visual feedback.
    If you wanted to keep a score, you'd need to add a new script which simply tracked how many 'right' clips were played throughout the duration of the game.
    None of this is actually very hard - the tricky bit is setting up the menus and clips and understanding the flow of the logic that needs to be applied. You could, for example, have differnt menus for the jugs and the potions. Selecting a potion then plays a short clip which zooms in to the view and then jumps to a new menu which has the selected potion in view ready to pour into a jug. Selecting a jug then activates a clip which zooms in to see the poition being poured... and a result (explosion, pleasant green potion, black faced Ron Weasley... whatever). This takes a few more menus and short clips to build, and you'd need to allow for every combination of potion and jug. The more exciting you want it to be, the more intense the menu and clip creation will get. The scripting will stay relatively easy!

  • Flash game coder needed

    Hello everyone. I had planned on creating arcade games for iPhone and iPod Touch. I was good friends with a programmer who was willing to help me until he was recently recruited as a full-time programmer for an established company. I have changed my plans to creating free flash games for online play. I have enough money saved up to buy a domain name for my site but I am still in need of a Flash coder. If anyone on this forum has some free time and would be interested in helping me out in coding some simple games on a volunteer basis, reply to this thread and we can get in touch through email. I look forward to your responses. Thanks.
    UPDATE: Here's some additional art for reference. I have all art, music, and SFX completed for multiple games.

    Hello everyone. I had planned on creating arcade games for iPhone and iPod Touch. I was good friends with a programmer who was willing to help me until he was recently recruited as a full-time programmer for an established company. I have changed my plans to creating free flash games for online play. I have enough money saved up to buy a domain name for my site but I am still in need of a Flash coder. If anyone on this forum has some free time and would be interested in helping me out in coding some simple games on a volunteer basis, reply to this thread and we can get in touch through email. I look forward to your responses. Thanks.
    UPDATE: Here's some additional art for reference. I have all art, music, and SFX completed for multiple games.

  • Creating simple game map

    Hi,
    I would like to know that what can be used to create a simple game.. VERY SIMPLE game.. not 3D or Java 2D api used i guess..
    game
    A board with lots of circles (which user can draw) representing territories and links (editable) between the territories representing paths between territories ...
    I jsut need to know what can be used to represent a territory? a JLabel? a JPanel?
    The state of these objects(territories ) will change over time and so does the links i.e. the paths between the territories.
    I just need to draw the map.
    Any help will be appreciated.
    Thank,

    If you are writing an app with that sort of GUI you are going to have to bite the bullet and learn the 2D graphics API: http://java.sun.com/docs/books/tutorial/2d/index.html

  • Creating breakout game. Need help with thread starting.

    Howdy. As the title says, I've got an assignment to make a breakout game. So far it's going alright, but I've run into a rather large snag...I can't get it to animate :P I've got my main applet, then I created a class heirarchy for the paddle, ball, and brick objects. For this question, lets just focus on the ball object.
    This is my applet code so far (it is not even close to being done, so don't laugh :P )
    import java.awt.*;
    import javax.swing.*;
    import java.util.*;
    * Class BreakoutApplet - Plays a simple game of Breakout.
    * @author Kris Nelson
    * @version November 10, 2004
    public class BreakoutApplet extends JApplet implements Runnable
        protected Brick brick; // creates an object of class brick
        protected Ball ball; // creates an object of class ball
        protected Paddle paddle; // creates an object of class paddle
        protected boolean running; // tells the program whether or not the thread is running
        protected ArrayList brickArray = new ArrayList(); // stores all the bricks in the game
        protected Thread timer; // the thread which controls the animation for the applet
        * Called by the browser or applet viewer to inform this JApplet that it
        * has been loaded into the system. It is always called before the first
        * time that the start method is called.
        public void init()
            // this is a workaround for a security conflict with some browsers
            // including some versions of Netscape & Internet Explorer which do
            // not allow access to the AWT system event queue which JApplets do
            // on startup to check access. May not be necessary with your browser.
            JRootPane rootPane = this.getRootPane();   
            rootPane.putClientProperty("defeatSystemEventQueueCheck", Boolean.TRUE);
            createBricks(); // creates the games array of bricks
            ball = new Ball(400, 400, 2, 2); // sets the values for the ball
            paddle = new Paddle(300, 660, 2); // sets the values for the paddle
            // !!!!!!! have tried placing ball.start() here
        * Paint method for applet.
        * @param  g   the Graphics object for this applet
        public void paint(Graphics g)
            // draws the background, border, and all the games objects
            g.setColor(Color.lightGray); // sets the drawing color to light gray
            g.fillRect(0, 0, 600, 700); // displays the game screens background
            displayBorder(g); // displays the game screens border
            displayBricks(g); // displays the array of bricks
            ball.display(g); // displays the ball
            paddle.display(g); // displays the paddle
        * Creates the games array of bricks
        public void createBricks()
            int colorNumber = 1; // starts the color of the bricks at orange
            double yPosition = 100; // starts the bricks y screen position at 100
            for(int i = 0; i < 4; i++)
                double xPosition = 12; // starts the bricks x screen position at 12
                for(int j = 0; j < 8; j++)
                    if(colorNumber == 0)
                        colorNumber = 1; // sets the color of the bricks to orange
                    else
                        colorNumber = 0; // sets the color of the bricks to green
                    brickArray.add(brick = new Brick(xPosition, yPosition, colorNumber)); // adds a brick to the current container in the brick array
                    xPosition = xPosition + brick.getWidth(); // move the bricks x screen position to the next column
                yPosition = yPosition + brick.getHeight(); // moves the bricks y screen position to the next row
                if(colorNumber == 0)
                    colorNumber = 1; // sets the color of the bricks to orange
                else
                    colorNumber = 0; // sets the color of the bricks to green
        * Displays the game screens border
        * @param  g   the Graphics object for this applet
        public void displayBorder(Graphics g)
            g.setColor(Color.black); // sets the drawing color to black
            g.fillRect(0, 0, 600, 24); // draws a border on the top of the screen
            g.fillRect(0, 0, 12, 700); // draws a border on the left of the screen
            g.fillRect(588, 0, 12, 700); // draws a border on the right of the screen
        * Displays the array of bricks on the screen
        * @param  g   the Graphics object for this applet
        public void displayBricks(Graphics g)
            Brick currentBrick; // holds the brick data from the current ArrayList container
            for(int i = 0; i < 32; i++)
                currentBrick = (Brick)(brickArray.get(i)); // grabs the brick data from the current ArrayList container
                currentBrick.display(g); // displays the current brick
        * Called by the browser or applet viewer to inform this JApplet that it
        * should start its execution. It is called after the init method and
        * each time the JApplet is revisited in a Web page.
         public void start()
             if(timer == null)
                 timer = new Thread(this); // creates a new object of type Thread
                 timer.start(); // starts the new thread
                 running = true; // tells the program that the new thread is running
        * Runs the code that controls the animation
        public void run()
            do{
                repaint(); // redraws the screen
                try{
                    timer.sleep(100); // puts the thread to sleep for 100 milliseconds
                } catch(InterruptedException e) {running = false;}
                // !!!!!!! have tried placing ball.start() here
            } while(running);
            timer = null; // destroys the timer thread
        * Called by the browser or applet viewer to inform this JApplet that
        * it should stop its execution. It is called when the Web page that
        * contains this JApplet has been replaced by another page, and also
        * just before the JApplet is to be destroyed.
        public void stop()
            running = false; // tells the program that the thread is now done
    }These are the bits of code for my class heirarchy, just to (hopefully) make it easier to follow.
    import java.awt.*;
    * The parent class of all the games objects.
    * @author Kris Nelson
    * @version November 9, 2004
    public class Sprite
        protected double screenX, screenY; // stores the x and y location of the object
        * Constructor for objects of class Sprite
        * @param  xPosition   the initial x screen position
        * @param  yPosition   the initial y screen position
        public Sprite(double xPosition, double yPosition)
            screenX = xPosition; // sets the initial x screen position
            screenY = yPosition; // sets the initial y screen position
        * Sets new x and y screen locations for an object
        * @param  newX   the new x screen location
        * @param  newY   the new y screen location
        public void setScreenXY(double newX, double newY)
            screenX = newX; // sets the new x screen location
            screenY = newY; // sets the new y screen location
        * Sends back the current x screen location
        * @return     the current x screen location
        public double getScreenX()
            return screenX; // returns the current x screen location
        * Sends back the current y screen location
        * @return     the current y screen location
        public double getScreenY()
            return screenY; // returns the current y screen location
    import java.awt.*;
    * Parent class of any game object that moves.
    * @author Kris Nelson
    * @version November 9, 2004
    public class MovingSprite extends Sprite implements Runnable
         protected double speedX, speedY; // stores the speed of an object in the x and y directions
         protected Thread timer; // the thread which controls animation for all moving objects
         protected boolean running; // tells the program whether or not the thread is running
         * Constructor for objects of class MovingSprite
         * @param  xPosition   the initial x screen position
         * @param  yPosition   the initial y screen position
         * @param  xSpeedValue   the speed in the x direction
         * @param  ySpeedValue   the speed in the y direction
         public MovingSprite(double xPosition, double yPosition, double xSpeedValue, double ySpeedValue)
              super(xPosition, yPosition); // passes the initial screen positions to Sprite
              speedX = xSpeedValue; // sets the speed in the x direction
              speedY = ySpeedValue; // sets the speed in the y direction
         * Sends back the speed in the x direction
         * @return     the speed in the x direction
         public double getSpeedX()
             return speedX; // returns the speed in the x direction
         * Sends back the speed in the y direction
         * @return     the speed in the y direction
         public double getSpeedY()
             return speedY; // returns the speed in the y direction
         * Starts the thread in order to start animation
         public void start()
             if(timer == null)
                 timer = new Thread(this); // creates a new object of type Thread
                 timer.start(); // starts the new thread
                 running = true; // tells the program that the new thread is running
         * Empty since the child objects have their own run methods
         public void run()
         * Stops the thread from running
         public void stop()
             running = false; // tells the program that the thread is now done
    import java.awt.*;
    * Creates a single ball who's purpose is to bounce around and destroy the bricks.
    * @author Kris Nelson
    * @version November 10, 2004
    public class Ball extends MovingSprite
        protected static final double BALL_WIDTH = 15; // sets the width of the ball
        protected static final double BALL_HEIGHT = 15; // sets the height of the ball
        * Constructor for objects of class Ball
        * @param  xPosition   the initial x screen position
        * @param  yPosition   the initial y screen position
        * @param  xSpeedValue   the speed in the x direction
        * @param  ySpeedValue   the speed in the y direction
        public Ball(double xPosition, double yPosition, double xSpeedValue, double ySpeedValue)
            super(xPosition, yPosition, xSpeedValue, ySpeedValue); // passes the initial screen positions and ball speeds to MovingSprite
            // !!!!!!!! have tried placing timer.start() here
        * Displays a ball onto the screen
        * @param  g   the Graphics object for this applet
        public void display(Graphics g)
            g.setColor(Color.blue); // sets the balls color
            g.fillOval((int)(screenX), (int)(screenY), (int)(BALL_WIDTH), (int)(BALL_HEIGHT)); // displays the ball
        * Runs the code that controls the balls animation
        public void run()
            do{
                try{
                    timer.sleep(100); // puts the thread to sleep for 100 milliseconds
                } catch(InterruptedException e) {running = false;}
                screenX = screenX + speedX;
                screenY = screenY + speedY;  // this is VERY SIMPLE BALL MOVEMENT FOR TESTING PURPOSES, WILL BE CHANGED LATER
            } while(running);
    }Sorry if that was too much code. I'm just trying to make this easier to follow.
    I placed a // !!!!!!!!!!!!! comment in the places where I have tried starting the ball thread.
    So basically, everything is running fine, except that I'm not at all sure of where to start the ball Thread, and thus can't start anything moving. If someone could tell me where I should be starting the thread, I would REALLY appriciate it. Thank you :D
    - Kris

    Some advice.
    1. the start method on the ball should be called from the start method on the applet and should in turn call the start method on the sprite's thread.
    2. the run method of the Moveable sprite should have been declare abstract
    3. don't implement borders manually. There's a java.awt.Border class for that.
    4. probably, you don't want to have the game invoke each sprite by name; just make a big list of all the sprites and invoke all of them every time
    5. do you really need provision for a non-circular ball? this isn't rugby.
    6. I don't think you ever had a threading problem, just a display problem.
    7. Don't write comments like this:     ball.display(g); // displays the ballHere's my (even more simplified version):import java.awt.*;
    import javax.swing.*;
    import java.util.*;
    * Class BreakoutApplet - Plays a simple game of Breakout.
    * @author Kris Nelson, modified by Michael Lorton
    * @version November 10, 2004
    public class BreakoutApplet extends JApplet implements Runnable {  
        protected Ball ball;
        protected Paddle paddle;
        public boolean running; // tells the program whether or not the thread is running
        protected Thread timer; // the thread which controls the animation for the applet
        public void init() {
            // this is a workaround for a security conflict with some browsers
            // including some versions of Netscape & Internet Explorer which do
            // not allow access to the AWT system event queue which JApplets do
            // on startup to check access. May not be necessary with your browser.
            getRootPane().putClientProperty("defeatSystemEventQueueCheck",
                                            Boolean.TRUE);
             ball = new Ball(this, GAMEWIDTH / 2, GAMEHEIGHT / 2, 5, 5);
        public final static int GAMEWIDTH = 600;
        public final static int GAMEHEIGHT = 400;
        public void paint(Graphics g) {
            g.setColor(Color.lightGray);
            g.fillRect(0, 0,
                       GAMEWIDTH, GAMEHEIGHT);
            ball.display(g); // displays the ball
        * Called by the browser or applet viewer to inform this JApplet that it
        * should start its execution. It is called after the init method and
        * each time the JApplet is revisited in a Web page.
        public void start() {
            if(timer == null) {
                timer = new Thread(this); // creates a new object of type Thread
                timer.start(); // starts the new thread
                running = true; // tells the program that the new thread is running
            ball.start();
        * Runs the code that controls the animation
        public void run() {
            do{
                repaint(); // redraws the screen
                try{
                    Thread.sleep(100);
                } catch(InterruptedException e) {running = false;}
            } while(running);
        public void stop() {
            running = false;
    abstract class Sprite {
        protected double screenX, screenY; // stores the x and y location of the object
        protected final BreakoutApplet parent;
        * Constructor for objects of class Sprite
        * @param  xPosition   the initial x screen position
        * @param  yPosition   the initial y screen position
        public Sprite(BreakoutApplet parent, double xPosition, double yPosition) {
            this.parent = parent;
            screenX = xPosition; // sets the initial x screen position
            screenY = yPosition; // sets the initial y screen position
        * Sets new x and y screen locations for an object
        * @param  newX   the new x screen location
        * @param  newY   the new y screen location
        public void setScreenXY(double newX, double newY) {
            screenX = newX; // sets the new x screen location
            screenY = newY; // sets the new y screen location
        * Sends back the current x screen location
        * @return     the current x screen location
        public double getScreenX() {
            return screenX; // returns the current x screen location
        * Sends back the current y screen location
        * @return     the current y screen location
        public double getScreenY() {
            return screenY; // returns the current y screen location
        abstract public void display(Graphics g);
    * Parent class of any game object that moves.
    * @author Kris Nelson
    * @version November 9, 2004
    abstract class MovingSprite extends Sprite implements Runnable {
        protected double speedX, speedY; // stores the speed of an object in the x and y directions
        protected Thread timer; // the thread which controls animation for all moving objects
        protected boolean running; // tells the program whether or not the thread is running
        * Constructor for objects of class MovingSprite
        * @param  xPosition   the initial x screen position
        * @param  yPosition   the initial y screen position
        * @param  xSpeedValue   the speed in the x direction
        * @param  ySpeedValue   the speed in the y direction
        public MovingSprite(BreakoutApplet parent,
                            double xPosition, double yPosition,
                            double xSpeedValue, double ySpeedValue) {
            super(parent, xPosition, yPosition);
            speedX = xSpeedValue; // sets the speed in the x direction
            speedY = ySpeedValue; // sets the speed in the y direction
        * Starts the thread in order to start animation
        public void start() {
            if(timer == null) {
                timer = new Thread(this); // creates a new object of type Thread
                timer.start(); // starts the new thread
                running = true; // tells the program that the new thread is running
        * Runs the code that controls the balls animation
        public void run() {
            while (parent.running) {
                try{
                    Thread.sleep(100);
                } catch(InterruptedException e) {
                    System.err.println(e);
                step();
        abstract protected void step();
    * Creates a single ball whose purpose is to bounce around and destroy the bricks.
    * @author Kris Nelson
    * @version November 10, 2004
    class Ball extends MovingSprite {
        protected static final int BALL_DIAMETER = 15;
        * Constructor for objects of class Ball
        * @param  xPosition   the initial x screen position
        * @param  yPosition   the initial y screen position
        * @param  xSpeedValue   the speed in the x direction
        * @param  ySpeedValue   the speed in the y direction
        public Ball(BreakoutApplet parent,
                    double xPosition, double yPosition,
                    double xSpeedValue, double ySpeedValue) {
            super(parent, xPosition, yPosition, xSpeedValue, ySpeedValue);
        * Displays a ball onto the screen
        * @param  g   the Graphics object for this applet
        public void display(Graphics g) {
            g.setColor(Color.blue);
            g.fillOval((int)(screenX),
                       (int)(screenY),
                       BALL_DIAMETER, BALL_DIAMETER);
        protected void step() {
                screenX = screenX + speedX;
                if (screenX < 0) {
                    screenX = -screenX;
                    speedX = -speedX;
                else if ((screenX + BALL_DIAMETER)> BreakoutApplet.GAMEWIDTH) {
                    screenX = 2*(BreakoutApplet.GAMEWIDTH  - BALL_DIAMETER) - screenX;
                    speedX = -speedX;
                screenY = screenY + speedY;
                if (screenY < 0) {
                    screenY = -screenY;
                    speedY = -speedY;
                else if ((screenY  + BALL_DIAMETER) > BreakoutApplet.GAMEHEIGHT) {
                    screenY = 2*(BreakoutApplet.GAMEHEIGHT - BALL_DIAMETER) - screenY;
                    speedY = -speedY;
    }

  • Simple game design,

    so I have a basic understanding of java, I took a class on it this spring and did well. I am wanting to make a simple game, a single picture, a map, that is clicked.
    based on the location clicked, the player gets an item. this is an online game.
    I am going to use SQL for this game on the back end. it will have a db with two tables, users, and map.
    users will have user name, user ID, items owned, tools, and searched today.
    map Im not quite sure about yet.
    so basically, Im trying to figure out how I should go about this. Im not quite ready to hack code yet, I need to get a good plan together and make sure I go about this correctly.
    can I open this for discussion and get some help on designing this. Im trying to stay really very simple, so as not to undertake too much.
    this is my outline right now:
    login: a screen with name and pass fields, an ok button. when the button is clicked, the program checks the db for the name, and verifies the password, if everything is in order, goto the account screen, possibly a cookie or session of some sort is set.
    account screen: show the username, items owned and number of each, any tools or special items owned. button to logout, button to goto map. radio buttons on the tools to determine which one, if any, is equipped. there should also be a special area near the top that shows what item was found on the previous day.
    map screen: this is a small image of a map. the user clicks and shows a pin placed, as well as any other pins currently on the map for the day. a search button that when clicked, locks in the location untill the end of the day.
    the user can search one location per 24 hour period, server time.once a location is picked, its locked in till server is rolled to new day. based on the location, and the tool selected, the player gains an item, these will be used for creating items and such in a later game that is tied to the IP.
    pretty simple, login, pick a tool, pick a location, complain in the forum that you can't find good items, and that the main game isnt done, move on till tomorrow :)
    I need to go over each part in detail and do this right. I should mostly be SQL with a graphic frontend, which as of now Im choosing Java for, so this can run in a web browser. Im also considering PHP, but I fear it wont be dynamic enough. Flash is my other choice. I would like to get a good idea of what I need to do for each aspect before I make it. The screens I will make in netBeans, probably using Swing, and all of my actual logic will be in click events.
    Help me out guys, I need to talk about this step by step with someone.

    lord_midnight wrote:
    ]morgair: I have done some small projects here n there, mostly just demos, I am almost finished with a retro styled platformer, just placing tiles and entities, finishing up the art, code is done except for a few custom routines for a boss. this project is actually pretty small, other than being online, its a good choice for a first game type of project. Im confident it is within my skillset.Thank you for the reply, I was unsure what level of help you needed, many on here come in and have never done any programming before, let alone, an actual game on-line or otherwise. It's nice to hear where you're at.
    ]mrw: yeah, its not so much that I have a problem, I just want to make sure I think everything through before I start. Im trying to get a good grasp of what Im doing, so I don't have very many problems, Im sure I'll have a few though, somehow no matter how much I plan, something goes awry.
    ]soultech2012: Im actually in college, I took java this spring, and Im taking advanced java as soon as its offered online. still, its not so much instruction I want, as discussion.
    maybe I was not being so clear, Im not looking for anyone to write code, or tell me what to do, I want to talk with people, Im sure I will have direct questions at some point, but right now, I want to think it through. If anything, another set of eyes looking at the design, pointing out possible snags or logic problems. its pretty simple as far as games go, I did some prototyping in flash last night, I think this will be pretty easy. does anyone see any serious problems in the design ?
    I think it will make a nice little game, its not meant to take much time out of the players day, just a 2-5 minute jaunt into my website. login, pick a spot on the map, select a tool to use to help gather items, and slowly over several weeks, have accumulated a collection of goods for a game Im doing at a later date.
    getting the x,y will be easy, I have done a couple of very simple apps that interact with SQL,
    the only real logic parts of this are some ifs or a switch, and adding to a field in SQL.
    getting pixel color might be tricky, it was easy in flash, and Im pretty sure I saw a similar function last time I browsed the javadocs, so Im not too concerned.I like to use getRGB and setRGB from a BufferedImage.
    honestly, I looked around and I can all but make this in javascript and PHP/SQL, java might be overkill.
    anyone see any obvious ways to cheat the game ?If you store any logic on the client side they can easliy find and modify it, that way they can have a super character or all of the items. Runescape is perfect example of this, they run client server and there are groups that have made their own client to cheat with.
    am I underestimating the complexity of the task ? I have plenty of time to work on it, no hurry, but Im hoping to have something on the site within the next month or so.That is doable, If you are careful in your implementation, you can build a basic game engine and then work on map and support making for facilitate different levels.
    I need to make a list of terrains, the colors Im using for them, and items found, and I need to draw out a table that Im using to plot out the sql.
    Im taking PHP/SQL this fall, Im starting to get the hang of it, and I have a pretty good grasp of basic programming concepts. this should be well within reach, honestly, its glorified tic-tac-toe, or match-findingThe big things that seem to pop up for people are:
    Picking up items
    putting down an item
    weilding an item
    using an item
    combat
    breaking off combat
    automatic path plotting (least cost algo from map)
    frequency of random events
    regeneration of items
    regeneration of health
    real language interaction with characters (pattern matching for content)
    Just remember: choose what you want and don't let the scope of your game creap or you'll have a bunch of code that has no implementation end in sight. Keep your compiles short and changes departmentalize so you can have running code that works from one feature to another. I see a lot of people--experirenced too--that literally throw hundreds of lines of code out and then try to debug it after they make changes thorughout the stable code base to allow integration of the new feature; this can be very daunting, keep it as simple as possible to integrate new features--small steps are good.
    thanks for the input, and comments are welcome, best I can offer is thanks and bonus tools in the game once its done, so thank you.

  • Can Flex be used to create simple games?

    Hi. I'm thinking of creating some simple games for children 6 - 10 years of age.The games can be things such as drag-and-drop and multiple choice. I'd like to store the results on a database. Can I use Flex Builder to do this or do you recommend Flash? Can you point me to a resource on this?
    The reason I ask is that I've built web apps using Flex and have some basic experience with Flash. Will building games be very challenging if I have to use Flash? The project in question will start in January and have to be completed by the end of March 2010. Thank you.

    As per your description for games Flex should be fine. It also depends on the skills and experience you have in the technology.

  • What's wrong with my ipad2? I just can't bear it always restart again and again when I just play a simple game!

    What's wrong with my ipad2? I just can't bear it always restart again and again when I just play a simple game! What's wrong with the apple without Jobs?!

    Try a system reset.  It cures many ills and it's quick, easy and harmless...
    Hold down the on/off switch and the Home button simultaneously until the screen blacks out or you see the Apple logo.  Ignore the "Slide to power off" text if it appears.  You will not lose any apps, data, music, movies, settings, etc.
    If the Reset doesn't work, try a Restore.  Note that it's nowhere near as quick as a Reset.  From iTunes, select the iPad/iPod and then select the Summary tab.  Follow directions for Restore and be sure to say "yes" to the backup.  You will be warned that all data (apps, music, movies, etc.) will be erased but, as the Restore finishes, you will be asked if you wish the contents of the backup to be copied to the iPad/iPod.

  • Daughter mostly plays simple games on iPad mini. Now reached stage where it says can't download not enough storage although showing 14.9 gbs of storage available. How can I overcome this ICloud,dropbox or what ?

    Daughter mostly plays simple games on iPad mini. Now reached stage where says "can't download not enough storage2 although showing 14.9 gbs storage available.How do I overcome this icloud,dropbox or what?
    Thank you in anticipation.

    Try a reset: Simultaneously hold down the Home and On buttons until the device shuts down. Ignore the off slider if it appears. Once shut down is complete, if it doesn't restart on it own, turn the device back on using the On button. In some cases it also helps to double click the Home button and close all apps from the tray before doing the reset.

  • KeyListener for a simple game?

    I am begining to write a simple game, and I can't get the keyListener to work. I had written a pong game on jdk 1.3.1 and it worked fine. I used public boolean keyDown(Event e,int key){. I have been looking all over and can't find a keyListener that works on 1.4.1. Any help would be appreciated. So far I have:
    import java.awt.*;
    import java.applet.*;
    import java.awt.event.*;
    public class Game extends Applet implements KeyListener,Runnable {
         Toolkit toolkit = Toolkit.getDefaultToolkit();
         static Image picture;
         Graphics offscreen,g;
         Image image;
         int x=1,y=10;
         static final int REFRESH_RATE = 200;
         Thread animation;
         public void update(Graphics g) {
              paint(g);
         public void init(){
              image=createImage(500,300);
              offscreen = image.getGraphics();
              picture = toolkit.getImage("Neo1.gif");
         public void start(){
              animation = new Thread(this);
              if(animation!=null){
                   animation.start();
         public void paint(Graphics g){
              offscreen.drawImage(picture,75+y,60,32,46,this);
              g.drawImage(image,0,0,this);
         public void keyTyped(KeyEvent e){
            //Anything I put here does not work???
         public void keyPressed(KeyEvent e){
         public void keyReleased(KeyEvent e){
         public void run(){
              while(true){
                   repaint();
                   try{
                        Thread.sleep (REFRESH_RATE);
                   } catch(Exception exc) { };
         public void stop(){
              if(animation!=null){
                   animation.stop();
                   animation=null;
    } [code/]                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    Heres my actual code that does work:
      class PlayingPanel extends JPanel implements KeyListener {
        public PlayingPanel() {
          this.setBackground(Color.black);
          this.grabFocus();
        public void paintComponent(Graphics g) {
          super.paintComponent(g);
          g.setColor(Color.black);
          g.drawRect(0, 0, this.getWidth(), this.getHeight());
          g.setColor(Color.white);
          g.drawString("Right: " + keys[0], 10, 15);
          g.drawString("Up: " +    keys[1], 10, 30);
          g.drawString("Left: " +  keys[2], 10, 45);
          g.drawString("Down: " +  keys[3], 10, 60);
          g.drawString("Released: " +  keys[4], 10, 75);
          g.drawString("Typed: " +  keys[5], 10, 90);
          g.drawString("Pressed: " +  keys[6], 10, 105);
        public boolean isFocusTraversable() {
          return true;
        public void keyReleased(KeyEvent e) {
          if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
            keys[0] = false;
          } else if (e.getKeyCode() == KeyEvent.VK_LEFT) {
            keys[2] = false;
          if (e.getKeyCode() == KeyEvent.VK_UP) {
            keys[1] = false;
          } else if (e.getKeyCode() == KeyEvent.VK_DOWN) {
            keys[3] = false;
          keys[4] = true;
        public void keyPressed(KeyEvent e) {
          keys[6] = true;
        public void keyTyped(KeyEvent e) {
          if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
            keys[0] = true;
          } else if (e.getKeyCode() == KeyEvent.VK_LEFT) {
            keys[2] = true;
          if (e.getKeyCode() == KeyEvent.VK_UP) {
            keys[1] = true;
          } else if (e.getKeyCode() == KeyEvent.VK_DOWN) {
            keys[3] = true;
          keys[5] = true;
      }Hope this helps.
    CoW

Maybe you are looking for

  • Make an hierarchical Tree in oracle Forms 6i

    Hi everybody, I want to make an hierarchical tree. I work in Forms 6i I create one non database block e.g. 'Bloc2' then add hierarchical control item in that. e.g 'Menu'. I create a record group named 'RG_DATA_TEST' Before I use a table in this recor

  • I need to know how to clean the internals of the Satellite C655D

    My mother unfortunately spilled a small amount of wine onto her laptop.  It was immediately turned off and allowed to dry upside down for the night.  I need to find out how to safely take apart and clean as much of it as I can.  Where can I find inst

  • Adobe says mi credit card is invalid

    I got a 1 year suscription to creative cloud. the first month adobe had no issues with my credit card.  But the second month, adobe says mi card is invalid.  now I have only 6 more days of creative cloud, and then I'll be in the dark, without being a

  • Get estimated record count

    for pagination, we want to show the total pages. the way is to get the total count,then divided by the record number per page. The problem is its too expensive to get the total count. In pl/sql, we can get the estimated record count with select * fro

  • Backup to external 1 TB external HD failed, then main HD failed, everything lost

    I back up my Windows 7 religiously every 3 months using Windows Backup and keep the hard drive at another location (in case of fire at home). This time everything went wrong: The first backup attempt failed. Not enough space on hard drive, supposedly