Java-Gaming.org    
Featured games (79)
games approved by the League of Dukes
Games in Showcase (477)
Games in Android Showcase (107)
games submitted by our members
Games in WIP (535)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
   Home   Help   Search   Login   Register   
  Show Posts
Pages: [1] 2 3
1  Game Development / Game Play & Game Design / Re: Resource Loading. on: 2010-05-25 06:32:39
I gave the above code a whirl and in this specific case getCodeSource() is returning null. I read the documentation and various questions on google and that appears to just happen sometimes "Depending on classloader configurations".

I have a few other things to try before I give up and make a textfile that contains a list of all the files to load. Although that seems a little awkward and un-necessary.

Thanks for the code above though. I would be curious to see how frequently it works on other systems, and will investigate that too.
2  Game Development / Game Play & Game Design / Re: Resource Loading. on: 2010-05-24 20:38:39
OK I found the source of the problem, not sure how to resolve it though. jarPath is a URL to the jar file on the server, not the local cached jar.

User.dir also just returns User.home so that is of no use.

Does anyone know how I might go about locating that? Or perhaps a better way to dynamically load resources from a JWS downloaded jar file.
3  Game Development / Game Play & Game Design / Resource Loading. on: 2010-05-24 07:55:10
Could not find an appropriate subforum to put this in so I decided on here:


I am trying to list all the files in a directory, regardless of the location of that directory (in a jar file, or just a plain system directory). The use of this is dynamically  loading resources and not having to change a huge hard-coded list in between versions. So far my code works splendidly when launching from a jar or just launching form the filesystem. All files are found and loaded correctly.

However, when I distribute the jar file via java web start, it has  trouble opening the jar file. I think perhaps my understanding of how java web start works is incorrect, and I will post this question in a more appropriate location if I can't figure out out here.

Here is the offending code:
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
private String[] getResourceListing(Class classs, String path) throws URISyntaxException, IOException {
        URL dirURL = classs.getResource(path);
        if (dirURL != null && dirURL.getProtocol().equals("file")) {
            /*Plain file, simple to list contents*/
            return new File(dirURL.toURI()).list();
        }
        String me = null;
        if (dirURL == null) {
            /*JAR file.*/
            me = classs.getName().replace(".", "/") + ".class";
            dirURL = classs.getClassLoader().getResource(me);

            if (dirURL.getProtocol().equals("jar")) {
                String internalJarPath = me.substring(0, me.lastIndexOf("/")) + "/" + path;
                String jarPath = dirURL.getPath().substring(5, dirURL.getPath().indexOf("!"));
                JarFile jar = new JarFile(URLDecoder.decode(jarPath, "UTF-8"));
                Enumeration<JarEntry> entries = jar.entries();
                Set<String> results = new HashSet<String>();
                JarEntry je;
                while (entries.hasMoreElements()) {
                    je = entries.nextElement();
                    String name =je.getName();
                    if (name.startsWith(internalJarPath) && !je.isDirectory()) {
                        results.add(name.substring(name.lastIndexOf("/")+1));
                    }
                }

                return results.toArray(new String[results.size()]);
            }
        }
        throw new UnsupportedOperationException("Cannot list files for URL "+dirURL);
    }


I think the offending line is:
1  
JarFile jar = new JarFile(URLDecoder.decode(jarPath, "UTF-8"));


I am decently sure the jarPath does not accurately point to the jar file launched when launching via a jnlp file. But finding documentation on that kind of thing, has been like pulling teeth.

Any insight into java web start would be greatly appreciated.
4  Game Development / Game Play & Game Design / Re: Java 2D Fighting game on: 2008-03-24 23:14:27
Your probably going to want to create an Animation class too otherwise its going to get very unwieldy.
5  Game Development / Newbie & Debugging Questions / Re: 2 Thread one for drawing and one for logic on: 2007-11-24 22:08:21
Your making it much more difficult than it needs to be.
6  Game Development / Networking & Multiplayer / Message size/speed on: 2007-09-28 00:16:18
Right now I am sending messages from and to the host as fast as possible. I am adding code right now to see how many messages are being sent a second and how large they are (just string length).

The question is should I have them bombarding each other or should there be some sort of max speed?
7  Game Development / Networking & Multiplayer / Re: Lagtastic on: 2007-09-26 04:59:27
Oopsies. No errors though.
8  Game Development / Networking & Multiplayer / Re: Lagtastic on: 2007-09-21 20:27:28
I'm only resistant for now. When I finish this project, I'll probably attempt one with a non-blocking approach. Then after that I'll probably just adopt some 3rd party code.

I have removed all the serialization and am just sending a String now, havn't tested it yet.

Will this be speed it up or do nothing?
1  
2  
DataOutputStream out = new DataOutputStream(myOtherStream);
out.writeUTF(myStringMessage);


and for reading
1  
2  
BufferedReader reader = new BufferedReader(new DataInputSream(myOtherStreams));
String message = reader.readLine();reader


Will those be faster than reading writing a stream or the same?


