This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 4 years ago.
Thats my tictactoe game and i have this problem i cant find out...When i compile my programm
Welcome To Tic Tac Toe Professor Falken!
***Use Numbers 1-9 To Select A Square***
_1_|_2_|_3_|
_4_|_5_|_6_|
_7_|_8_|_9_|
You Go First!
___|___|___|
___|___|___|
___|___|___|
Player X, enter move (1 - 9):
10
INVALID MOVE: Enter number 1 - 9 only:
5
___|___|___|
___|_X_|___|
___|___|___|
Player O, enter move (1 - 9):
___|___|___|
___|_X_|_O_|
___|___|___|
Player X, enter move (1 - 9):
4
___|___|___|
_X_|_X_|_O_|
___|___|___|
Player O, enter move (1 - 9):
And stops there, i dont know why can anyone help me?
import java.util.Random;
import java.util.Scanner;
public class TicTacToe {
private Scanner in;
private boardPiece[][] board = {{new boardPiece(),new boardPiece(),new boardPiece()},
{new boardPiece(),new boardPiece(),new boardPiece()},
{new boardPiece(),new boardPiece(),new boardPiece()}};
private char turn = 'X';
private boolean win = false;
private int count = 0;
private Random random = new Random();
private int randomNumber = random.nextInt(9);
public static void main(String [] args)
{
int replay;
TicTacToe game = new TicTacToe();
game.in = new Scanner(System.in);
System.out.println("Welcome To Tic Tac Toe Professor Falken!");
System.out.println("***Use Numbers 1-9 To Select A Square***");
System.out.println("_1_|_2_|_3_|");
System.out.println("_4_|_5_|_6_|");
System.out.println("_7_|_8_|_9_|");
System.out.println(" n You Go First!");
game.play();
System.out.println("Would you like to play again?(1 = Yes & 2 = No): ");
replay = game.in.nextInt();
while(replay != 2){
game.init();
game.play();
System.out.println("Would you like to play again?(1 = Yes & 2 = No): ");
replay = game.in.nextInt();
}
game.in.close();
System.out.println("How about a nice game of chess :p");
}
public void play()
{
printBoard();
while(!win)
move();
}
public void printBoard()
{
for(int x=0; x<3; x++){
for(int y=0; y<3; y++){
System.out.print(board[x][y].piece);
}
System.out.println();
}
}
public void move()
{
int move = 0;
String valid = "";
System.out.println("Player " + turn + ", enter move (1 - 9): ");
if(turn == 'O') {
move = randomNumber; }
else {
move = in.nextInt();
}
valid = checkMove(move);
while(valid != "ok")
{
if(turn == 'X') {
System.out.println("INVALID MOVE: "+ valid);
move = in.nextInt();
}
else {
move = randomNumber;
}
valid = checkMove(move);
}
count++;
board[(move-1)/3][(move-1)%3].piece = "_"+turn+"_|";
board[(move-1)/3][(move-1)%3].player = turn;
board[(move-1)/3][(move-1)%3].used = true;
printBoard();
if(count >= 5)
checkWin(move);
if(turn == 'X')
turn = 'O';
else
turn = 'X';
}
public String checkMove(int move)
{
if(move < 1 || move > 9)
return "Enter number 1 - 9 only: ";
else
if(board[(move-1)/3][(move-1)%3].used)
return "That move has been used. Enter another move (1 - 9): ";
else
return "ok";
}
public void checkWin(int move)
{
for(int x = 0; x<3; x++){ //Horizontal
if((board[x][0].used && board[x][1].used && board[x][2].used) &&
(board[x][0].player == board[x][1].player && board[x][0].player == board[x][2].player)){
System.out.println("Congratulations Player " + turn + "!!! You win!");
win = true;
return;
}
}
for(int y = 0; y<3; y++)
{
if((board[0][y].used && board[1][y].used && board[2][y].used) &&
(board[0][y].player == board[1][y].player && board[0][y].player == board[2][y].player)){
System.out.println("Congratulations Player " + turn + "!!! You win!");
win = true;
return;
}
}
if((board[0][0].used && board[1][1].used && board[2][2].used) &&
(board[0][0].player == board[1][1].player && board[0][0].player == board[2][2].player)){
System.out.println("Congratulations Player " + turn + "!!! You win!");
win = true;
return;
}
if((board[2][0].used && board[1][1].used && board[0][2].used) &&
(board[2][0].player == board[1][1].player && board[2][0].player == board[0][2].player))
{
System.out.println("Congratulations Player " + turn + "!!! You win!");
win = true;
return;
}
if(count==9){
System.out.println("Draw! Nobody Wins (ยด???`)");
win = true;
return;
}
}
public void init()
{
for(int x=0;x<3;x++){
for(int y=0;y<3;y++){
board[x][y] = new boardPiece();
}
}
turn = 'X';
win = false;
count = 0;
}
class boardPiece{
public String piece;
public char player;
public boolean used;
boardPiece(){
piece = "___|";
used = false;
}
}
}
I made a some changes in move and checkMove
public void move() {
int move = 0;
Boolean valid = false;
System.out.println("Player " + turn + ", enter move (1 - 9): ");
if (turn == 'O') {
move = randomNumber;
} else {
move = in.nextInt();
}
valid = checkMove(move);
while (!valid) {
if (turn == 'X') {
move = in.nextInt();
} else {
move = random.nextInt(9);
}
valid = checkMove(move);
}
count++;
board[(move - 1) / 3][(move - 1) % 3].piece = "_" + turn + "_|";
board[(move - 1) / 3][(move - 1) % 3].player = turn;
board[(move - 1) / 3][(move - 1) % 3].used = true;
printBoard();
if (count >= 5) {
checkWin(move);
}
if (turn == 'X') {
turn = 'O';
}else {
turn = 'X';
}
}
public Boolean checkMove(int move) {
if (move < 1 || move > 9) {
System.out.println("INVALID MOVE: Enter number 1 - 9 only: ");
return false;
}else if (board[(move - 1) / 3][(move - 1) % 3].used) {
System.out.println("INVALID MOVE: That move has been used. Enter another move (1 - 9): ");
return false;
}else {
return true;
}
}
Related
This is my nim game (goal is dont be the last person to pick up marbles), can someone please guide me. In playing the game, I have just one question
How can I keep track of whose turn it is, I guess if I can keep track of that I can monitor my remainingMarbles. This is the crux of my code. Please help
public class Nim{
public static void main(String[] args)
{
System.out.println("************** Welcome to the game of Nim *******************");
System.out.println("The object of this game is to make me take the last marble off the table");
System.out.println("You must take at least 1 and you can take up to 3 marbles on your turn");
System.out.println("You can go first");
Scanner scan = new Scanner(System.in);
final int MARBLES = 13;
int remainingMarbles;
String input;
do {
//boolean whoseTurn = true;
remainingMarbles = MARBLES;
System.out.println("There are " + MARBLES + " marbles on the table");
while (remainingMarbles > 0){
remainingMarbles -= getUserSelection();
System.out.println("There are " + (remainingMarbles -= getComputerSelection()) + " marble(s) on the table.");
}
if (1 <= remainingMarbles && remainingMarbles <= 2 && remainingMarbles < 0) {
System.out.println("Congratulations! you won!");
System.out.println("Want to play again? y/n");
input = scan.nextLine();
input = input.toLowerCase();
} else
System.out.println("Hard luck you lose!");
System.out.println("Want to play again? y/n");
input = scan.nextLine();
input = input.toLowerCase();
}while (input.charAt(0) == 'y');
}
private static int getUserSelection()
{
Scanner scan = new Scanner(System.in);
do {
System.out.println("Enter 1, 2 or 3");
int userSelection = scan.nextInt();
if (isValidMove(userSelection)){
return userSelection;
}
else {
System.out.println("Not a valid entry");
}
}while (true);
}
private static boolean isValidMove(int input)
{
return 1 <= input && input <= 3;
}
private static int getComputerSelection ()
{
Random generator = new Random();
int computerSelection = 1 + generator.nextInt(3);
System.out.println("The computer chooses " + computerSelection);
return computerSelection;
}
}
First, make a boolean before the loop.
boolean whoseTurn = true;
When the variable is true it's the first player's turn, otherwise the second player's turn.
Now inside the while loop we change the variable at the end of every repetition:
whoseTurn = !whoseTurn;
(Which is a faster way of this)
if(whoseTurn) whoseTurn = false;
else whoseTurn = true;
To conclude, you should do something like that:
...
boolean whoseTurn = true;
while(remainingMarbles > 0){
remainingMarbles -= getUserSelection();
System.out.println("There are " + (remainingMarbles -= getComputerSelection()) + " marble(s) on the table.");
whoseTurn = !whoseTurn;
}
...
I am printing simple map of numbers 1,2,3,4,5,6,7,8 (10/10) and everytime i type LEFT or RIGHT it doesnt tell me if im falling off the map but he is asking me if next YX is bigger than 9(collision from bottom and right) or its less than 0(collision from top and right) but instead he asks me what is in next cell( is it 1,2,3,4,5,6,7,8)
How the F*** do i check if he does not fall of the map?
Help please!!!!!!!
import java.util.Scanner;
public class Game {
static String dir = "";
static int player;
static int chest;
static int monster;
static int key;
static int tile;
static int wall;
static int keysFound = 0;
static int chestsOpened = 0;
static int chestsLeft = 3;
static int sword = 0;
static int angel;
static int pickaxe = 0;
static Scanner scan = new Scanner(System.in);
static int[][] map = new int[10][10];
static int x = map[0][0];
static int y = map[0][0];
static int playerPos = map[x][y];
static int life = 3;
static boolean isInGame;
static String NoTileFound = "trying to knock this wall is pointless try some other move";
static String FreeTile = "you move to a free tile";
public static void main(String[] args) {
MapCreator mapcreate = new MapCreator();
map = mapcreate.getMapcreated();
int isPlaying;
System.out.println(" Welcome to the game, kill monsters and open three chests to win");
System.out.println(" Gather a key to open the chest, collect 3 of theese to win! that's it!");
System.out.println(" Press 1 to play..anything else to exit!");
isPlaying = scan.nextInt();
if (isPlaying == 1) {
isInGame = true;
enterGame();
} else {
System.out.println("You missed out on a good game...");
System.exit(1);
}
}
public static void enterGame() {
System.out.println(
"Type, up, down, left, or right, to move. equipment to see what you have and exit to exit game");
while (isInGame) {
move();
}
}
public static void move() {
dir = scan.nextLine();
switch (dir) {
case "up":
entertileup();
break;
case "down":
entertiledown();
break;
case "left":
entertileright();
break;
case "right":
entertiledown();
break;
case "equipement":
System.out.println("you have " + life + " lifes, " + key + " keys and " + chestsOpened
+ " chests opened, keep searching solider!");
move();
break;
case "exit":
System.out.println("You missed out on a good game...");
System.exit(1);
}
ShowMap mapprint = new ShowMap();
mapprint.print(map);
}
public static void map() {
wall = 1;
tile = 2;
monster = 3;
chest = 4;
key = 5;
sword = 6;
player = 0;
angel = 7;
pickaxe = 8;
if (playerPos == tile) {
System.out.println(FreeTile);
}
if (playerPos == monster) {
monsterEncounter();
}
if (playerPos == chest) {
openChest();
}
if (playerPos == key) {
findKey();
}
if (playerPos == sword) {
findsword();
if (playerPos == angel) {
findangel();
}
if (playerPos == pickaxe) {
findpickaxe();
}
}
}
public static void entertileup() {
if (x + 1 > 9) {
System.out.println(NoTileFound);
move();
} else if (map[x + 1][y] == 1) {
if (pickaxe == 0) {
System.out.println(NoTileFound);
move();
}
else if (pickaxe == 1) {
map[x][y] = 2;
x = x + 1;
playerPos = map[x][y];
map();
}
} else if (map[x + 1][y] == 2)
x = x + 1;
playerPos = map[x][y];
map();
}
public static void entertiledown() {
if (x - 1 < 0) {
System.out.println(NoTileFound);
move();
} else if (map[x - +1][y] == 1) {
if (pickaxe == 0) {
System.out.println(NoTileFound);
move();
}
else if (pickaxe == 1) {
map[x][y] = 2;
x = x - 1;
playerPos = map[x][y];
map();
}
} else if (map[x - 1][y] == 2)
x = x - 1;
playerPos = map[x][y];
map();
}
public static void entertileright() {
if (y - 1 < 0) {
System.out.println(NoTileFound);
move();
} else if (map[x][y - 1] == 1) {
if (pickaxe == 0) {
System.out.println(NoTileFound);
move();
}
else if (pickaxe == 1) {
map[x][y] = 2;
y = y - 1;
playerPos = map[x][y];
map();
}
} else if (map[x][y - 1] == 2)
y = y - 1;
playerPos = map[x][y];
map();
}
public static void entertileleft() {
if (y + 1 > 9) {
System.out.println(NoTileFound);
move();
} else if (map[x][y + 1] == 1) {
if (pickaxe == 0) {
System.out.println(NoTileFound);
move();
}
else if (pickaxe == 1) {
map[x][y] = 2;
y = y + 1;
playerPos = map[x][y];
map();
}
} else if (map[x][y + 1] == 2)
y = y + 1;
playerPos = map[x][y];
map();
}
public static void findsword() {
System.out.println("You found a sword, monsters can't kill you! ");
sword = sword + 1;
map[x][y] = 0;
}
public static void findangel() {
System.out.println("You have found angel! what a mighty creature! He gives you a life");
life = life + 1;
map[x][y] = 0;
}
public static void findpickaxe() {
System.out.println("You have found a pickaxe Niceeee! you can destroy walls now! just simply walk over it");
pickaxe = pickaxe + 1;
map[x][y] = 0;
}
public static void monsterEncounter() {
if (sword == 0) {
if (life > 0) {
System.out.println("WOAH! A MONSTER! You kill him but you lose a life!");
life = life - 1;
System.out.println("You have: " + life + " life(s) left! Don't die out there!");
map[x][y] = 0;
} else {
System.out.println("You have: " + life + " , You encountered too many monsters. GAME OVER.");
System.exit(1);
}
} else {
System.out.println(" You killed a monster with mighty sword, no life loss, nice! ");
map[x][y] = 0;
}
}
public static void findKey() {
System.out.println("You found a key, nice!");
keysFound += 1;
map[x][y] = 2;
}
public static void openChest() {
System.out.println("Chest, nice!!");
if (keysFound >= 1) {
chestsOpened += 1;
int totalChestsFound = chestsLeft - chestsOpened;
chestsLeft -= 1;
System.out.println("You have opened a chest! You have " + totalChestsFound + " chests to go!");
map[x][y] = 2;
keysFound -= 1;
}
if (chestsLeft == 0) {
System.out.println("YOU WON! GOOD GAME SIR, GOOD GAME.");
System.exit(1);
} else {
System.out.println("No keys, no chests. Keep searching soldier.");
}
}
}
It looks like your map is a multidimensional array (0..7)(0..7), is it possible that what you're seeing is because you looking at a boundary of "9" and not "7"?
I also see that in your move() switch, case "left" looks at "entertileright()" and case "right" looks at "entertiledown()".
I have been trying to figure out how to write the code to reset my program/ clear the board so tic tac toe can be played again. It is supposed to have a prompt that asks "do you want to play again" after a win/tie. It's the final part I am trying to figure out.
Board:
public class Board {
private char[][] board;
public Board() {
char[][] temp = {{'1', '2', '3'}, {'4', '5', '6'}, {'7', '8', '9'}};
board = temp;
}
public void printBoard() {
for (char[] row : board) {
for (char cell : row) {
System.out.printf("| %c ", cell);
}
System.out.println();
}
}
public boolean isCellAvailable(int number) {
if (1 <= number && number <= 9) {
int row = (number - 1) / 3;
int col = (number - 1) % 3;
if (board[row][col] == 'X' || board[row][col] == 'O') return false;
else return true;
}
return false;
}
public void place(int number, char marker) {
int row = (number - 1) / 3;
int col = (number - 1) % 3;
board[row][col] = marker;
}
public boolean isWinner() {
if (board[0][0] == board[0][1] && board[0][1] == board[0][2]) return true;
else if (board[1][0] == board[1][1] && board[1][1] == board[1][2]) return true;
else if (board[2][0] == board[2][1] && board[2][1] == board[2][2]) return true;
else if (board[0][0] == board[1][0] && board[1][0] == board[2][0]) return true;
else if (board[0][1] == board[1][1] && board[1][1] == board[2][1]) return true;
else if (board[0][2] == board[1][2] && board[1][2] == board[2][2]) return true;
else if (board[0][0] == board[1][1] && board[1][1] == board[2][2]) return true;
else if (board[0][2] == board[1][1] && board[1][1] == board[2][0]) return true;
return false;
}
}
Driver:
import java.util.Scanner;
class Driver {
public static void main(String[] args) {
Board board = new Board();
Scanner scanner = new Scanner(System.in);
board.printBoard();
int moves = 0;
while (true) {
while (true) {
System.out.print("Player 1: Enter your move: ");
int cell = scanner.nextInt();
if (board.isCellAvailable(cell)) {
board.place(cell, 'X');
board.printBoard();
moves += 1;
break;
} else {
System.out.println("Cell not available.");
}
}
if (board.isWinner()) {
System.out.println("Player 1 wins.");
break;
}
if (moves == 9) {
System.out.println("Draw. Game ended.");
break;
}
while (true) {
System.out.print("Player 2: Enter your move: ");
int cell = scanner.nextInt();
if (board.isCellAvailable(cell)) {
board.place(cell, 'O');
board.printBoard();
moves += 1;
break;
} else {
System.out.println("Cell not available.");
}
}
if (board.isWinner()) {
System.out.println("Player 2 wins.");
break;
}
}
}
}
You need another loop in order to manage the Play again option. If the player wants to play again, a new Board() is created and the moves are reseted as well. Something like this:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (true) {
Board board = new Board();
board.printBoard();
int moves = 0;
while(true){
while (true) {
System.out.print("Player 1: Enter your move: ");
int cell = scanner.nextInt();
if (board.isCellAvailable(cell)) {
board.place(cell, 'X');
board.printBoard();
moves += 1;
break;
} else {
System.out.println("Cell not available.");
}
}
if (board.isWinner()) {
System.out.println("Player 1 wins.");
break;
}
if (moves == 9) {
System.out.println("Draw. Game ended.");
break;
}
while (true) {
System.out.print("Player 2: Enter your move: ");
int cell = scanner.nextInt();
if (board.isCellAvailable(cell)) {
board.place(cell, 'O');
board.printBoard();
moves += 1;
break;
} else {
System.out.println("Cell not available.");
}
}
if (board.isWinner()) {
System.out.println("Player 2 wins.");
break;
}
}
System.out.println("Do you want to play again? Press 1, otherwise press 0")
int option = scanner.nextInt();
if(option == 0) break;
}
}
I would like to ask why the program prints already the answer? Even if I select on different Difficulty it is still the same.
import java.util.Scanner;
import java.util.Random;
public class GuessigGame {
public static int level(int y) {
Random ans = new Random();
int easy = 20, medium = 50, hard = 10, x;
Scanner in = new Scanner(System.in);
System.out.println("Choose Difficulty");
System.out.println("1. easy ");
System.out.println("2. medium ");
System.out.println("3. hard ");
x = in.nextInt();
switch (x) {
case 1:
System.out.println("Easy");
y = easy;
break;
case 2:
System.out.println("Medium");
y = medium;
break;
case 3:
System.out.println("Hard");
y = hard;
break;
default:
break;
}
return y;
}
public static void main(String[] args) {
int choice, difficulty = 0, answer = -1;
Scanner in = new Scanner(System.in);
Random rand = new Random();
System.out.println("\n\n1. Play Game");
System.out.println("2. Exit");
System.out.println("");
choice = in.nextInt();
int diff = 0, tries = 0, triesbot = 0, trieshu = 0;
diff = level(difficulty);
difficulty = 1 + rand.nextInt(diff);
boolean win = false;
switch (choice) {
case 1:
while (win != true) {
System.out.println(difficulty);
System.out.println("Tries: " + tries);
answer = in.nextInt();
if (answer == difficulty + 1 || answer == difficulty - 1) {
System.out.println("so close");
} else if (answer == difficulty + 2 || answer == difficulty + 2) {
System.out.println("youre answer was close");
} else if (answer == difficulty + 3 || answer == difficulty - 3) {
System.out.println("try more youre close");
} else if (answer == difficulty + 4 || answer == difficulty - 4) {
System.out.println("try youre best buddy!");
} else if (answer > difficulty + 4 || answer < difficulty - 4) {
System.out.println("so far!");
} else if (tries == 0) {
System.out.print("Game Over!");
win = true;
} else if (answer == difficulty) {
System.out.println("You got the correct answer!!!!");
win = true;
} else {
}
tries++;
}
break;
default:
System.exit(0);
break;
}
}
}
This is the output of the program:
Because you told the computer to print out the difficulty. I suggest having better names.
difficulty = 1 + rand.nextInt(diff);
boolean win = false;
switch(choice) {
case 1:
while(win != true) {
System.out.println(difficulty);
System.out.println("Tries: " + tries);
Paper rock scissors java program.
Ok so the only problem I'm having now is the player's score doesn't update until the second loop around. Any suggestions?
Thanks again Radiodef for your help!!
Updated code below.......
import java.util.Scanner;
public class RPS_Game {
public static void main(String[] args) {
char r = 'R';
char p = 'P';
char s = 'S';
char player1 = 0;
char player2 = 0;
int player1Score = 0;
int player2Score = 0;
int playCount = 0;
Scanner scan = new Scanner(System.in);
while(playCount < 3) {
System.out.print("Please enter either (R)ock, (P)aper, or (S)iccors: ");
player1 = scan.nextLine().toUpperCase().charAt(0);
System.out.print("Please enter either (R)ock, (P)aper, or (S)iccors: ");
player2 = scan.nextLine().toUpperCase().charAt(0);
int winner = winningPlayer(player1, player2);
if(winner == 0) {
System.out.print("\nIt's a tie. Nobody wins!\n");
System.out.println("\nPlayer 1: " + (player1Score += 0));
System.out.println("\nPlayer 2: " + (player2Score += 0));
}
if(winner == 1) {
System.out.print("\nPlayer 1 wins!!\n");
System.out.println("\nPlayer 1: " + player1Score++);
System.out.println("\nPlayer 2: " + (player2Score += 0));
}
if(winner == 2) {
System.out.print("\nPlayer 2 wins!!\n");
System.out.println("\nPlayer 1: " + (player1Score += 0));
System.out.println("\nPlayer 2: " + player2Score++);
}
playCount++;
}
}
public static int winningPlayer(int player1, int player2) {
//Player 1 wins
int result = 0;
if(player1 == 'R' && player2 == 'S') {
result = 1;
}
else if(player1 == 'P' && player2 == 'R') {
result = 1;
}
else if(player1 == 'S' && player2 == 'P') {
result = 1;
}
//Player 2 wins
else if(player2 == 'R' && player1 == 'S') {
result = 2;
}
else if(player2 == 'P' && player1 == 'R') {
result = 2;
}
else if(player2 == 'S' && player1 == 'P') {
result = 2;
}
return result;
}
}
Well, it seems like first you just need to move the call in to the loop:
while(playCount < 3) {
System.out.print("Please enter either (R)ock, (P)aper, or (S)iccors: ");
player1 = scan.nextLine().toUpperCase().charAt(0);
System.out.print("Please enter either (R)ock, (P)aper, or (S)iccors: ");
player2 = scan.nextLine().toUpperCase().charAt(0);
// recompute the winner each time
int winner = winningPlayer(player1, player2);
...
}
For keeping a score, you could just have a variable for each player:
int player1Score = 0;
int player2Score = 0;
while (...) {
...
if (winner == 1) {
++player1Score;
}
if (winner == 2) {
++player2Score;
}
}
Or you could do something fancier like use an array:
int[] scores = new int[3];
while (...) {
...
++scores[ winner ];
for (int i = 1; i < scores.length; ++i) {
System.out.printf("Player %d score is %d.\n", i, scores[i]);
}
}