Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am writing a TicTacToe game, and it repeatedly prompts the user for a move. It is asking for a selection more than 9 times and I am not sure why.
My design has a 2-dimensional array to store information about the current state of the board, use JOptionPane to ask users for selection of the board (1 for top left, 2 for top middle, 3 for top right, 4 for middle left, etc). After every move, output into the console the current board. If a spot is already used, prompt the user again. (There is no need for a winner check, as we were told to do this another time.
Here is my entire code:
import javax.swing.JOptionPane;
// Basic TicTacToe game.
public class TicTacToe1 {
public static void main(String[] args){
// Hello there!
Object[] options = { "I'm ready to play!",};
Object[] options2 = { "Select another number.",};
JOptionPane.showOptionDialog(null,"To play TicTacToe, use the numbers 1 to 9 to choose where you place a mark. Are you ready?","TicTacToe1",
JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null, options, options[0]);
// Define the board.
char board[][] = new char[3][3];
// Zero out the board.
for(int a=0; a<3; a++) {
for(int b=0; b<3; b++) {
board[a][b] = ' ';
}
}
// Print an initial, clean board.
print(board);
// Use a for loop to ask for the selection and nest the selector into it.
for(int i=1; i<10 ; i++) {
if ((i%2) == 1) {
boolean goahead = true;
while (goahead) {
int selection = Integer.parseInt(JOptionPane.showInputDialog(null,"Where do you want to place an X?"));
if ((board[(((selection-1)-((selection-1)%3))/3)][(selection-1)%3]=='X') || (board[(((selection-1)-((selection-1)%3))/3)][(selection-1)%3]=='O')) {
JOptionPane.showOptionDialog(null,"I'm sorry, the number "+selection+" spot is already being used.","TicTacToe1",
JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null, options2, options2[0]);
} else {
goahead = false;
board[(((selection-1)-((selection-1)%3))/3)][(selection-1)%3] = 'X';
print(board);
}
}
}
if ((i%2) == 1) {
boolean goahead = true;
while (goahead) {
int selection = Integer.parseInt(JOptionPane.showInputDialog(null,"Where do you want to place an O?"));
if ((board[(((selection-1)-((selection-1)%3))/3)][(selection-1)%3]=='X') || (board[(((selection-1)-((selection-1)%3))/3)][(selection-1)%3]=='O')) {
JOptionPane.showOptionDialog(null,"I'm sorry, the number "+selection+" spot is already being used.","TicTacToe1",
JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null, options2, options2[0]);
} else {
goahead = false;
board[(((selection-1)-((selection-1)%3))/3)][(selection-1)%3] = 'O';
print(board);
}
}
}
// didsomeonewinyet(board);
}
}
// Make a helper function named print to print the board
public static void print(char board[][]){
for(int a=0; a<3; a++) {
for(int b=0; b<3; b++) {
System.out.print("|"+board[a][b]+"|");
}
System.out.println();
}
System.out.println();
}
// Winner checker.
// public static void didsomeonewinyet(char board[][]){
// Manually checking will yield 16 cases (2 diagonal, 3 horizontal, 3 vertical, either X or O), which is not that bad.
// }
}
Why does it ask for a selection too many times?
Your if conditions in the for loop are the same so they both occur during the same iteration of the loop:
if ((i%2) == 1) {
one of the if statements should be:
if ((i%2) == 0) {
depending on who you want to go first.
Alternatively you could just use an else statement:
if ((i%2) == 1) {
//code for x to go
}else {
//code for y to go
}
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 days ago.
Improve this question
I'm writing a Chess plugin with Spigot, and I can't figure out why the GUI isn't working as I expected it to.
I've been trying to create a Chess board using the Minecraft inventory GUI, and I've managed to create a chequered pattern so far. For the time being, I've just been trying to leave spaces blank if a piece is at those given coordinates, however I've only managed to leave one space blank at a time, and at the wrong coordinates. I mostly want to figure out why only one space is being left blank though, instead of the top two and bottom two rows being blank as they should be.
I believe two classes in particular are the culprit, the "Game" and "GameGUI" classes. "Game" of course takes charge of the implementation of the actual game logic, and the "GameGUI" class handles player interactions.
Here is the constructor from the "Game" class:
public Game(GamePlayer player1, GamePlayer player2, String instance) {
Game.player1 = player1;
Game.player2 = player2;
Game.instance = instance;
Piece[][] player1Pieces = new Piece[8][6];
Piece[][] player2Pieces = new Piece[8][6];
setUpPieces(player1, player1Pieces);
setUpPieces(player2, player2Pieces);
Game.pieces.put(player1, player1Pieces);
Game.pieces.put(player2, player2Pieces);
}
So, as can be seen above, when a game is created, it gives each of the players a two-dimensional array of pieces. If you think it's odd to use a two-dimensional array for this purpose, I'm using it because I was trying to fix the problem that I'm currently facing. I was originally just using a List, then I tried an array of Lists, and now I'm on to a two-dimensional array. Of course, now there's the possibility of a piece being null, but I run a check in the GameGUI class if the piece is null, as you'll see later on in this post.
I am putting each type of Chess piece in its own array within the two-dimensional array, like so:
public static void setUpPieces(GamePlayer player, Piece[][] pieces) {
pieces[0] = setUpPawns(player);
pieces[1] = setUpRooks(player);
pieces[2] = setUpKnights(player);
pieces[3] = setUpBishops(player);
pieces[4] = setUpQueen(player);
pieces[5] = setUpKing(player);
}
Each of those methods looks roughly like this:
public static Piece[] setUpPawns(GamePlayer player) {
Piece[] initialSetup = new Piece[8];
String color = player.getColor();
int y1 = color.equals("WHITE") ? 2 : 7;
for (int i = 1; i <= 8; i++) {
initialSetup[i - 1] = new Piece(i, y1, new PieceType("PAWN"), color);
}
return initialSetup;
}
I thought it might help to mention that absolutely every variable in the "Game" class is static, as well.
So here's the GUI code, which ChatGPT helped me make:
public void initializeItems() {
Piece[][] pieces = Game.getPieces(game.getPlayer1());
Piece[][] opponentPieces = Game.getPieces(game.getPlayer2());
for (int i = 0; i < 72; i++) {
if (i % 9 < 8) {
int x = i % 9;
int y = 8 - i / 9;
boolean isOccupied = false;
for (Piece[] pieceArray : pieces) {
for (Piece piece : pieceArray) {
if (piece != null) {
if (piece.getX() == x && piece.getY() == y) {
System.out.println(piece.getType().getName());
isOccupied = true;
break;
}
}
}
}
for (Piece[] pieceArray : opponentPieces) {
for (Piece piece : pieceArray) {
if (piece != null) {
if (piece.getX() == x && piece.getY() == y) {
System.out.println(piece.getType().getName());
isOccupied = true;
break;
}
}
}
}
if (!isOccupied) {
if ((x + y) % 2 == 0) {
if (i < 54) {
inv.setItem(i, new ItemStack(WHITE_STAINED_GLASS_PANE));
} else {
pInv.setItem(i - 45, new ItemStack(WHITE_STAINED_GLASS_PANE));
}
} else {
if (i < 54) {
inv.setItem(i, new ItemStack(BLACK_STAINED_GLASS_PANE));
} else {
pInv.setItem(i - 45, new ItemStack(BLACK_STAINED_GLASS_PANE));
}
}
}
} else {
if (i < 54) {
inv.setItem(i, new ItemStack(GRAY_STAINED_GLASS_PANE));
} else {
pInv.setItem(i - 45, new ItemStack(GRAY_STAINED_GLASS_PANE));
}
}
}
}
If anyone can think of a solution to this, I would greatly appreciate it! Thanks for taking the time to read this post.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I am trying to create a simple TicTacToe game but I am having trouble having the program recognize a row of x's.
If you look at the following line of code:
public void run() {
setFont("Helvetica-40");
fillArray();
checkWinner();
run();
}
//fill array:
public void fillArray() {
for(int row = 0; row<3; row++) {
String fill = readLine("");
for(int col=0; col<3;col++) {
char xo = fill.charAt(row);
String xoString = Character.toString(xo);
ticTac[row][col] = xoString;
}
}
}
public boolean checkWinner() {
// array[row][col]
if (ticTac[0][0].equals("x") && ticTac[0][1].equals("x") && ticTac[0][2].equals("x")) {
println("Player X wins!");
return true;
} else
println("no x");
return false;
}
String[][] ticTac = new String[3][3];
}
I think you have a mistake, you have to change one of these two things :
1.
if (ticTac[0][0].equals("x") && ticTac[0][1].equals("x") && ticTac[0][2].equals("x"))
to
if( ticTac[0][0].equals("x") && ticTac[1][0].equals("x") && ticTac[2][0].equals("x"))
or
2.
char xo = fill.charAt(row);
to
char xo = fill.charAt(col);
just one of them, it depend on your design
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
class Que{
char q[];
int front , rear ;
Que(int size){
q = new char[size];
front = rear =0;
}
void push(char ch){
if(rear == q.length){
System.out.println("Que is Full");
}
else{
q[rear++]=ch;
System.out.println(ch + " Added");
}
}
void pop(){
if(front==rear){
System.out.println("Que is Empty");
}
else{
System.out.println(q[front] + " Is being popped ");
front++;
}
}
void disp(){
char temp = q[front];
for(int i = front;i<rear ; i++)
{
System.out.println(q[i]);
}
}
}
class Example{
public static void main(String args[])
throws java.io.IOException{
Que Sample1 = new Que(10);
int opt = 1;
char j,k;
while(opt!=0){
System.out.println("1-Add , 2 - Pop , 3 - Display");
j = (char) System.in.read();
if(j=='1'){
System.out.println("What to push ?");
k = (char)System.in.read();
Sample1.push(k);
}
else if(j=='2'){
Sample1.pop();
}
else if(j=='3'){
Sample1.disp();
}
else if(j=='4'){
opt = 0;
}
else{ System.out.println("Try Again");}
}
}
}
This is not working . When I compile and run it it show me the main menu and as soon as I press 1)ADD - it skips displaying 'Added' msg from the function .
What am I doing wrong?
When I press 1 (Add) it should ask me "what To Push " which it does, but then does not wait for my input and plays loop again .
So this is what displays --
1)ADD
2)Pop
3)Display
1
What to push ( takes no input)
Added (automatically displayed)
1)ADD
2)Pop
3)Display
What are you typing in your terminal ?
If you type more than one character for example 11 or even 1<Enter>, your second call to System.in.read() will immediatly return with this second character: 1 or <Enter>.
This question already has an answer here:
Loop doesn't see value changed by other thread without a print statement
(1 answer)
Closed 7 years ago.
I am writing a basic Tic-Tac-Toe Single player game using basic swing graphics. I completed the game, but there is a weird problem I am facing. At one place, I used a while loop with a SOP statement. If I omit this statement, program works differently and nothing happens (like some kind of infinite loop), and if I keep it, it works just fine. I don't know what's happening in the code. Please help.
Below is the source code which causing problem. Sorry for my amateur coding style.
import java.util.Random;
public class SinglePlayer implements Runnable{
public final int MINIMUM = -1000000;
private GameBoard game;
public SinglePlayer(){
game = new GameBoard("Single Player");
}
public static void main(String[] args){
SinglePlayer gameSingle = new SinglePlayer();
gameSingle.run();
}
public void run(){
boolean machinePlayed = true, userPlayed = false;
// Outer loop is to maintain re-match option of program
while(this.game.quitTwoPlayer == false){
// Inner loop is a single game b/w user and machine
while(this.game.GameQuitStatus() == false){
/* I kept two conditions to switch b/w machine and user mode
* of game and they just keep changing to simulate the game
* b/w machine and user.
*/
if(machinePlayed == false && userPlayed){
try {
MachineMove("O");
} catch (CloneNotSupportedException e) {
e.printStackTrace();
break;
}
this.game.ChangePlayerLabels();
machinePlayed = true;
userPlayed = false;
}
else if(machinePlayed && userPlayed == false){
int earlierCount = this.game.CountSteps();
/* THIS IS THE WHILE LOOP I AM TALKING ABOUT.
* If I omit the print statement inside the body of loop,
* program behaves differently, but when I keep it,
* it working just fine.
* */
while(earlierCount == this.game.CountSteps()){
System.out.println("Player User thinking");
}
this.game.ChangePlayerLabels();
machinePlayed = false;
userPlayed = true;
}
this.game.DeclareResult();
}
this.game.dispose();
}
}
public void MachineMove(String player) throws CloneNotSupportedException{
/* If board is empty, play at center of the board */
if(this.game.CountSteps() == 0){
this.game.MakeMove(1, 1);
}
/* If center is blank, play it there. Otherwise, pick a corner randomly */
else if(this.game.CountSteps() == 1){
if(this.game.IsEmpty(1, 1))
this.game.MakeMove(1, 1);
else{
Random randomNum = new Random();
int num = randomNum.nextInt(4);
if(num == 0)
this.game.MakeMove(0, 0);
else if(num == 1)
this.game.MakeMove(2, 0);
else if(num == 2)
this.game.MakeMove(0, 2);
else if(num == 3)
this.game.MakeMove(2, 2);
}
}
else{
/* If the next move is such that it should be taken, otherwise opponent will win */
String opponent = "";
if(this.game.GetCurrentPlayer().equals("O"))
opponent = "X";
else
opponent = "O";
for(int i = 0; i<3; i++){
for(int j = 0; j<3; j++){
if(this.game.IsEmpty(i,j)){
GameBoard tempGame = new GameBoard(this.game, "Single Player");
tempGame.MakePossibleMove(i, j, opponent);
if(tempGame.GameWinner().equals(opponent + " wins")){
this.game.MakeMove(i,j);
return;
}
}
}
}
/* If the next move is not such that if missed, game is lost, then play most optimal move towards winning */
Move tempMove = new Move(MINIMUM, 0, 0);
Move bestMove = new Move(MINIMUM, 0, 0);
for(int i = 0; i<3; i++){
for(int j = 0; j<3; j++){
if(this.game.IsEmpty(i,j)){
GameBoard tempGame = new GameBoard(this.game, "Single Player");
tempMove = MakeMoves(tempGame, i, j);
if(tempMove.score > bestMove.score){
bestMove.row = tempMove.row;
bestMove.col = tempMove.col;
bestMove.score = tempMove.score;
}
}
}
}
this.game.MakeMove(bestMove.row, bestMove.col);
}
}
public Move MakeMoves(GameBoard tempGame, int row, int col){
String player = tempGame.GetCurrentPlayer();
tempGame.MakeMove(row, col);
if(tempGame.GameWinner().equals("Match Draw")){
return new Move(0, row, col);
}
else if(tempGame.GameWinner().equals("X wins")){
if(player.equals("X")){
return new Move(1, row, col);
}
else{
return new Move(-1, row, col);
}
}
else if(tempGame.GameWinner().equals("O wins")){
if(player.equals("O")){
return new Move(1, row, col);
}
else{
return new Move(-1, row, col);
}
}
else{
Move bestMove = new Move(MINIMUM, 0, 0);
Move tempBestMove = new Move(0, 0, 0);
for(int i = 0; i<3; i++){
for(int j = 0; j<3; j++){
if(tempGame.IsEmpty(i,j)){
GameBoard newGame = new GameBoard(tempGame, "Single Player");
tempBestMove = MakeMoves(newGame, i, j);
if(tempBestMove.score > bestMove.score)
bestMove = tempBestMove;
}
}
}
return bestMove;
}
}
}
class Move{
public int score;
public int row;
public int col;
public Move(int score, int row, int col){
this.score = score;
this.row = row;
this.col = col;
}
}
Your loop is likely typing up your processor, and the SOP slows the loop enough to allow other processes to occur. But regardless and most importantly, you don't want to have this loop present in the first place. You state that you have a,
Tic-Tac-Toe Single player game using basic swing graphics
Remember that Swing is an event driven GUI library, so rather than loop as you would in a linear console program, let events occur, but respond to them based on the state of the program.
In other words, give your class several fields including a boolean variable that tells whose turn it is, such as boolean playersTurn, a boolean variable gameOver, ..., and change the state of these variables as the game is played, and base the games behavior depending on these states. For instance the game would ignore the player's input if it was not his turn.
I am trying to make a memory card game with 3 conditions:
when the player start the game the first click reveal the first card
if the player click in the second card there are 2 options
a. the second card have the same value as the first card. Hence keep both of them.
b. the second card have different value. Hence flip both back when click
I don't know what is the best way to deal with this problem. I thought of using if statement and making new method "state" which should have 3 outputs.
public void mousePressed() {
if(state==READY){
for (int i = 0; i < 6; i++) {
if(mouseX >= cards[i].x &&
mouseX <= cards[i].x+cards[i].WIDTH &&
mouseY >= cards[i].y &&
mouseY <= cards[i].y+cards[i].HEIGHT) {
cards[i].flip();
}
}
}
else if (state==FIRST_CHOSEN){
}
else{
}
}
I would break the problem into smaller problems.
Have several different methods that solve a little task that is required to tackle the larger end goal:
public void revealCard(Card card)
public boolean isMatch(Card card)
public void flipCardsBackOver(Card card1, Card card2);
And add an instance variable that stores the card that is already up. Once you have broken apart all of the separate challenges, then your problem becomes an easy one:
private Card CardOne; //instance variable
public void revealCard(Card myCard) {
myCard.flipCard(); //Whatever task you need to flip the card
if (CardOne = null) {
myCard = CardOne;
return;
}
if myCard.isMatch(CardOne)) {
//Do whatever you need to do when there is a match
}
else {
this.flipCardsBackOver(myCard, CardOne) //Flip all up cards over and set Card1
//to null
}
}