9  Game Development / Networking & Multiplayer / Re: Lagtastic on: 2007-09-21 04:07:29
I am resistant to a 3rd party "thingy" of any kind. I was in the process of removing all the serialization stuff, sending strings now. Hadn't thought of binary data, i'll look into that thanks.
10  Game Development / Networking & Multiplayer / Re: Lagtastic on: 2007-09-20 07:08:09
Didnt fit in first one.

Client listener - hosts way of communicating with clients
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
61  
62  
63  
64  
65  
66  
67  
68  
69  
70  
71  
72  
73  
74  
75  
76  
77  
78  
79  
80  
81  
82  
83  
84  
85  
86  
87  
88  
89  
90  
91  
92  
93  
94  
95  
96  
97  
98  
99  
100  
101  
102  
103  
104  
105  
106  
107  
108  
109  
110  
111  
112  
113  
114  
115  
116  
117  
118  
119  
120  
121  
122  
123  
124  
125  
126  
127  
128  
129  
130  
131  
132  
133  
134  
135  
136  
137  
138  
139  
140  
141  
142  
143  
144  
145  
146  
147  
148  
149  
150  
151  
152  
153  
154  
155  
156  
157  
158  
159  
160  
161  
162  
163  
164  
165  
166  
167  
168  
169  
170  
171  
172  
173  
174  
175  
176  
import java.io.*;
import java.net.*;
import java.util.*;

public class ClientListener extends Thread {
   private World world;
    private LinkedList<Client> clients;
    private ServerSocket serv;
    private boolean running = true;
    private ResourceManager rm = ResourceManager.INSTANCE;
   
    public ClientListener(World world) {
       this.world = world;
        try {
            serv = new ServerSocket(64652);
        }
        catch (IOException e) {
        }
        clients = new LinkedList<Client>();
        start();
    }
   
    public Client getHost() {
       return clients.get(0);
    }
   
    public void processInput(Tank tank, String message) {
        message = message.substring(5);
        String[] parts = message.split(";");
        tank.setVelocityX(0.0f);
        tank.setVelocityY(0.0f);
       
        if (parts[0].equals("1")) {
            tank.setVelocityY(tank.getVelocityY() - Tank.SPEED);
        }
        else if (parts[1].equals("1")) {
            tank.setVelocityY(tank.getVelocityY() + Tank.SPEED);
        }
        else if (parts[2].equals("1")) {
            tank.setVelocityX(tank.getVelocityX() - Tank.SPEED);
        }
        else if (parts[3].equals("1")) {
            tank.setVelocityX(tank.getVelocityX() + Tank.SPEED);
        }
        if (parts[4].equals("1")) {
            tank.fire();
        }
    }
   
    public synchronized boolean processMessage(Client client, String message) {
       if (message.equals("quit")) {
            return false;
        }
        if (message.startsWith("input")) {
           if (client.getTank() != null) {
              processInput(client.getTank(), message);
           }
        }
        if (message.startsWith("init")) {
             message = message.substring(5);
             Tank tank = generateTank(message);
             client.setTank(tank);
             world.addSprite(tank);
             sendWorldTo(client.getSock());
        }
       
        return true;
    }
   
    public synchronized void sendString(String s) {
        for (Client c : clients) {
            c.getSock().send(s);
        }
    }
   
    public synchronized void sendObject(Object o) {
        try {
            for (int i = 0 ; i < clients.size() ; i++) {
               Client c = clients.get(i);
                c.getSock().send(o);
            }  
        }
        catch (IOException e) {
        }
    }
   
    public void run() {
        try  {
            while (running) {
                SocketAction sock = new SocketAction(serv.accept());
               
                newCommer(sock);
            }
        }
        catch (IOException e) {
           e.printStackTrace();
        }
    }
   
    public Tank generateTank(String name) {
       Tank tank = new Tank(rm.getAnimationForKey("green up"),
             rm.getAnimationForKey("green down"),
                rm.getAnimationForKey("green right"),
                rm.getAnimationForKey("green left"),
                rm.getAnimationForKey("green fire up"),
                rm.getAnimationForKey("green fire down"),
                rm.getAnimationForKey("green fire right"),
                rm.getAnimationForKey("green fire left"),
                Tank.GREEN);
       tank.setName(name);
       tank.setPosition(100, 100);
       tank = (Tank)World.tagSprite(tank);
       return tank;
    }
   
    public synchronized void newCommer(SocketAction sock) {
       clients.add(new Client(sock));
    }

    public synchronized void sendWorldTo(SocketAction socket) {
       synchronized (socket) {
          try {
             for (Sprite s : world.getSprites()) {
                socket.send(new Message("new", "", s));
         
             }
          }
             catch (IOException e) {
             System.err.println(e);
          }  
       }
    }
   
    private class Client extends Thread {
       
        private Tank player;
        private SocketAction sock;
        private boolean running = true;
       
        public Client(SocketAction sock) {
           this(sock, null);
        }
       
        public Client(SocketAction sock, Tank tank) {
            player = tank;
            this.sock = sock;
            start();
        }
       
