I'm searching on the internet for hours and i cannot find the right answer that works for me.
So.. I made a game called 'seabattle'
After playing that game the console comes with the question to play again.
System.out.println("Well done! " + whosturn.getName() + ". A ship down!" );
System.out.println("Hurraaaaaayyyyy, All boats down!!");
System.out.println("Do you want to play this game again? (y/n) ");
input = scanner.next().toLowerCase();
if(input == "y"){
System.out.println("The game should start again now..");
System.out.println("Butttttttt, I don't know how to...");
}
else{
System.out.println("Thank you for player Battleships!");
System.out.println("See you next time ;)");
}
}
else{
FiredPosition.setDisplayValue('*');
System.out.println("Good job, you hit a ship!");
switchTurn();
}
If the user types y in console. The game should start again.
I read something about Main(args) or something like that.. That didn't work for me because this is another class.
I hope you guys can help me?
Ciaoo
If your main class SeaBattle is currently as this:
public class SeaBattle {
public static void main(String[] args) {
...
}
}
you could change it the following way:
public class SeaBattle {
private static String[] args;
public static void run() {
//do the same than main() previously
}
public static void main(String[] args) {
SeaBattle.args = args;
run();
}
}
Then to relaunch the game,
SeaBattle.run();
A simple answer is: Whatever you do to start the game in the first place, do it again when you detect the 'y'.
However, a more in depth answer involves the use of an object to store and update the game state, it is not fully clear from your description whether you are currently doing this. So if it is a battleships type game the object may contain a 2d array for the game area, and perhaps a variable to store whose turn it is. This object would have an 'initialise' method where you randomly select where the ships are in the game area, set the value for whose turn it is, etc.
Your main method would interact with this object, so it would call the game object's initialise method, and after each turn it would call another method (e.g. 'isGameFinished') to check whether the game is over. The isGameFinished method would check if all of the ships have been destroyed and return true if so. If it returns true, then the user would be prompted for a new game. If they enter 'y', then you can either create a completely new object of the game state or just call the game state's initialise method again. You will then have a new game state to begin a new game with.
Related
So first off is just some text showing my thought process on the way the code should work. I am super new to programming in general and just started learning java only a few days ago. I think I have a basic understanding of how oop works but I can't implement it well into my code. The use of while loops makes a bit of sense to me though so I'm just starting out with those ;D
Things I want:
a main menu with 3 options
Menu (camp)
Quest (activates the quest loop)
Go to Town (activates the town loop)
quit game (exits the program)
Quest
Gameplay loop of fighting random monsters and gaining gold/score
"monster appears"
fight monster
does damage to monster
monster does damage back
back to main loop
use item
choose item
use item
item effects applied
back to main loop
run
return back to main menu (activates main menu)
Town
allows you to spend gold on "gear" to increase health and damage values
"I am the blacksmith blah blah blah"
Upgrade Weapon (increases damage)
Upgrade Armor (increases health)
Leave Town (returns player back to main menu)
Game Ends when player dies or chooses quit game
Display a Score and thank player for playing game
Below is just a prototype of the logic
I feel like this should work but every time I run it,
it doesn't work right and just ends up doing an
infinite loop. I'm hoping one of you guys will be able
to see why it doesn't work and kinda steer me in the right
direction. Anything would be greatly appreciated!
Also any comments on those booleans for camp, dungeon, town?
I don't know if I really needed those and its probably just
an extra bit of useless code but I'm really not sure.
import java.util.Scanner;
public class logic
{
public static void main(String[] args)
{
boolean running = true;
Scanner in = new Scanner(System.in);
System.out.println("This is a test");
while(running)
{
boolean camp = true;
boolean dungeon = false;
boolean town = false;
String input = in.nextLine();
while(camp)
{
System.out.println("what u do?");
System.out.println("1. go dungeon");
System.out.println("2. go town");
System.out.println("3. quit");
if (input.equals("1"))
{
dungeon = true;
while(dungeon)
{
System.out.println("you are in the dungeon");
dungeon = false;
break;
}
}
else if (input.equals("2"))
{
dungeon = false;
town = true;
while(town)
{
System.out.println("you are in the town");
town = false;
break;
}
}
else if (input.equals("3"))
{
break;
}
else
{
System.out.println("invalid command!");
}
}
}
}
}
Personally, I wouldn't use so much while loops and instead put each section's logic into its own function then use an if-else-if / switch statement to decide which function should be called and do this in a while loop, sadly I can't test this because I haven;t got a Java environment and its been a while since I used Java.
This is the new code I came up with. I was able to figure out how to break all the different areas up into their own methods. This should make building the game world much easier :D
import java.util.Scanner;
public class LogicTest
{
Scanner in = new Scanner(System.in);
public static void main(String[] args)
{
LogicTest game;
game = new LogicTest(); // a new instance of the public class folder has to be created in order to use all the other methods
game.run();
}
public void run() // this method is used to run the game from the main method
{
camp();
}
public void quest()
{
System.out.println("you go on quest");
camp();
}
public void town()
{
System.out.println("you go to town");
camp();
}
public void camp() // this method acts as the game hub where the player can choose what they want to do next
{
System.out.println("you are in your camp");
System.out.println("----------------------");
System.out.println("what do you want to do?");
System.out.println("1. go quest");
System.out.println("2. go town");
System.out.println("3. quit");
String input = in.nextLine();
// each one of these options just calls its respective method
// the methods are what have the menus and everything for each location
if (input.equals("1"))
{
quest();
}
else if (input.equals("2"))
{
town();
}
else if(input.equals("3")) // by leaving this empty the program has nothing else to read with this option and so it closes
{
}
else
{
camp();
}
}
}
I'm a beginner in Java and I am making a basic game for practice. I'm almost done, but I have one further obstacle to overcome.
I would like to know how to make the game loop on the game() method after pressing no as a choice when asked whether to end the game.
Here is my code:
private static void game() //game method
{
//...
int play = JOptionPane.showOptionDialog(null
,"End"
, "Do you want to play again?"
, JOptionPane.PLAIN_MESSAGE
,JOptionPane.DEFAULT_OPTION
, null
, again
, again[1]);
//end of game
if (play == 0)
System.exit(0);//exit
else
/* what do I put here to restart the program in the same method(game())
after pressing the No button on the JOptionPane??? */
System.out.println("Service not available");
To anybody who can help, I thank you very much!
Given the current state of your program, the easiest simplest most straightforward readable method is recursion. Just call your game method again. Note that there's probably a recursion limit, so the loop is the recommended method, even if it does involve restructuring your code a bit.
else{
game();
}
Loop method: declare play at the beginning and use a loop:
private static void game(){
boolean play = true;
while (play){
//...
//find out if user wants to play again
//set play to false if player doesn't want to play anymore
}
}
Extract the JOptionPane part from your game() function code
int play=0;
do{
game();
play = JOptionPane.showOptionDialog(null
,"End"
, "Do you want to play again?"
, JOptionPane.PLAIN_MESSAGE
,JOptionPane.DEFAULT_OPTION
, null
, again
, again[1]);
}while(play);
If you just want to make it work you can do something like this :
private static void game()//game method
{
boolean exit = false;
while(!exit){
//...int play = JOptionPane.showOptionDialog(null,"Play Again?", "Do you want to play again?", JOptionPane.PLAIN_MESSAGE,JOptionPane.DEFAULT_OPTION, null, again, again[1]);
//end of game
if (play == 0) {
exit = true;
}
}
System.exit(0);//exit
But a better more professionnal approach would be to refactor your code, so you extract game logic and separate it from User dialog interaction.
You can use this method which i am very sure will work in your program since it is something that i have done before. You'll use Desktop class of the system that will initiate the opening of the program. The program will look like this
public static void restart()
{
Desktop desktop = Desktop.getDesktop();
try {
desktop.open(new File("name_of_your_jarfile.jar").getCanonicalFile());
// desktop.open(new File("name_of_your_exe.exe").getCanonicalFile());//for exe
} catch (IOException e) {
//if this happen try looking whether the name of your jar file is correct
e.printStackTrace();
}
}
private static void game() //game method
{
//...
int play = JOptionPane.showOptionDialog(null
,"End"
, "Do you want to play again?"
, JOptionPane.PLAIN_MESSAGE
,JOptionPane.DEFAULT_OPTION
, null
, again
, again[1]);
//end of game
if (play == 0)
System.exit(0);//exit
else
/* what do I put here to restart the program in the same
after pressing the No button on the JOptionPane??? */
System.out.println("Service not available");
restart();//this will reopen your jar/exe file
System.exit(0);
}
I'm trying to put together a game, However, i'm not sure how to tackle the reset function. I have made it so that the game resets, this works, however, on game restart, the label that is supposed to display how many games the player has played does not change from 0. Heres what I have done so far.
The display and positioning of labels...
private int noGamesPlayed;
private JLabel gamesPlayed = new JLabel("Games Played = " + noGamesPlayed);
getContentPane().add(gamesPlayed);
gamesPlayed.setBounds(60,60+gridsize*boardsize,130,30);
The reset function...
public void reset(){
game.this.setVisible(false);
game.this.dispose();
new game();
updateGamesPlayed();
}
The function that is suppose to update the games played...
public void updateGamesPlayed() {
noGamesPlayed ++;
gamesPlayed.setText("" + noGamesPlayed + " Games Played");
}
Help Appreciated.
Change the noOfGamesPlayed variable to static. That field does not belong to the object, but to the class itself. Then, change the updateGamesPlayed to a static method, this way all game objects will see the same numberOfGamesPlayed count. Like that:
private static int noGamesPlayed = 0;
public static void updateGamesPlayed() {
noGamesPlayed ++;
}
Then, on the reset method, create a new game after updating the number of games played.
public void reset(){
game.this.setVisible(false);
game.this.dispose();
updateGamesPlayed();
new game();
}
You can also make it "automatic" by incrementing the noGamesPlayed on the game constructor. That way you don't need to call updateGamesPlayed.
You're creating a completely new game object, one that has its own noGamesPlayed variable and JTextField, and likely this method call is not changing the gamesPlayed JTextField in the newly displayed GUI
gamesPlayed.setText("" + noGamesPlayed + " Games Played");
but rather is updating the JTextField of the GUI that has been disposed of. Note that your reset method looks to be recursive.
One solution is to call the updateGamesPlayed(...) method of the newly created game object (note that the class should be renamed Game), and pass in the correct number as a parameter.
Myself, I'd go about resetting my game in a completely different way, by not creating a new window, but instead by updating the key model variables (the non-GUI variables and classes that determine the state of your program) and then using those variables to reset the current display.
I am currently making a TicTacToe program for an assignment in college. I have my board laid out with 3x3 JTextFields, each one has an action listener attached. What I need to do is create another class which will check for errors (eg a user will put a number or a letter that is NOT x or o) they should get a dialog box stating the error and the JTextField they tried to enter will return to blank. How would I go about implementing the error checking, through try - catch - finally method?
Another question, I have a GameGUI class, I also want to have a GameLogic class. How do I check from GameLogic if the game has been won? In my GameLogic I will have something like
if j1, j2 and j3 are all x or o then display dialog box "x player wins".
I will try to answer the question regarding a general board game. Your object oriented thinking of splitting into different classes is correct. What I do generally is that I have the GameLogic containing my logic and validations for the game as well as determining whether the game is over or not and so on.
The GameGUI class would then have an instance variable of the type GameLogic that's initialized on creating an object of type GameGUI. In my way of thinking, I would have the GameLogic representing the board state with 2D Array of chars. The GameGUI would be just there to relay input from the user to the GameLogic which determines if the game is over. The GameLogic should throw an Exception of the type that you want to clarify and then the GameGUI should try to update the board with the input text from the user in the JText fields, catch the error from the GameLogic (if any) and then repaint the GUI that's displayed to the user based on the input it got. I will give a sample below to clarify my point although I won't provide the actual implementation for the TicTacToe game, you can easily do it on your own.
public class GameLogic {
....
char[][]board;
public GameLogic() {
//initialize the board representation for game
}
public boolean gameOver() {
//determine if the game is over by checking the board 2D array
// 3 xs or os in a row, column, or diagonal should determine the game is over or if there are no more moves
}
public void move(char character, int x, int y) {
//update a certain position with a character should throw an Exception if the character is invalid or if the the character is valid but it's not the character that the user owns player1 plays with x for example but puts o.
//should also have the logic for the turns
}
...
}
public class GameGUI {
.....
GameLogic engine;
public GameGUI() {
engine = new GameLogic();
}
public void actionPerformed(ActionEvent e) {
// here you would get the co-ordinates of the clicked JTextButton
// then call the method move on the engine instance
try {
engine.move(character, x, y);
} catch(Exception e) {
//display the validation for the error that happened
}
//repaint the representation from the engine to be displayed on the GUI Frame that you are using
}
...
}
One more thing is that I would have declared the JTextFields as 2D Array of JTextFields and not as individual instance variables to mirror the representation in the GameLogic class. You can also avoid the validations all together if you use JButton class instead of JTextField and that the user gets the character he is playing with on the clicked button if it is his turn and the button is not already used before.
I have been stuck for the past month and I did not find any solution.
my problem is I am writing a game of four players. three are computers and one human.
so there are a play() function for computers and one Overridden play() function for human.
here is the function which human player will use
#Override
public void play(){
for(int i=0 ; i <13;i++){
getJLabels()[i].addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent evt)
{
int Index = getIndex(getJLabels(), (JLabel)evt.getSource());
getJLabels()[Index].setIcon(getHand()[Index].getBackSide());
getPlayerJLabel().setIcon(getHand()[Index].getCardImage());
setObjectForPlay(getHand()[Index]);
}
});
}
temp = getObjectForPlay();
return temp;
}
Other three players use play() and return an object automatically. i mean the mouselistener is only for this human.play() function
i am running these functions from nested loop. when a round of loop complete every player complete his play() turn and then next loop start. and so on.
Problem is computers play() functions are not waiting for human to click.
I want that when loop play the human Play() then wait for human to click and return object. when human play() end with click then next computer play() call
My english is poor thanks for understanding
waiting for nice solution