How do I make a "Character Select" system?
I'm making a game for school that is a vertical scrolling shooter (like theRaiden series), based off of the animeGalaxy Angel. For anyone who has seen GA would know there's 5 main characters, all of which I have put in my game. My program is an application (so swing answers only please), and made up of 4 classes: Title Page, Character Select, Main Game, and Credits. I intend to make my program load different Player sprites depending on what character is chosen. Can someone tell me how I can make my Main Game class read which character has been chosen from my Character Select class?
A very quick and easy way of doing this with Swing is using the JRadioButton class. The following suggestion is similar to a technique used in "How to use Radio Buttons".
http://java.sun.com/docs/books/tutorial/uiswing/components/button.html#radiobutton
Inside CharSel class:
First, declare a class String variable called "userIcon" or something at the top of your program. This will be the path of the icon for your user.
private static String userIcon=null;
When you're setting up the GUI for your CharSel screen, use an array of JRadioButtons for the character buttons. In the for loop where you initialize each button, group them all, and set up the basics (ie: stylize the button to make it feel more like a game), add something like this:
buttons[i].addActionListener(this); //assuming you've implemented ActionListener
buttons[i].setActionCommand("images/charIcon"+i+".gif");
The i variable is just an int; the current index of your radio button array in your for loop. An action command is simply a String passed to the ActionEvent of your ActionListener.
You would then add something like the following so you can retrieve the icon's path from other classes:
public static void setUserIconPath(String s) { this.userIcon = userIcon; }
public static String getUserIconPath() { return userIcon; }
//called when a radio button is pressed
public void actionPerformed(ActionEvent e) {
//retrieve the action command
setUserIconPath(e.getActionCommand());
}
When you are writing your actual game classes, you'll create the user image using the static methods:
ImageIcon portrait = new ImageIcon(CharSel.getUserIconPath());
If you wish to avoid the static methods (which may cause problems depending on how you use them), you can set the constructor of your MainGame class to accept the icon's path (or just the ImageIcon itself).
Alternately, you could simply call a method passing the path/imageicon after you initialize your MainGame class.
Other techniques may include constant ints and a switch statement (which checks something like CharSel.selectedIcon() == CharSel.BOB). Of course, a more typesafe way of doing that would be to use enums. If you did use enums, you could even include methods for your enum constants (ie: CharSel.Chars.BOB.getImageIcon() may return Bob's ImageIcon).
Good luck!