        public SocketAction getSock() {
            return sock;
        }
       
        public void setTank(Tank tank) {
           player = tank;
        }
       
        public Tank getTank() {
           return player;
        }
       
        public void run() {
            try {
                while (running && sock.isConnected()) {
                    String in = sock.receive();
                    if (in != null) {
                        running = processMessage(this, in);
                    }
                }
            }
            catch (IOException e) {
               e.printStackTrace();
            }
        }
    }
}

11  Game Development / Networking & Multiplayer / Lagtastic on: 2007-09-20 07:07:13
Works peachy on a lan across any distance though it gets ridiculously laggy. I used the blocking approach because I do not come close to understanding the non-blocking approach no matter how much I read about it. In fact I didn't read anything at all on nonblocking, which is probably why my code is laggy, but I was still able to figure it out.

My last post was far too long so Ill ahve to give it in bits and pieces. Here are what I think are the most important two classes.

SocketAction - socket wraper
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
61  
62  
63  
64  
65  
66  
67  
68  
69  
70  
71  
72  
73  
74  
75  
76  
77  
78  
79  
80  
81  
82  
import java.io.*;
import java.net.*;

public class SocketAction extends Thread    {

    private BufferedReader inStream = null;
    protected PrintStream outStream = null;
    private ObjectOutputStream oos = null;
    private ObjectInputStream ois = null;
   
    private Socket socket = null;
   
    public SocketAction(Socket sock) {
       super("SocketAction");
       try {
            inStream = new BufferedReader(new InputStreamReader(sock.getInputStream()));
            outStream = new PrintStream(new
                BufferedOutputStream(sock.getOutputStream(), 1024), true);
           
            oos = new ObjectOutputStream(sock.getOutputStream());
            ois = new ObjectInputStream(sock.getInputStream());
            socket = sock;
        }
        catch (IOException e) {
            System.out.println("Couldn't initialize SocketAction: " + e);
            System.exit(1);
        }
    }
   
    public void send(Object o) throws IOException {
        oos.writeObject(o);
        oos.reset();
    }
   
    public void send(String s) {
        outStream.println(s);
    }

    public String receive() throws IOException {
        return inStream.readLine();
    }
   
    public Object receiveObject() throws IOException, ClassNotFoundException {
        return ois.readObject();
    }
   
   
    public boolean isConnected() {
        return ((inStream != null) && (outStream != null) && (socket != null));
    }
   
    protected void finalize () {
        if (socket != null) {
        try {
            socket.close();
        }
        catch (IOException e) {
            System.out.println("Couldn't close socket: " + e);
            }
        socket = null;
        }
    }
   
    public void closeConnections() {
        try {
            socket.close();
            socket = null;
        }
        catch (IOException e) {
            System.out.println("Couldn't close socket: " + e);
        }
    }
   
    public void reset() {
        try {
            inStream.reset();
        }
        catch (IOException e) {
        }
    }
}
       



Message - sent object
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
import java.io.*;

public class Message implements Serializable {
   private String title;
   private String message;
   private Object data;
   
   public Message(String title, String message) {
      this.title = title;
      this.message = message;
   }
   
   public Message(String title, String message, Object data) {
      this(title, message);
      this.data = data;
   }
   
   public String getTitle() {
      return title;
   }
   
   public String getMessage() {
      return message;
   }
   
   public Object getData() {
      return data;
   }
}


HostListener - clients communication with host
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
61  
62  
63  
64  
65  
import java.io.*;
import java.net.*;

public class HostListener extends Thread {
    private SocketAction host;
    private boolean running = true;
    private String name;
   
    public HostListener(String name) {
        this.name = name;
    }
   
    public boolean connectTo(String ip) {
       try {
            host = new SocketAction(new Socket(ip, 64652));
        }
        catch (UnknownHostException e) {
           e.printStackTrace();
           return false;
        }
        catch (IOException e) {
           e.printStackTrace();
           return false;
        }
        send("init:" + name);
        start();
        return true;
    }
   
    public void run() {
        try {
            while (running) {
                 Object o = host.receiveObject();
                 processObject(o);
            }
        }
        catch (IOException e) {
           System.err.println(e);
        }
        catch (ClassNotFoundException e) {
           System.err.println(e);
        }
    }
   
    public void processMessage(String message) {
       
    }
   
    public synchronized void processObject(Object o) {
       Message message = (Message)o;
       if (message.getTitle().equals("state")) {
          GameManager.INSTANCE.adjustWorld(message.getMessage());
       }
       else if (message.getTitle().equals("new")) {
          GameManager.INSTANCE.getWorld().addSprite((Sprite)message.getData());
       }
       else if (message.getTitle().equals("remove")) {
          GameManager.INSTANCE.getWorld().removeSpriteForID(Integer.parseInt(message.getMessage()));
       }
    }
   
    public void send(String s) {
        host.send(s);
    }
}


