I have created a boolean called multiplay.
private boolean multiplay;
within my public Game() I have:
// make a player
player = new Player(this);
if(multiplay == true) {
player2 = new Player(this);
}
Within the actually class file I have created a method:
public void startMutliPlayer() {
multiplay = true;
}
What I am trying to do is when startMultiPlayer is called it will set the boolean multiplay as true, therefore, two players will be added to the frame not one. if 'startMultiPlayer' is not called it will only add one player.
At the moment it only adds one player not two when I called startMultiPlayer.
UPDATE:
Was able to sort this issue out using the following code:
// Make Players (Single & MultiPlayer)
if (multiplay == false) {
player = new Player(this);
player.setPosition(startPosition);
player.move(new Vec2(-210, 0));
multiplay = true;
} else if(multiplay == true) {
player = new Player(this);
player.setPosition(startPosition);
player.move(new Vec2(-210, 0));player2 = new Player(this);
player2.setPosition(startPosition);
player2.move(new Vec2(-150, 0));
multiplay = false;
}
public static void startMutliPlayer() {
multiplay = false;
}
Thanks
Which object of the Game class are you calling startMultiPlay on? Since it will always be called after the Game constructor is called, it will not work - because when the Game ctor is called, multiplay will be false.
On way to fix this is
private boolean multiplay;
needs to be changed to
private static boolean multiplay;
Also make startMultiPlayer as static and call it before you create a Game object.
Another way is not to create Player's in Game's ctor.
Have to methods startMultiPlayer and startSinglePlayer - create one or two Player objects in these methods respectively.
Create a method in your Game class, i.e.
public void setMultiplay(boolean multiplay) {
this.multiplay = multiplay; // scope
if (multiplay) {
player2 = new Player(this);
}
}
I'm guessing you are calling the method startMultiPlayer() on an object of the class Game.
However, the constructor is the first thing to be executed when you create an object in Java.
Game game = new Game();
game.startMultiPlayer();
will execute the following lines in this order:
// make a player
player = new Player(this);
if(multiplay == true) {
player2 = new Player(this);
}
multiplay = true;
which means multiplay is set to true after you check if it's true. Therefore, you will still be in singleplayer mode.
Try checking if multiplay is true after calling (or not calling) the startMultiPlayer() method.
Also note that you can simply write if(multiplay) instead of if(multiplay==true) since if-statements in Java can only take booleans. But that's personal preference, this is probably optimized automatically anyway.
Related
I am new to Java and I have come across a "bug" in my code that I am having trouble understanding/fixing. To give you some background knowledge, I set up an Enum that states all the game states (below)
public enum GameState {
IN_LOBBY(true), IN_GAME(false), POST_GAME(false), RESETTING(false);
private boolean canJoin;
private static GameState currentState;
GameState(boolean canJoin) {
this.canJoin = canJoin;
}
public boolean canJoin() {
return canJoin();
}
public static void setState(GameState state) {
GameState currentState = state;
}
public static boolean isState(GameState state) {
return GameState.currentState == state;
}
public static GameState getState() {
return currentState;
}
}
In my main.java class I specify in the onEnable method to set the GameState to IN_LOBBY.
Basically what I am trying to do is in a BlockBreakEvent Listener I want to say is
if (GameState.isState(GameState.IN_LOBBY)) {
Location bLoc = block.getLocation();
ChatUtilties.errorPlayer("You may not break blocks at this time.", player);
bLoc.getBlock().setType(Material.type);
}
In other words I am trying to detect if the GameState is IN_LOBBY and if so make it so that players can not break blocks. But currently two problems have arisen.
For some reason when the GameState is IN_LOBBY the plugin won't even take notice. It just ignores that if statement. It won't even send the message, as if the gamestate was not IN_LOBBY.
I'm not sure how to dynamically change the material based on what block the player broke.
Your setter is wrong:
public static void setState(GameState state) {
GameState currentState = state;
}
You are creating a new local variable currentState here, instead of using the existing field. This happens because you wrote the variable type in front of it, creating a new initialization statement.
Instead use:
public static void setState(GameState state) {
currentState = state;
}
(Since currentState is a static field GameState.currentState = state; would also work in this case)
Edit:
Another problem is with your canJoin method.
public boolean canJoin() {
return canJoin();
}
this method calls itself recursivly without any end condition. So you will get a StackOverflowException if you ever try to call it.
Instead you probably meant to return the canJoin field:
public boolean canJoin() {
return canJoin;
}
Gym.java
public class Gym extends ActiveObject {
public void run() {
...
}
}
GymController.java
public class GymController extends WindowController implements KeyListener{
private Gym gym;
public void begin() {
Gym gym = new gym(canvas, new Location(dx, dy), delay, this);
}
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_SPACE) {
gym.run();
}
}
}
There is an object and its moving code in Gym.java file... and I wanted to call that to GymController.java file's keyPressed method... so that the object moves when the user presses the space bar.
How do I even link these two files in the first place...?
But the compiler is giving me an error saying that it cannot find symbol.
How can I call a method from another .java file into current file's keyPressed method properly, so that it compiles...?
As pointed out by comments, your problem lies in:
public void begin() {
Gym gym = new gym(canvas, new Location(dx, dy), delay, this);
}
And it should be:
public void begin() {
gym = new Gym(canvas, new Location(dx, dy), delay, this);
}
First of all, new takes the class name, you are building an actual object from a "pattern". Then, doing Gym gym =... creates a local variable within the scope of your begin() method. It will be discarded on return from begin.
If you just use gym or this.gym, it will assign the new instance to the member variable.
But be careful, your initial gym instance will create a new gymcontroller instance which will, in turn create a new gym instance. So the gym.run() will not use the same instance of gym than the one who created it. If that was your intention, you need to pass the this reference from gym to gymcontroller.
so I'm a 6th grader who's trying to program a TicTacToe program using netbeans 8.1 and java.
This is my code so far (for the sake of simplicity i've only included the code of one button):
public class TicTacToe extends JFrame{
static Random computerGenerate = new Random();
static int rounds = 0;
static JPanel panel = new JPanel();
static JButton s1 = new JButton();
public static void main(String[] args) {
Gui();
}
public static void Gui() {
JFrame Gui = new JFrame("TicTacToe");
Gui.setVisible(true);
Gui.setResizable(false);
Gui.setSize(320, 340);
Gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel.setLayout(null);
Gui.add(panel);
s1.setBounds(0, 0, 100, 100);
s1.setFont(new Font("Times New Roman", Font.PLAIN, 50));
s1.addActionListener(new Response());
panel.add(s1);
}
private static class Response extends TicTacToe implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == tictactoe.TicTacToe.s1) {
s1.setText("X");
s1.setEnabled(false);
rounds += 1;
}
}
}
public static void Moves() {
if (rounds == 1) {
int computerStartPos = 1 + computerGenerate.nextInt(8);
switch (computerStartPos) {
case 1:
if (button"s1" is disabled)) {
computer will generate a new starting position for the AI
} else {
button s1 will be disabled and it will show a "O" to show the computer has selected the square
}
break;
}
}
}
}
The section which I have a problem with is the very last method, method Moves().
What I'm trying to do is, after the player has selected their starting square, the computer will generate a number, 1-9 which will determine its own starting position.
The problem I have is if the player has already selected that button before the computer, I need the computer to re-generate a new number as its starting point.
My idea to solve this is "if s1.setEnabled() is equal to false, then the computer will re-generate a new number which corresponds to its new starting position".
Is this posible to write? This is only a small time project but I would appreciate the help.
Oh, and I have been told I'm incorrectly using static in java, however if I don't include "static" in the code netbeans gives me errors for days until all of my code is like RED ERROR!!!! If anyone knows why or can explain how to properly use it please do as well :D
I sincerely appreciate any help I receive.
There is a method for checking whether a button is enabled or not...
if (button.isEnabled()) {
}else {}
and
if I don't include "static" in the code netbeans gives me errors for
days until all of my code is like RED ERROR!!
you Cannot make a static reference to the non-static field...
try dont using static things and create instances instead...
you can use as start point:
remove the static keyword from the fields, define a construtor and create an instance in the main method..
like this:
// YOU NEED A CONSTRUCTOR
public TicTacToe () {
computerGenerate = new Random();
panel = new JPanel();
s1 = new JButton();
}
public static void main(String[] args) {
TicTacToe demoExample = new TicTacToe ();
demoExample.Gui();
}
Static methods in java belong to the class (not an instance of it).
They use no instance variables and will usually take input from the
parameters, perform actions on it, then return some result
Secondly yes you can check that.
if(! s1.isEnabled())
{
...
}
Remember there is ! at the start of the condition which will check for enabled or not!
I'm using preferences to save the sound settings in my game as a boolean value. However, when I first start the game, the boolean initializes to false (sound off), because I'm not initializing it elsewhere. I could initialize it to true in the create method, but then the game would just start with sounds on every time you start the game, and that would just defeat the purpose of preferences.
Otherwise it works fine, it's just that I want the boolean to initialize to true the first time you start the game and not every time you restart it.
Is there a way to do this with preferences or do I have to use some other kind of saving method?
Note: this is a desktop application
public Preferences getPreferences() {
if (preferences == null) {
preferences = Gdx.app.getPreferences("myPrefs");
}
return preferences;
}
private void generatePreferences() {
getPreferences().clear();
getPreferences().putBoolean("soundEnabled", true).flush();
getPreferences().putBoolean("notFirstLaunch", true).flush();
}
public void loadPreferences() {
if (!getPreferences().getBoolean("notFirstLaunch")) {
generatePreferences();
} else {
//read the prefs and do your stuff
}
}
I would suggest you a slightly different approach:
Firstly, I think that the perfect place to initialize prefs is create method of the main game class (the one that extends Game):
public void create () {
Prefs.initPrefs();
....other initialization....
}
Then, initPrefs method looks like:
private static final String MUSIC_ON = "music_on";
private static final String LANG = "lang";
public static void initPrefs() {
boolean needChange = false;
if (!pref.contains(MUSIC_ON)) {
pref.putBoolean(MUSIC_ON, true);
needChange = true;
}
//if no lang - select system default
if (!pref.contains(LANG)) {
String language = Locale.getDefault().getLanguage();
pref.putString(LANG, language);
needChange = true;
}
if (needChange) {
pref.flush();
}
}
And finally to toggle the music:
public static boolean isMusicOn() {
return pref.getBoolean(MUSIC_ON);
}
public static void toggleMusic() {
pref.putBoolean(MUSIC_ON, !isMusicOn());
pref.flush();
}
I know this is a few years old now but just in case anyone else was wondering.
I think what you need to do is add a default value to your getBoolean() method without calling flush().
In my game i have a method called isSoundOn() which i call when my sound button is created. The very first time you start your game after installing it, you probably wont have saved a preference which means that the method below has to default to something. if you add true to the getBoolean method then your game should initialize to true.
public boolean isSoundOn() {
return preferences.getBoolean("soundOn", true);
}
I am trying to do some funky stuff which i have never done before.
So what i am trying to do is:
I create an object by doing the following
Player playerVar = new Player(1234);
Players constructor will then look for a player called 1234, if it exists, it will then deserialize and store the loaded object under 'playerVar', if not it'll just follow through and give a'blank'` player object.
I am not sure if its even possible to make the current object an other instance of the same object, so i am posting here.
This is essentially what i am trying to do.
this = deserielizedObject
I know this can all be done by loading the object, then setting all the necessary variables manually, but that is hardly ideal. How can i 'replace' an object with another instance of itself, from within itself
This is the code i currently have
player.java
public class Player implements java.io.Serializable
{
Player(String GUID) // when loading a new player
{
Player player = loadPlayer(GUID);
//i want to set this to player
// something like this = player If you know what i mean....
}
Player()//when creating a new player
{
}
private Player loadPlayer(String GUID)
{
File f = new File("data/players/"+GUID+".ser");
if(!f.exists())
{
Player player = new Player();
return player;
}
Player player = null;
try
{
FileInputStream fileIn = new FileInputStream("data/players/"+GUID+".ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
player = (Player) in.readObject();
in.close();
fileIn.close();
}
catch(IOException i)
{
i.printStackTrace();
return null;
}
catch(ClassNotFoundException c)
{
System.out.println("Cant find Player Class!");
c.printStackTrace();
return null;
}
return player;
}
private int guid;
private String name;
private int bankMoney;
.......
...
.
}
You could use a factory class/method. The simpliest way in your case would probably be to just have loadPlayer as a public static method.
public static Player loadPlayer(String GUID)
{
...
return player;
}
then:
Player playerVar = Player.loadPlayer(1234);
What you describe is not possible. But you could create a (static) factory method instead of the constructor, which either deserializes or creates a new instance.
You cannot assign a value to this, not possible. Why not directly call the loadPlayer method:
Player player = Player.loadPlayer(GUID); //having loadPlayer as public static