Any point in the right direction would be appriciated
12  Game Development / Game Play & Game Design / Re: What do you want in a web game? on: 2007-08-01 07:34:41
If it isn't a deep-sea shrimp shooter i'm not interested.
13  Game Development / Networking & Multiplayer / Re: Sprite list on: 2007-06-30 04:18:48
Heh, I just realized this is all pointless anyway. The goal of this post was to find out how to keep everything up to date without having to send any BufferedImages ever. If I could do that I would get rid of my silly int[].
14  Game Development / Networking & Multiplayer / Re: Sprite list on: 2007-06-30 01:56:10
Then why would you have an extra array for the image data?

BufferedImages do not implement Serializable, so i need to not have any field be a BufferedImage in any class I am intending to send over an ObjectOutputStream. This is the easiest way I could figure out.
15  Game Development / Networking & Multiplayer / Re: Sprite list on: 2007-06-29 20:39:32
I made them serializable, the Animation holds an int[] instead of a bufferedImage which is converted back and fourth in the set/get methods. I have it working, its just that im sending way to much useless data over the socket. There are little jitters occasionally even when both client and host are on localhost.

I was trying to think of how I could sum up the state of the sprite list in a string or some primitive array. Like when a sprite is created maybe I could have a SpriteID field, then I could send info like
"sprite:294 x:2 y:8 animation:up animationProgress:873". Or maybe I could just let the clients keep track of how far along the animation is and just have the host send information about when the animation changes.

My thought behind the sprite ID is that the host/client sprite list may not stay in the same order, so each sprite would have a number associated, which I guess would mean in need a sprite factory class.



Here is my animation class by the way, i thought i posted it in the first one, guess not:
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
61  
62  
63  
64  
65  
66  
67  
68  
69  
70  
71  
72  
73  
74  
75  
76  
77  
78  
79  
80  
81  
82  
83  
84  
85  
86  
87  
88  
89  
90  
91  
92  
93  
94  
95  
96  
97  
98  
99  
100  
101  
102  
103  
104  
105  
106  
107  
108  
109  
110  
111  
112  
113  
114  
115  
116  
117  
118  
119  
120  
121  
122  
123  
124  
125  
126  
127  
128  
129  
130  
131  
132  
133  
134  
135  
136  
137  
138  
139  
140  
141  
142  
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.io.*;

/**
    The Animation class manages a series of images (frames) and
    the amount of time to display each frame.
*/

public class Animation implements Serializable{

    private ArrayList<AnimFrame> frames;
    private int currFrameIndex;
    private long animTime;
    private long totalDuration;


    /**
        Creates a new, empty Animation.
    */

    public Animation() {
        this(new ArrayList<AnimFrame>(), 0);
    }
   
    public Animation(BufferedImage img) {
        this();
        frames.add(new AnimFrame(img, 1));
    }


    private Animation(ArrayList<AnimFrame> frames, long totalDuration) {
        this.frames = frames;
        this.totalDuration = totalDuration;
        start();
    }

   public void setAnimTime(long time) {
      animTime = time;
   }

   public long getAnimTime() {
      return animTime;
   }
   
    public int getDuration() {
        return (int)totalDuration;
    }

    /**
        Creates a duplicate of this animation. The list of frames
        are shared between the two Animations, but each Animation
        can be animated independently.
    */

    public Object clone() {
        return new Animation(frames, totalDuration);
    }


    /**
        Adds an image to the animation with the specified
        duration (time to display the image).
    */

    public synchronized void addFrame(BufferedImage image,
        long duration)
    {
        totalDuration += duration;
        frames.add(new AnimFrame(image, totalDuration));
    }


    /**
        Starts this animation over from the beginning.
    */

    public synchronized void start() {
        animTime = 0;
        currFrameIndex = 0;
    }


    /**
        Updates this animation's current image (frame), if
        neccesary.
    */

    public synchronized void update(long elapsedTime) {
        if (frames.size() > 1) {
            animTime += elapsedTime;

            if (animTime >= totalDuration) {
                animTime = animTime % totalDuration;
                currFrameIndex = 0;
            }

            while (animTime > getFrame(currFrameIndex).endTime) {
                currFrameIndex++;
            }
        }
    }


    /**
        Gets this Animation's current image. Returns null if this
        animation has no images.
    */

    public synchronized BufferedImage getImage() {
        if (frames.size() == 0) {
            return null;
        }
        else {
            return getFrame(currFrameIndex).getImage();
        }
    }


    private AnimFrame getFrame(int i) {
        return (AnimFrame)frames.get(i);
    }

    public void reset(){
       animTime = 0;
       currFrameIndex = 0;
    }

    private class AnimFrame implements Serializable {
       int[] imageData;
       int height, width;
        long endTime;

        public AnimFrame(BufferedImage image, long endTime) {
           width = image.getWidth();
           height = image.getHeight();
           imageData = new int[width * height];
           image.getRGB(0, 0, width, height, imageData, 0, width);
           
            this.endTime = endTime;
        }
       
        public BufferedImage getImage() {
           BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
           image.setRGB(0, 0, width, height, imageData, 0, width);
           return image;
        }
    }
}

16  Game Development / Networking & Multiplayer / Sprite list on: 2007-06-29 09:11:34
Ive been sending a LinkedList to all my clients which seems pretty ineffective since all kinds of useless data is being sent as well.

Sprite:
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
public class Sprite implements Serializable {
    public static final int LEFT = 0, RIGHT = 1, UP = 2, DOWN = 3;
   
    private Rectangle collisionRect;
    protected Animation anim;
    protected float posX; // x position in pixels
   protected float posY; // y position in pixels
   protected float dx; // delta x in pixels per millisecond
   protected float dy; // delta y in pixels per millisecond
   protected boolean visible;
    protected int state;
    protected boolean alive;
   
    lots of methods here that make more than 10000 characters

}



Ive been trying to figure out if I should let each client keep track of the animations themselves, and let the server just handle movement. But there is a seperate animation for each direction and I havnt been able to figure out what I could do. What is the best way to go about this?
17  Game Development / Newbie & Debugging Questions / Re: Visible to current unit on: 2007-06-20 20:17:10
I think your better off just re coloring the sprites, thats what I do. Otherwise you would have to make a color that you go through and replace, which means you couldn't have that color on the sprite. If there is another way to do it I don't know it. I bet there is though.
18  Game Development / Newbie & Debugging Questions / Re: Visible to current unit on: 2007-06-20 19:13:48
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
public void drawBrighterImage(Graphics2D g2d, BufferedImage im, 
                                      int x, int y, float brightness)
  /* Draw the image with changed brightness, by using a RescaleOp.
     Any alpha channel is unaffected. */

  {
    if (im == null) {
      System.out.println("drawBrighterImage: input image is null");
      return;
    }

    if (brightness < 0.0f) {
      System.out.println("Brightness must be >= 0.0f; setting to 0.5f");
      brightness = 0.5f;
    }
    // brightness may be less than 1.0 to make the image dimmer

    RescaleOp brigherOp;
    if (hasAlpha(im)) {
       float[] scaleFactors = {brightness, brightness, brightness, 1.0f};
                // don't change alpha
               // without the 1.0f the RescaleOp fails, which is a bug (?)
      float[] offsets = {0.0f, 0.0f, 0.0f, 0.0f};
       brigherOp = new RescaleOp(scaleFactors, offsets, null);
    }
    else   // not transparent
     brigherOp = new RescaleOp(brightness, 0, null);

    g2d.drawImage(im, brigherOp, x, y);
  }  // end of drawBrighterImage()


  public void drawNegatedImage(Graphics2D g2d, BufferedImage im, int x, int y)
  /* Draw the image with 255-<colour value> applied to its RGB components.
     Any alpha channel is unaffected. */

  {
    if (im == null) {
      System.out.println("drawNegatedImage: input image is null");
      return;
    }

    if (hasAlpha(im))
      g2d.drawImage(im, negOpTrans, x, y);  // use predefined RescaleOp
   else
      g2d.drawImage(im, negOp, x, y);
  }



1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
public void drawFadedImage(Graphics2D g2d, BufferedImage im, 
                                   int x, int y, float alpha)
  /* The degree of fading is specified with the alpha value.
     alpha == 1 means fully visible, 0 mean invisible. */

  {
    if (im == null) {
      System.out.println("drawFadedImage: input image is null");
      return;
    }

    if (alpha < 0.0f) {
      System.out.println("Alpha must be >= 0.0f; setting to 0.0f");
      alpha = 0.0f;
    }
    else if (alpha > 1.0f) {
      System.out.println("Alpha must be <= 1.0f; setting to 1.0f");
      alpha = 1.0f;
    }

    Composite c = g2d.getComposite();  // backup the old composite

    g2d.setComposite( AlphaComposite.getInstance(
                           AlphaComposite.SRC_OVER, alpha));
    g2d.drawImage(im, x, y, null);

    g2d.setComposite(c);
      // restore the old composite so it doesn't mess up future rendering
 }


19  Game Development / Newbie & Debugging Questions / Re: setListData merging array items together on: 2007-06-15 10:10:27
Neat...

Here is all my code, I changed how I did it to every imaginable way including making my own subclass of AbstractListModel, and get the same results every time.

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
61  
62  
63  
64  
65  
66  
67  
68  
69  
70  
71  
72  
73  
74  
75  
76  
77  
78  
79  
80  
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.util.*;

public class Welcome extends JFrame implements ActionListener {

    private String[] rooms;
   
    private static JButton quit = new JButton("Quit");
    private static JButton join = new JButton("Join");
    private static JButton make = new JButton("Make");
   
    private DefaultListModel listModel;
    private static JList list;

    private SocketAction host;
   
    public Welcome(String[] rooms, SocketAction host) {
        super("Connect 4");
        quit.addActionListener(this);
        make.addActionListener(this);
        join.addActionListener(this);
        this.host = host;
        this.rooms = rooms;
       
        listModel = new DefaultListModel();
        listModel.addElement(rooms[0]);
        list = new JList(listModel);
       
        JPanel content = new JPanel(new BorderLayout());
        content.add(new JLabel("Join or make a game."), BorderLayout.NORTH);
        content.add(new JScrollPane(list), BorderLayout.CENTER);
       
        JPanel southPanel = new JPanel();
        southPanel.add(join);
        southPanel.add(make);
        southPanel.add(quit);
       
        content.add(southPanel, BorderLayout.SOUTH);
        add(content);
        setLocation(400, 400);
        setResizable(false);
        pack();
        setVisible(true);
    }
   
    public void setRooms(String[] rooms) {
        listModel.clear();
        list.setVisibleRowCount(rooms.length);
        int i = 0;
        for (String s : rooms) {
            listModel.add(0, s);
            list.setSelectedIndex(i);
            list.ensureIndexIsVisible(i);
            i++;
        }
    }
   
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == quit) {
            host.send("quit");
            System.exit(0);
        }
        else if (e.getSource() == join) {
            String name = (String)list.getSelectedValue();
            if (!name.equals("Loading List") && name != null && !name.equals("null")) {
                host.send("join" + name);
                setVisible(false);
            }
        }
        else if (e.getSource() == make) {
            String name = JOptionPane.showInputDialog("Game Name");
            if (name != null) {
                host.send("make" + name);
                setVisible(false);
            }
        }
    }
}


20  Game Development / Newbie & Debugging Questions / Re: Trade off question on: 2007-06-14 04:15:28
No I don't know, that's the whole point of my question :\

Noone can tell you if your code is fast or not if you don't profile it. Doesn't sound like it matters at all though.
21  Game Development / Newbie & Debugging Questions / setListData merging array items together on: 2007-06-13 09:05:44
Google has been very unhelpful, and believe me this is a last very sad resort. Or don't I don't care.

I create a JList, and when i call setListData(String[]) it merges all the items in my String[] into one and sticks it in one slot of the List.


Here is how I create it. rooms = {"Loading List"}
1  
2  
3  
DefaultListModel listModel = new DefaultListModel();
        list = new JList(listModel);
        list.setListData(rooms);



Here is where I try and use setListData
1  
2  
3  
4  
5  
public void setRooms(String[] rooms) {
        int index = list.getSelectedIndex();
        list.setListData(rooms);
        list.setSelectedIndex(index);
    }



In the specific case I have been trying rooms is {"Frog", "Toad"}

The JList's first item changes from "Loading List" to "FrogToad"


I also tried converting the String[] to a Vector and adding it that way, same result.
22  Game Development / Networking & Multiplayer / Re: TextArea replacement on: 2007-06-13 01:24:32
Hrm? JTextArea doesn't automatically scroll to the bottom. I had to make it do that myself.
23  Game Development / Networking & Multiplayer / Re: Routers on: 2007-06-12 00:39:35
Thank you, got it working. I had to parse whatsmyip.com but it works.
24  Game Development / Networking & Multiplayer / Routers on: 2007-06-11 08:36:21
So I finished my first networking "Game" (connect 4)

Works great on LANs but I have no idea (and google is not being helpful) how to set it up to work over the internets. So links/advice please?
25  Game Development / Networking & Multiplayer / Re: sr on: 2007-06-05 19:52:44
I don't know why I extended Thread.

The Bind exception thing I thought was fine because on my earlier chat client thingy I would get it for every connection but they still connected and functioned properly.
OK nevermind it turns out im a liar, I just went back and tried it again and there was no exeption about bind. Just in this app. Well good times for halucinations.

HostListener
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
import java.nio.*;
import java.io.*;
import java.net.*;

public class HostListener extends Thread {
   
    SocketAction host;
   
    public HostListener(SocketAction sock) {
        host = sock;
        start();
    }
   
   
    public void run() {
        while (true) {
            try {
                String message = host.receive();
                if (message != null) {
                    GameManager.INSTANCE.setLastMessage(message);
                }
            }
            catch (IOException e) {
                System.err.println(e);
            }
        }
    }
}


Noting out that line of code removed the sr from being sent, and also changed q~beep to beep so yay. Although that means my object serializer/sender is horribly broken.
Still looking for why that bind exception is being thrown.


Thanks for the responces thus far, very helpful. Removed the extend Thread part  Roll Eyes
26  Game Development / Networking & Multiplayer / Re: sr on: 2007-06-05 05:39:40
Code

My handy dandy Socket subclass
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
61  
62  
63  
64  
65  
66  
67  
68  
69  
70  
71  
72  
73  
74  
75  
76  
import java.nio.*;
import java.io.*;
import java.net.*;

public class SocketAction extends Thread    {

    private DataInputStream inStream = null;
    protected PrintStream outStream = null;
    protected ObjectOutput out = null;
    private Socket socket = null;
    private String initMessage = null;
   
    public SocketAction(Socket sock, String initMessage) {
        this(sock);
        initMessage = null;
    }
   
    public SocketAction(Socket sock) {
        super("SocketAction");
        try {
            inStream = new DataInputStream(new
                BufferedInputStream(sock.getInputStream(), 64652));
            outStream = new PrintStream(new
                BufferedOutputStream(sock.getOutputStream(), 64652), true);
            socket = sock;
            out = new ObjectOutputStream(outStream);
        }
        catch (IOException e) {
            System.out.println("Couldn't initialize SocketAction: " + e);
            System.exit(1);
        }
    }
   
    public String getInitMessage() {
        return initMessage;
    }
   
    public void send(String s) {
        outStream.println(s);
    }
   
    public void send(Object o) throws IOException {
        out.writeObject(o);
    }

    public String receive() throws IOException {
        return inStream.readLine();
    }
   
   
    public boolean isConnected() {
        return ((inStream != null) && (outStream != null) && (socket != null));
    }
   
    protected void finalize () {
        if (socket != null) {
        try {
            socket.close();
        }
        catch (IOException e) {
            System.out.println("Couldn't close socket: " + e);
            }
        socket = null;
        }
    }
   
    public void closeConnections() {
        try {
            socket.close();
            socket = null;
        }
        catch (IOException e) {
            System.out.println("Couldn't close socket: " + e);
        }
    }
}


GameManager
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
61  
62  
63  
64  
65  
66  
67  
68  
69  
70  
71  
72  
73  
74  
75  
76  
77  
78  
79  
80  
81  
82  
83  
84  
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.sound.sampled.AudioFormat;
import javax.sound.midi.*;

import java.io.*;
import javax.sound.sampled.*;
import java.text.DecimalFormat;
import java.net.*;
import java.nio.*;

public class GameManager extends GameCanvas {
    public static GameManager INSTANCE = new GameManager();
    public static final int PORT = 64652; //spells ninja on a phone ^^
   public static final String ADDR = "localhost";
   
    private SocketAction host;
    private int fps;
    private SpriteManager sm = SpriteManager.INSTANCE;
    private ClientListener cl = ClientListener.INSTANCE;
    private HostListener hl;
    private String lastMessage;
   
    public void init(String type) {
        try {
            if (type.equals("host")) {
                ClientListener cl = new ClientListener();
                host = new SocketAction(new Socket(ADDR, PORT));
            }
            else if (type.equals("client")) {
                host = new SocketAction(new Socket(ADDR, PORT));
                sm = null;
                cl = null;
            }
            hl = new HostListener(host);
        }
        catch (IOException e) {
            System.err.println(e);
        }
    }
   
    public synchronized void setLastMessage(String message) {
        lastMessage = message;
    }

    public void Update(long elapsedTime) {
        cl.sendString("beep");
        if (elapsedTime > 0) {
            fps = (int) (1000L / elapsedTime);
        }
        try {
            if (cl != null) {
                cl.sendObject(sm);
            }
        }
        catch (IOException e) {
            System.err.println(e);
        }
       
        synchronized (lastMessage) {
            System.out.println("Last Message: " + lastMessage);
        }
    }

    public void draw(Graphics g) {
        Graphics2D g2 = (Graphics2D) g;
        g2.setRenderingHint(
            RenderingHints.KEY_TEXT_ANTIALIASING,
            RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

        // Render game here
       g.setColor(Color.GREEN);
        g.fillRect(0, 0, getWidth(), getHeight());

        // Display data
       g.setColor(Color.WHITE);
        g.setFont(new Font("Dialog", Font.PLAIN, 18));
        g.drawString("FPS: " + fps, getWidth() - 90, getHeight() - 10);
    }
}


Thingy that listens for clients trying to connect and adds them to a list
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
import java.nio.*;
import java.net.*;
import java.util.*;
import java.io.*;
import java.awt.*;

public class ClientAdder extends Thread {
   
    private ServerSocket serv;
    private ClientListener cl;
   
    public ClientAdder(ServerSocket serv, ClientListener c) {
        this.serv = serv;
        cl = c;
    }
   
    public void run() {
        while (true) {
            try {
                SocketAction sock = new SocketAction(serv.accept());
                cl.addPlayer(new Player(sock, new Sprite(Color.red)));
            }
            catch (IOException e) {
                System.err.println(e);
            }
        }
    }
}


Thingy that listens to the clients for input information
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
61  
62  
63  
64  
65  
66  
67  
import java.nio.*;
import java.net.*;
import java.util.*;
import java.io.*;
import java.awt.*;


public class ClientListener extends Thread {

    public static ClientListener INSTANCE = new ClientListener();

    private ClientAdder ca;
    private ServerSocket serv;
    private LinkedList<Player> players;
   
    public ClientListener() {
        try {
            serv = new ServerSocket(GameManager.PORT);
            ca = new ClientAdder(serv, this);
            ca.start();
        }
        catch (IOException e) {
            System.err.println(e);
        }
       
        players = new LinkedList<Player>();
        start();
    }
   
    public void run() {
        while (true) {
            try {
                synchronized (players) {
                    for (Player p : players) {
                        String action = p.getSock().receive();
                        if (action != null) {
                            p.addAction(action);
                        }
                    }
                }
                Thread.sleep(10);
            }
            catch (IOException e) {
                System.err.println(e);
            }
            catch (InterruptedException e) {
                System.err.println(e);
            }
        }
    }
   
    public synchronized void addPlayer(Player p) {
        players.add(p);
    }
   
    public synchronized void sendString(String s) {
        for (Player p : players) {
            p.getSock().send(s);
        }
    }
   
    public synchronized void sendObject(Object o) throws IOException {
        for (Player p : players) {
            p.getSock().send(o);
        }
    }
}


My "player" class which i really have no idea where I am going with
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
import java.util.*;

public class Player {
    private LinkedList<String> actionsLine;
    private Sprite sprite;
    private SocketAction sock;
   
    public Player(SocketAction sock, Sprite sprite) {
        actionsLine = new LinkedList<String>();
        this.sock = sock;
        this.sprite = sprite;
    }
   
    public SocketAction getSock() {
        return sock;
    }
   
    public Sprite getSprite() {
        return sprite;
    }
   
    public void addAction(String s) {
        actionsLine.add(s);
    }
   
    public String proccessFirstAction() {
        String action = actionsLine.get(0);
        actionsLine.remove(0);
        return action;
    }
}



The Idea I came up with was to have the client and host applicatins differ by simply having a socket point either to another machine or to itself. If certain variables aren't null then it gets input from clients and then sends it out, treating itself as a client which I know is stupid but I couldn't think of any other way.

Anyway if I run it with the arg "host" it makes a clientListener and clientAdder which hold the ServerSocket. In the init I attatch a socket to itself because I am a genius. In the update method I send the message "beep" to all clients. The clients, the only one is the host itself, is recieving "q~beep". Also "sr" is being sent sometime between the init method and the first update.

Feel free to point me to a good reference (which I havn't managed to find) for good ways to organize this.
27  Game Development / Newbie & Debugging Questions / Re: Making a card game on: 2007-06-05 04:39:01
I thought it was FlowLayout by default... not that it matters. At all, just looking for an excuse to post something.
28  Game Development / Networking & Multiplayer / Re: sr on: 2007-06-05 02:18:22
Nice avatar  Grin. I figured the bind exception was pointless since I was getting it all the time on my multiple chat clients and it was working fine.

I supose I could just try other ports and maybe it will go away? I guess i'll do that. Starting with 646527 ninjas! (out of range Sad)

I searched my project and an s does not appear in my code followed by an r except once in the center of a variable. So yea..

Edit: So no matter the port my message gets sent, then sr goes through.
Ill post my code later when I have time.

Edit: another unrelated problem is that I couldn't find a book I liked that detailed game programming specifically, so I figured out how to connect sockets and am trying to reinvent the wheel.  So far its square.
29  Game Development / Networking & Multiplayer / sr on: 2007-06-04 22:42:07
Does this have any special significance? I have made a serverSocket and a socket, and I send the message "beep" as a test form the server to the client which are both on localhost. For some reason after beep it gets the message "sr" though I never send that message.

I get a bindalready in use exception and I am using port 64652. Does that mean the socket is already taken or whats going on now. Also I have no idea what code to show if any.

As a side note I chose 64652 because it spells ninja on a phone.
30  Games Center / Archived Projects / Re: Pac Man!!! on: 2007-06-01 08:00:17
The link doesn't work.
Pages: [1] 2 3
 

Add your game by posting it in the WIP section,
or publish it in Showcase.

The first screenshot will be displayed as a thumbnail.

E.R. Fleming (20 views)
2014-07-29 03:07:13

E.R. Fleming (7 views)
2014-07-29 03:06:25

pw (39 views)
2014-07-24 01:59:36

Riven (39 views)
2014-07-23 21:16:32

Riven (26 views)
2014-07-23 21:07:15

Riven (28 views)
2014-07-23 20:56:16

ctomni231 (59 views)
2014-07-18 06:55:21

Zero Volt (50 views)
2014-07-17 23:47:54

danieldean (42 views)
2014-07-17 23:41:23

MustardPeter (45 views)
2014-07-16 23:30:00
HotSpot Options
by dleskov
2014-07-08 03:59:08

Java and Game Development Tutorials
by SwordsMiner
2014-06-14 00:58:24

Java and Game Development Tutorials
by SwordsMiner
2014-06-14 00:47:22

How do I start Java Game Development?
by ra4king
2014-05-17 11:13:37

HotSpot Options
by Roquen
2014-05-15 09:59:54

HotSpot Options
by Roquen
2014-05-06 15:03:10

Escape Analysis
by Roquen
2014-04-29 22:16:43

Experimental Toys
by Roquen
2014-04-28 13:24:22
java-gaming.org is not responsible for the content posted by its members, including references to external websites, and other references that may or may not have a relation with our primarily gaming and game production oriented community. inquiries and complaints can be sent via email to the info‑account of the company managing the website of java‑gaming.org
Powered by MySQL Powered by PHP Powered by SMF 1.1.18 | SMF © 2013, Simple Machines | Managed by Enhanced Four Valid XHTML 1.0! Valid CSS!