java assistance for looping the main code - java

Im trying to write a code and i used the do while loop in an atempt to loop my main code after the user types in y or yes (case insensitive) into an InputDialog.
here is the code, the only error is that a } needs to be put in after the do { but eve if i put it into the place I want, it doesn't work, also, it does not recognize thw while statement at the bottom, please help.
package tictactoemain;
import javax.swing.JOptionPane;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.LineBorder;
/**
* JFrame to hold TicTacToe board.
*/
public class TicTacToeFrame extends JFrame
{
**do {** //do starts here
private static final long serialVersionUID = 1L;
// Indicate whose turn it is
private char whoseTurn = 'X';
private boolean gameOver = false;
// Create cell grid using an Array
private Cell[][] cells = new Cell[3][3];
// Create a status label
JLabel jlblStatus = new JLabel("X's turn to play");
/**
* No-argument Constructor
* #return
*/
public TicTacToeFrame()
{
// Panel to hold cells
JPanel panel = new JPanel(new GridLayout(3, 3, 0, 0));
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
panel.add(cells[i][j] = new Cell());
panel.setBorder(new LineBorder(Color.black, 1));
jlblStatus.setBorder(new LineBorder(Color.black, 1));
add(panel, BorderLayout.CENTER);
add(jlblStatus, BorderLayout.SOUTH);
}
// Determine if it's a tie
/**
* Determine if game board is full.
* #return True, if game board is full. Otherwise, false.
*/
public boolean isFull()
{
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
if (cells[i][j].getToken() == ' ')
return false;
return true;
}
// Check to see if a player (Token) has won
/**
* Determines if a given token has won.
* #param token Token to test for winning
* #return True, if the token has won. Otherwise, false.
*/
public boolean isWon(char token)
{
// check rows
for (int i = 0; i < 3; i++)
if ((cells[i][0].getToken() == token)
&& (cells[i][1].getToken() == token)
&& (cells[i][2].getToken() == token))
{
return true;
}
// check columns
for (int j = 0; j < 3; j++)
if ((cells[0][j].getToken() == token)
&& (cells[1][j].getToken() == token)
&& (cells[2][j].getToken() == token))
{
return true;
}
// check diagonals
if ((cells[0][0].getToken() == token)
&& (cells[1][1].getToken() == token)
&& (cells[2][2].getToken() == token))
{
return true;
}
if ((cells[0][2].getToken() == token)
&& (cells[1][1].getToken() == token)
&& (cells[2][0].getToken() == token))
{
return true;
}
return false;
}
/**
* Defines a cell in a TicTacToe game board.
*/
public class Cell extends JPanel
{
/**
*
*/
private static final long serialVersionUID = 1L;
// token of this cell
private char token = ' ';
/**
* Constructor
*/
public Cell()
{
setBorder(new LineBorder(Color.black, 1));
addMouseListener(new MyMouseListener());
}
/**
* Gets the token of the cell.
* #return The token value of the cell.
*/
public char getToken()
{
return token;
}
/**
* Sets the token of the cell.
* #param c Character to use as token value.
*/
public void setToken(char c)
{
token = c;
repaint();
}
#Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
if (token == 'X')
{
g.drawLine(10, 10, getWidth() - 10, getHeight() - 10);
g.drawLine(getWidth() - 10, 10, 10, getHeight() - 10);
}
else if (token == 'O')
{
g.drawOval(10, 10, getWidth() - 20, getHeight() - 20);
}
}
// MouseListener to listen for a click to place a token
private class MyMouseListener extends MouseAdapter
{
private String playAgain;
private Object playYes;
private Object playNo;
#Override
public void mouseClicked(MouseEvent e)
{
if (gameOver)
return;
// if condition not met, the game is not over
if (token == ' ' && whoseTurn != ' ')
setToken(whoseTurn);
// Check game status
if (isWon(whoseTurn))
{
jlblStatus.setText("Congratulations " + whoseTurn + ", You Are Winnner! Game Over! Exit And Restart The Program To Play Again!" );
whoseTurn = ' ';
gameOver = true;
}
else if (isFull())
{
jlblStatus.setText("Tie game! Game over!");
whoseTurn = ' ';
gameOver = true;
}
else
{
whoseTurn = (whoseTurn == 'X') ? 'O' : 'X';
jlblStatus.setText(whoseTurn + "'s turn to play.");
}
// and ends here, while statement is below
{
// if the game is over, this will run
if (gameOver == true)
playAgain = JOptionPane.showInputDialog("Would you like to play again?");
// if statement that either restarts the game or closes it depending on the yes/y (cases are ignored) answer
while (playAgain.equalsIgnoreCase("y") | playAgain.equalsIgnoreCase("yes"))
{
playYes = ("Yes? Okay, have fun!");
JOptionPane.showMessageDialog( null, playYes );
}
}
}// End of Win condition checker
} // End class MyMouseListener
}
} // End class TicTacToeFrame

You could initialize all of your variables from a single method. This way you could initialize the game at the beginning of the program with it and if the player requests to play the game again you could call the same method thus bringing the program back to its original state.
private void init() {
whoseTurn = 'X';
gameOver = false;
jlblStatus = new JLabel("X's turn to play");
for(Cell[] ca : cells) {
for(Cell c : ca) {
c.setToken(' ');
}
}
}
My example might not include all variables but you could tweak it to suit your needs.
The do-while loop is not recognized because it is outside of a method.

Related

Chess Interface with Piece IMG implementation

I am currently making a Chess program as a project for my data structures class. We pretty much have most of the code complete but for some reason, I cannot figure out how to place the pieces onto any help would be Greatly Appreciated.
we are using JAVA and Swing
MAIN GOAL:
get piece IMG to go onto the board:
public abstract class UserInterface {
//FIELDS
protected Board board;
//The board that the UI will be used to interact with
//CONSTRUCTORS
public UserInterface(Board board) {
//Constructor for UserInterface implementers
this.board = board;
}
public UserInterface() {
}
//OTHER
public abstract Move promptMove();
public abstract PieceType promptPromotion();
public abstract void updateBoard();
public abstract void playGame(Interactable whiteUser, Interactable blackUser);
}
class CommandInterface extends UserInterface {
private GraphicInterface gui = null;
//CONSTRUCTORS
public CommandInterface(Board board) {
//Main constructor for the CommandInterface
super(board);
gui = new GraphicInterface(board, null);
gui.initializeGui();
}
//OTHER
public void playGame(Interactable whiteUser, Interactable blackUser) {
//Starts a game using the UI and the board.
//[TEST CODE] Probably will clean this up later
board.setUsers(whiteUser, blackUser);
updateBoard();
Scanner input = new Scanner(System.in);
boolean gameOver = false;
while(!gameOver) {
boolean illegalMove;
do {
try {
// System.out.println("Press enter to move");
// String s = input.nextLine();
board.doMove(board.getCurrentUser().getMove());
illegalMove = false;
} catch(IllegalArgumentException e) {
System.out.println(e.getMessage());
illegalMove = true;
}
if(board.getState() == BoardState.CHECKMATE) {
System.out.println("\n" + board.getTurn().toString() + " is now checkmated. Game over!");
gameOver = true;
illegalMove = false;
} else if(board.getState() == BoardState.CHECK) {
System.out.println("\n" + board.getTurn().toString() + " has been put in check!");
illegalMove = false;
} else if(board.getState() == BoardState.STALEMATE) {
System.out.println("\n" + board.getTurn().toString() + " is now stalemated. Game over!");
gameOver = true;
illegalMove = false;
}
} while(illegalMove);
updateBoard();
}
}
public Move promptMove() {
//Takes user input for a move and returns the Move object
Scanner input = new Scanner(System.in);
String move;
boolean again;
do {
System.out.print("Enter your move (? for help): ");
move = input.nextLine();
if(move.equals("?")) {
//If the user asks for help
System.out.printf("%nHELP: To move, you must type a move in the following format:"
+ "%n<STARTING TILE> <ENDING TILE>"
+ "%nThe starting tile is the tile of the piece you wish to move."
+ "%nThe ending tile is the tile you wish to move your piece to."
+ "%nEach tile is notated with \"<COLUMN><RANK>\", example: \"e5\""
+ "%n%nFull example move: \"a5 g5\"%n");
again = true;
} else if(move.equalsIgnoreCase("CASTLE")) {
System.out.print("Enter the movement of the King: ");
move = input.nextLine();
return new Move(board, move, true);
} else again = false;
} while(again);
//Reprompt if the user asks for help
return new Move(board, move);
//Returns a Move object made from the SMN string
}
public PieceType promptPromotion() {
Scanner input = new Scanner(System.in);
System.out.print("Pawn has promotion available.\nWhich piece to promote to? ");
while(true) {
String type = input.nextLine();
PieceType promotion = PieceType.NONE;
if (type.equalsIgnoreCase("PAWN")) promotion = PieceType.PAWN;
else if (type.equalsIgnoreCase("ROOK")) promotion = PieceType.ROOK;
else if (type.equalsIgnoreCase("KNIGHT")) promotion = PieceType.KNIGHT;
else if (type.equalsIgnoreCase("BISHOP")) promotion = PieceType.BISHOP;
else if (type.equalsIgnoreCase("QUEEN")) promotion = PieceType.QUEEN;
else if (type.equalsIgnoreCase("KING")) promotion = PieceType.KING;
else if (type.equalsIgnoreCase("EARL")) promotion = PieceType.EARL;
else if (type.equalsIgnoreCase("MONK")) promotion = PieceType.MONK;
if(promotion == PieceType.NONE) {
System.out.print("\nInvalid type, please try again: ");
continue;
}
return promotion;
}
}
public void updateBoard() {
//Prints the board in basic ASCII format.
gui.updateBoard();
drawCaptured(Color.WHITE);
System.out.println();
//Adds a line before the board starts printing
int squaresPrinted = 0;
//Keeps track of the total number of squares that has been printed
for(int y = board.getZeroSize(); y >= 0; y--) {
//Loop through y-values from top to bottom
if(y != board.getZeroSize()) System.out.println();
//If not on the first iteration of y-loop, go down a line (avoids leading line break)
System.out.print((y + 1) + " ");
//Print the rank number
for(int x = 0; x <= board.getZeroSize(); x++) {
//Loop through x-values from left to right
if(board.pieceAt(x, y) != null) {
//If there is a piece on the tile
if(squaresPrinted % 2 == 0) System.out.print("[" + board.pieceAt(x, y).getString() + "]");
//If squaresPrinted is even, print "[<pString>]"
else System.out.print("(" + board.pieceAt(x, y).getString() + ")");
//If squaresPrinted is odd, print "(<pString>)"
} else {
//If there is no piece on the tile
if(squaresPrinted % 2 == 0) System.out.print("[ ]");
//If squaresPrinted is even, print "[ ]"
else System.out.print("( )");
//If squaresPrinted is odd, print "( )"
}
squaresPrinted++;
//Increment squaresPrinted for each iteration of the x-loop
}
squaresPrinted++;
//Increment squaresPrinted for each iteration of the y-loop
}
System.out.println();
System.out.print(" ");
//Print an extra line and the leading whitespace for the column identifiers
for(int i = 0; i <= board.getZeroSize(); i++) {
//Repeat <size> times
System.out.print(" " + (char) (i + 97));
//Print the column identifier chars by casting from int
}
drawCaptured(Color.BLACK);
//Prints all black pieces that have been captured
System.out.println();
}
private void drawCaptured(Color color) {
//Prints captured pieces of either color.
System.out.println();
//Prints a blank line
ArrayList<String> capturedPieces = board.getCaptured(color);
if(capturedPieces == null) return;
for(String p : capturedPieces) {
System.out.print(p + " ");
//TODO: Remove trailing whitespace
}
}
}
#SuppressWarnings("ALL")
class GraphicInterface extends UserInterface implements MouseListener {
private JButton[][] chessBoardSquares = null;
private JButton buttonsAndLabels = new JButton();
private JLabel message = null;
private String columnNames = null;
private Board board = null;
private JFrame frame;
public ImageIcon BK;
public ImageIcon WP;
public ImageIcon WR;
public ImageIcon WN;
public ImageIcon WB;
public ImageIcon WQ;
public ImageIcon WK;
public ImageIcon BP;
public ImageIcon BR;
public ImageIcon BN;
public ImageIcon BB;
public ImageIcon BQ;
public ImageIcon blank;
private Object ImageIcon;
public GraphicInterface(Board board, GraphicInterface frame) {
super(board);
// super(board);
this.board = board;
try {
//remove later
String path = "src/chuss/icons/";
new ImageIcon(javax.imageio.ImageIO.read(new File(path + "BK.gif")));
new ImageIcon(javax.imageio.ImageIO.read(new File(path + "WP.gif")));
new ImageIcon(javax.imageio.ImageIO.read(new File(path + "WR.gif")));
WN = new ImageIcon(javax.imageio.ImageIO.read(new File(path + "WN.gif")));
WB = new ImageIcon(javax.imageio.ImageIO.read(new File(path + "WB.gif")));
WQ = new ImageIcon(javax.imageio.ImageIO.read(new File(path + "WQ.gif")));
WK = new ImageIcon(javax.imageio.ImageIO.read(new File(path + "WK.gif")));
BP = new ImageIcon(javax.imageio.ImageIO.read(new File(path + "BP.gif")));
BR = new ImageIcon(javax.imageio.ImageIO.read(new File(path + "BR.gif")));
BN = new ImageIcon(javax.imageio.ImageIO.read(new File(path + "BN.gif")));
BB = new ImageIcon(javax.imageio.ImageIO.read(new File(path + "BB.gif")));
BQ = new ImageIcon(javax.imageio.ImageIO.read(new File(path + "BQ.gif")));
blank = new ImageIcon(javax.imageio.ImageIO.read(new File(path + "blank.png")));
buttonsAndLabels.addMouseListener((MouseListener) this);
buttonsAndLabels.add(buttonsAndLabels);
buttonsAndLabels.setSize(600, 600);
//buttonsAndLabels.getContentPane().setPreferredSize(new Dimension(800, 700));
} catch(IOException e) {
e.getCause();
e.printStackTrace();
}
buttonsAndLabels = new JButton((Action) new BorderLayout(3, 3));
chessBoardSquares = new JButton[8][8];
message = new JLabel("Chuss Champ is ready to play!");
columnNames = "ABCDEFGH";
initializeGui();
}
public GraphicInterface(JButton buttonsAndLabels) {
super();
}
public GraphicInterface(Board board) {
}
#Override
public Move promptMove() {
return null;
}
#Override
public PieceType promptPromotion() {
return null;
}
public final JButton initializeGui() {
// set up the main GUI
assert false;
buttonsAndLabels.setBorder(new EmptyBorder(5, 5, 5, 5));
JToolBar tools = new JToolBar();
tools.setFloatable(false);
buttonsAndLabels.add(tools, BorderLayout.PAGE_START);
tools.add(new JButton("New")); // TODO - add functionality!
tools.add(new JButton("Save")); // TODO - add functionality!
tools.add(new JButton("Restore")); // TODO - add functionality!
tools.addSeparator();
tools.add(new JButton("Resign")); // TODO - add functionality!
tools.addSeparator();
tools.add(message);
buttonsAndLabels.add(new JLabel("?"), BorderLayout.LINE_START);
// create the chess board squares
buttonsAndLabels = new JButton((Action) new GridLayout(0, 9));
buttonsAndLabels.setBorder(new LineBorder(java.awt.Color.BLACK));
buttonsAndLabels.add((Component) ImageIcon);
updateBoard();
Runnable r = () -> {
JFrame f = new JFrame("CHUSS");
f.add(getGui());
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
// ensures the frame is the minimum size it needs to be
// in order display the components within it
f.pack();
// ensures the minimum size is enforced.
f.setMinimumSize(f.getSize());
f.setVisible(true);
};
SwingUtilities.invokeLater(r);
assert false;
return null;
}
public void updateBoard() {
//Prints the board in graphical format.
buttonsAndLabels.removeAll();
Insets buttonMargin = new Insets(0,0,0,0);
for (int ii = 7; ii >= 0; ii--) {
for (int jj = 0; jj < chessBoardSquares.length; jj++) {
JButton b = new JButton();
b.setMargin(buttonMargin);
// our chess pieces are 64x64 px in size, so we'll
// 'fill this in' using a transparent icon..
Piece p = board.pieceAt(jj, ii);
ImageIcon icon = new ImageIcon();
if (p instanceof Pawn && p.getColor() == Color.WHITE) icon = WP;
else if (p instanceof Rook && p.getColor() == Color.WHITE) icon = WR;
else if (p instanceof Knight && p.getColor() == Color.WHITE) icon = WN;
else if (p instanceof Bishop && p.getColor() == Color.WHITE) icon = WB;
else if (p instanceof Queen && p.getColor() == Color.WHITE) icon = WQ;
else if (p instanceof King && p.getColor() == Color.WHITE) icon = WK;
else if (p instanceof Pawn && p.getColor() == Color.BLACK) icon = BP;
else if (p instanceof Rook && p.getColor() == Color.BLACK) icon = BR;
else if (p instanceof Knight && p.getColor() == Color.BLACK) icon = BN;
else if (p instanceof Bishop && p.getColor() == Color.BLACK) icon = BB;
else if (p instanceof Queen && p.getColor() == Color.BLACK) icon = BQ;
else if (p instanceof King && p.getColor() == Color.BLACK) icon = BK;
else if (p == null) icon = blank;
b.setIcon(icon);
if ((jj % 2 == 1 && ii % 2 == 1)
//) {
|| (jj % 2 == 0 && ii % 2 == 0)) {
b.setBackground(java.awt.Color.WHITE);
} else {
b.setBackground(java.awt.Color.GRAY);
}
chessBoardSquares[jj][ii] = b;
buttonsAndLabels.add(chessBoardSquares[jj][ii]);
}
}
initializeGui();
// fill the top row
for (int ii = 0; ii <= 7; ii++) {
buttonsAndLabels.add(
new JLabel(columnNames.substring(ii, ii + 1),
SwingConstants.CENTER));
}
// fill the black non-pawn piece row
for (int ii = 7; ii >= 0; ii--) {
for (int jj = 0; jj < 8; jj++) {
if (jj == 0) {
buttonsAndLabels.add(new JLabel("" + (ii + 1),
SwingConstants.CENTER));
}
buttonsAndLabels.add(chessBoardSquares[jj][ii]);
}
}
buttonsAndLabels.updateUI();
}
#Override
public void playGame(Interactable whiteUser, Interactable blackUser) {
GraphicInterface gui = new GraphicInterface(buttonsAndLabels);
gui.getChessBoard();
}
public JComponent getChessBoard() {
return buttonsAndLabels;
}
public JComponent getGui() {
return buttonsAndLabels;
}
#Override
public void mouseClicked(MouseEvent e) {
}
#Override
public void mousePressed(MouseEvent e) {
}
#Override
public void mouseReleased(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}

Cant run the code, intelij run arrow is 'grey' [duplicate]

This question already has answers here:
Auto errors detection in IntelliJ IDEA
(8 answers)
Closed 5 years ago.
enter image description here import java.util.Scanner;
public class EnglishCheckers {
// Global constants
public static final int RED = 1;
public static final int BLUE = -1;
public static final int EMPTY = 0;
public static final int SIZE = 8;
// You can ignore these constants
public static final int MARK = 3;
public static EnglishCheckersGUI grid;
public static Scanner getPlayerFullMoveScanner = null;
public static Scanner getStrategyScanner = null;
public static final int RANDOM = 1;
public static final int DEFENSIVE = 2;
public static final int SIDES = 3;
public static final int CUSTOM = 4;
public static void main(String[] args) {
// ******** Don't delete *********
// CREATE THE GRAPHICAL GRID
grid = new EnglishCheckersGUI(SIZE);
// *******************************
//showBoard(example);
//printMatrix(example);
//interactivePlay();
//twoPlayers();
/* ******** Don't delete ********* */
if (getPlayerFullMoveScanner != null){
getPlayerFullMoveScanner.close();
}
if (getStrategyScanner != null){
getStrategyScanner.close();
}
/* ******************************* */
}
public static int[][] createBoard() {
int[][] board = null;
board=new int[8][8]; // defines the new length of the array
for (int j=0; j<8; j=j+1)
{
for (int m=0; m<8; m=m+1) // these two "for" loops will set the value of each square of the board according to the instructions regarding it's location.
{
if (j==0|j==2)
{
if (m%2==0)
board[j][m]=1;
else
board[j][m]=0;
}
if (j==1)
{
if (m%2!=0)
board[j][m]=1;
else
board[j][m]=0;
}
if (j>2&j<5)
board[j][m]=0;
if (j==5|j==7)
{
if (m%2!=0)
board[j][m]=-1;
else
board[j][m]=0;
}
if (j==6)
{
if (m%2==0)
board[j][m]=-1;
else
board[j][m]=0;
}
}
}
return board;
}
public static int howManyDiscs (int[][] board, int player){ // this function will return the number of discs a player has on the board
int positive=0;
int negative=0;
for (int i=0; i<8; i=i+1)
{
for (int j=0; j<8; j=j+1)
{
if (board[i][j]>0) positive=positive+1;
if (board[i][j]<0) negative=negative+1;
}
}
if (player>0) return positive;
else return negative;
}
public static int[][] playerDiscs(int[][] board, int player) {
int[][] positions = null;
if (howManyDiscs(board,player)>0)
{
positions=new int[howManyDiscs(board,player)][2]; // defines the new length of the array
int line=0;
for (int i=0; i<8; i=i+1)
{
for (int j=0; j<8; j=j+1)
{
if (player>0&&board[i][j]>0) // will update the array if the player is 1
{
positions[line][0]=i;
positions[line][1]=j;
line=line+1;
}
if (player<0&&board[i][j]<0) // will update the array if the player is (-1)
{
positions[line][0]=i;
positions[line][1]=j;
line=line+1;
}
}
}
}
return positions;
}
public static boolean isBasicMoveValid(int[][] board, int player, int fromRow, int fromCol, int toRow, int toCol) {
boolean ans = false;
if (fromRow>=0&&fromRow<8&&fromCol>=0&&fromCol<8&&toRow>=0&&toRow<8&&toCol>=0&&toCol<8) // makes sure the coordinates are legal
{
if (board[fromRow][fromCol]==player|board[fromRow][fromCol]==player*2) // checks if a disc of the player exists in the origin square
{
if(board[toRow][toCol]==0) // checks if the destination square is legal
{
if (toCol==fromCol+1||toCol==fromCol-1) // checks if the destination column is legal
{
if (toRow==fromRow+1&&player!=-1) // makes sure the move is legal for a player that isn't (-1)
{
ans=true;
}
if (toRow==fromRow-1&&player!=1) // makes sure the move is legal for a player that isn't 1
{
ans=true;
}
}
}
}
}
return ans;
}
public static int[][] getAllBasicMoves(int[][] board, int player) {
int[][] moves = null;
int line=0;
for (int i=0; i<8; i=i+1)
{
for (int j=0; j<8; j=j+1) // these 2 "for" loops will add 1 to the counter "line" for each legal move a square has
{
if (isBasicMoveValid(board,player,i,j,i+1,j+1)) line=line+1;
if (isBasicMoveValid(board,player,i,j,i+1,j-1)) line=line+1;
if (isBasicMoveValid(board,player,i,j,i-1,j+1)) line=line+1;
if (isBasicMoveValid(board,player,i,j,i-1,j-1)) line=line+1;
}
}
moves=new int[line][4]; // creating the length of the output array according to the amount of possibilities found
line=0;
for (int i=0; i<8; i=i+1)
{
for (int j=0; j<8; j=j+1) // the if's below will insert every move that exists for each square to the array
{
if (isBasicMoveValid(board,player,i,j,i+1,j+1))
{
moves[line][0]=i;
moves[line][1]=j;
moves[line][2]=i+1;
moves[line][3]=j+1;
line=line+1;
}
if (isBasicMoveValid(board,player,i,j,i+1,j-1))
{
moves[line][0]=i;
moves[line][1]=j;
moves[line][2]=i+1;
moves[line][3]=j-1;
line=line+1;
}
if (isBasicMoveValid(board,player,i,j,i-1,j+1))
{
moves[line][0]=i;
moves[line][1]=j;
moves[line][2]=i-1;
moves[line][3]=j+1;
line=line+1;
}
if (isBasicMoveValid(board,player,i,j,i-1,j-1))
{
moves[line][0]=i;
moves[line][1]=j;
moves[line][2]=i-1;
moves[line][3]=j-1;
line=line+1;
}
}
}
return moves;
}
public static boolean isBasicJumpValid(int[][] board, int player, int fromRow, int fromCol, int toRow, int toCol) {
boolean ans = false;
if (fromRow>=0&&fromRow<8&&fromCol>=0&&fromCol<8&&toRow>=0&&toRow<8&&toCol>=0&&toCol<8) // makes sure the coordinates are legal
{
if (board[fromRow][fromCol]==player|board[fromRow][fromCol]==player*2) // checks if a disc of the player exists in the origin square
{
if(board[toRow][toCol]==0) // checks if the destination square is legal
{
if (toRow==fromRow+2)
{
if (toCol==fromCol+2)
{
if (player==1|player==2)
{
if (board[fromRow+1][fromCol+1]<0)
ans=true;
}
if (player==-2)
{
if (board[fromRow+1][fromCol+1]>0)
ans=true;
}
}
if (toCol==fromCol-2)
{
if (player==1|player==2)
{
if (board[fromRow+1][fromCol-1]<0)
ans=true;
}
if (player==-2)
{
if (board[fromRow+1][fromCol-1]>0)
ans=true;
}
}
}
if (toRow==fromRow-2)
{
if (toCol==fromCol+2)
{
if (player==-1|player==-2)
{
if (board[fromRow-1][fromCol+1]>0)
ans=true;
}
if (player==2)
{
if (board[fromRow-1][fromCol+1]<0)
ans=true;
}
}
if (toCol==fromCol-2)
{
if (player==-1|player==-2)
{
if (board[fromRow-1][fromCol-1]>0)
ans=true;
}
if (player==2)
{
if (board[fromRow-1][fromCol-1]<0)
ans=true;
}
}
}
}
}
}
return ans;
}
public static int [][] getRestrictedBasicJumps(int[][] board, int player, int row, int col) {
int[][] moves = null;
int line=0;
for (int i=row-2; i<=row+2; i=i+2)
{
for (int j=col-2; j<=col+2; j=j+2) // these 2 "for" loops will add 1 to the counter "line" for each legal move a square has
{
if (isBasicJumpValid(board,player,row,col,i,j)) line=line+1;
}
}
moves=new int[line][4]; // creating the length of the output array according to the amount of possibilities found
line=0;
for (int i=row-2; i<=row+2; i=i+2)
{
for (int j=col-2; j<=col+2; j=j+2)
{
if (isBasicJumpValid(board,player,row,col,i,j)) // will insert every possible jump to the array
{
moves[line][0]=row;
moves[line][1]=col;
moves[line][2]=i;
moves[line][3]=j;
line=line+1;
}
}
}
return moves;
}
public static int[][] getAllBasicJumps(int[][] board, int player) {
int [][] moves = null;
int [][] discs = playerDiscs(board,player); // this array holds a list of the discs the player has on the board currently
int counter=0;
for (int i=0; i<discs.length; i=i+1) // will add each disc's amount of possible moves to the counter
counter=counter+getRestrictedBasicJumps(board,player,discs[i][0],discs[i][1]).length;
moves=new int[counter][4]; // defining the array's size according to the sum of all discs possible jumps
int line=0;
for (int a=0; a<discs.length; a=a+1)
{
int [][] jumps = getRestrictedBasicJumps(board,player,discs[a][0],discs[a][1]); // creates the array "jumps" that holds the possible jumps for the current "for" disc
for (int i=0; i<jumps.length; i=i+1) // will insert each line of the jumps array to the moves array
{
moves[line][0]=jumps[i][0];
moves[line][1]=jumps[i][1];
moves[line][2]=jumps[i][2];
moves[line][3]=jumps[i][3];
line=line+1;
}
}
return moves;
}
public static boolean canJump(int[][] board, int player) {
boolean ans = false;
if (getAllBasicJumps(board,player).length>0) ans=true;
return ans;
}
public static boolean isMoveValid(int[][] board, int player, int fromRow, int fromCol, int toRow, int toCol) {
boolean ans = false;
if (isBasicJumpValid(board,player,fromRow,fromCol,toRow,toCol))
ans=true;
else
if (isBasicMoveValid (board,player,fromRow,fromCol,toRow,toCol))
ans=true;
return ans;
}
public static boolean hasValidMoves(int[][] board, int player) {
boolean ans = false;
if (getAllBasicMoves(board,player).length>0) ans=true;
if (canJump(board,player)) ans=true;
return ans;
}
public static int[][] playMove(int[][] board, int player, int fromRow, int fromCol, int toRow, int toCol) {
if (isBasicJumpValid(board,player,fromRow,fromCol,toRow,toCol)) // in case it's a jump- will replace the eaten player with 0
{
if (fromRow>toRow)
{
if (fromCol>toCol) board[fromRow-1][fromCol-1]=0;
else board[fromRow-1][fromCol+1]=0;
}
else
{
if (fromCol>toCol) board[fromRow+1][fromCol-1]=0;
else board[fromRow+1][fromCol+1]=0;
}
}
if (player==1&toRow==7)
{
board[toRow][toCol]=2;
board[fromRow][fromCol]=0;
}
else
{
if (player==-1&toRow==0)
{
board[toRow][toCol]=-2;
board[fromRow][fromCol]=0;
}
else
{
board[toRow][toCol]=player;
board[fromRow][fromCol]=0;
}
}
return board;
}
public static boolean gameOver(int[][] board, int player) {
boolean ans = false;
if (!hasValidMoves(board,player)) ans=true;
if (playerDiscs(board,1)==null | playerDiscs(board,-1)==null) ans=true;
return ans;
}
public static int findTheLeader(int[][] board) {
int ans = 0;
int player1=0, player2=0;
for (int i=0; i<8; i=i+1)
{
for (int j=0; j<8; j=j+1)
{
if (board[i][j]==1) player1=player1+1;
if (board[i][j]==2) player1=player1+2;
if (board[i][j]==-1) player1=player2+1;
if (board[i][j]==-2) player1=player2+2;
}
}
if (player1>player2)
ans=1;
else
if (player2>player1)
ans=-1;
else
ans=0;
return ans;
}
public static int[][] randomPlayer(int[][] board, int player) {
if (hasValidMoves(board,player))
{
if (getAllBasicMoves(board,player).length>0 && isMoveValid(board,player,getAllBasicMoves(board,player)[0][0],getAllBasicMoves(board,player)[0][1],getAllBasicMoves(board,player)[0][2],getAllBasicMoves(board,player)[0][3]))
board=playMove(board,player,getAllBasicMoves(board,player)[0][0],getAllBasicMoves(board,player)[0][1],getAllBasicMoves(board,player)[0][2],getAllBasicMoves(board,player)[0][3]);
else
if (getAllBasicJumps(board,player).length>0 && isMoveValid(board,player,getAllBasicJumps(board,player)[0][0],getAllBasicJumps(board,player)[0][1],getAllBasicJumps(board,player)[0][2],getAllBasicJumps(board,player)[0][3]))
board=playMove(board,player,getAllBasicJumps(board,player)[0][0],getAllBasicJumps(board,player)[0][1],getAllBasicJumps(board,player)[0][2],getAllBasicJumps(board,player)[0][3]);
}
return board;
}
public static int[][] defensivePlayer(int[][] board, int player) {
if (hasValidMoves(board,player))
{
if (canJump(board,player))
board=playMove(board,player,getAllBasicJumps(board,player)[0][0],getAllBasicJumps(board,player)[0][1],getAllBasicJumps(board,player)[0][2],getAllBasicJumps(board,player)[0][3]);
else
{
boolean goodMove=false;
int i=0;
int [][] arr=board;
while (i<getAllBasicMoves(board,player).length && !goodMove)
{
arr=playMove(board,player,getAllBasicMoves(board,player)[i][0],getAllBasicMoves(board,player)[i][1],getAllBasicMoves(board,player)[i][2],getAllBasicMoves(board,player)[i][3]);
if (!canJump(arr,-player))
goodMove=true;
i=i+1;
}
board=arr;
}
}
return board;
}
public static int[][] sidesPlayer(int[][] board, int player) {
if (hasValidMoves(board,player))
{
if (canJump(board,player))
board=playMove(board,player,getAllBasicJumps(board,player)[0][0],getAllBasicJumps(board,player)[0][1],getAllBasicJumps(board,player)[0][2],getAllBasicJumps(board,player)[0][3]);
else
{
if (getAllBasicMoves(board,player).length>1)
{
int bestMove=0, minHefresh=7;
for (int i=1; i<getAllBasicMoves(board,player).length; i=i+1)
{
if (Math.abs(0-getAllBasicMoves(board,player)[i][3])<minHefresh)
{
bestMove=i;
minHefresh=Math.abs(0-getAllBasicMoves(board,player)[i][3]);
}
if (Math.abs(0-getAllBasicMoves(board,player)[i-1][3])<minHefresh)
{
bestMove=i-1;
minHefresh=Math.abs(0-getAllBasicMoves(board,player)[i-1][3]);
}
if (Math.abs(7-getAllBasicMoves(board,player)[i][3])<minHefresh)
{
bestMove=i;
minHefresh=Math.abs(7-getAllBasicMoves(board,player)[i][3]);
}
if (Math.abs(7-getAllBasicMoves(board,player)[i-1][3])<minHefresh)
{
bestMove=i-1;
minHefresh=Math.abs(7-getAllBasicMoves(board,player)[i-1][3]);
}
}
board=playMove(board,player,getAllBasicMoves(board,player)[bestMove][0],getAllBasicMoves(board,player)[bestMove][1],getAllBasicMoves(board,player)[bestMove][2],getAllBasicMoves(board,player)[bestMove][3]);
}
else
board=playMove(board,player,getAllBasicMoves(board,player)[0][0],getAllBasicMoves(board,player)[0][1],getAllBasicMoves(board,player)[0][2],getAllBasicMoves(board,player)[0][3]);
}
}
return board;
}
//******************************************************************************//
/* ---------------------------------------------------------- *
* Play an interactive game between the computer and you *
* ---------------------------------------------------------- */
public static void interactivePlay() {
int[][] board = createBoard();
showBoard(board);
System.out.println("Welcome to the interactive Checkers Game !");
int strategy = getStrategyChoice();
System.out.println("You are the first player (RED discs)");
boolean oppGameOver = false;
while (!gameOver(board, RED) && !oppGameOver) {
board = getPlayerFullMove(board, RED);
oppGameOver = gameOver(board, BLUE);
if (!oppGameOver) {
EnglishCheckersGUI.sleep(200);
board = getStrategyFullMove(board, BLUE, strategy);
}
}
int winner = 0;
if (playerDiscs(board, RED).length == 0 | playerDiscs(board, BLUE).length == 0){
winner = findTheLeader(board);
}
if (winner == RED) {
System.out.println();
System.out.println("\t *************************");
System.out.println("\t * You are the winner !! *");
System.out.println("\t *************************");
}
else if (winner == BLUE) {
System.out.println("\n======= You lost :( =======");
}
else
System.out.println("\n======= DRAW =======");
}
/* --------------------------------------------------------- *
* A game between two players *
* --------------------------------------------------------- */
public static void twoPlayers() {
int[][] board = createBoard();
showBoard(board);
System.out.println("Welcome to the 2-player Checkers Game !");
boolean oppGameOver = false;
while (!gameOver(board, RED) & !oppGameOver) {
System.out.println("\nRED's turn");
board = getPlayerFullMove(board, RED);
oppGameOver = gameOver(board, BLUE);
if (!oppGameOver) {
System.out.println("\nBLUE's turn");
board = getPlayerFullMove(board, BLUE);
}
}
int winner = 0;
if (playerDiscs(board, RED).length == 0 | playerDiscs(board, BLUE).length == 0)
winner = findTheLeader(board);
System.out.println();
System.out.println("\t ************************************");
if (winner == RED)
System.out.println("\t * The red player is the winner !! *");
else if (winner == BLUE)
System.out.println("\t * The blue player is the winner !! *");
else
System.out.println("\t * DRAW !! *");
System.out.println("\t ************************************");
}
/* --------------------------------------------------------- *
* Get a complete (possibly a sequence of jumps) move *
* from a human player. *
* --------------------------------------------------------- */
public static int[][] getPlayerFullMove(int[][] board, int player) {
// Get first move/jump
int fromRow = -1, fromCol = -1, toRow = -1, toCol = -1;
boolean jumpingMove = canJump(board, player);
boolean badMove = true;
getPlayerFullMoveScanner = new Scanner(System.in);//I've modified it
while (badMove) {
if (player == 1){
System.out.println("Red, Please play:");
} else {
System.out.println("Blue, Please play:");
}
fromRow = getPlayerFullMoveScanner.nextInt();
fromCol = getPlayerFullMoveScanner.nextInt();
int[][] moves = jumpingMove ? getAllBasicJumps(board, player) : getAllBasicMoves(board, player);
markPossibleMoves(board, moves, fromRow, fromCol, MARK);
toRow = getPlayerFullMoveScanner.nextInt();
toCol = getPlayerFullMoveScanner.nextInt();
markPossibleMoves(board, moves, fromRow, fromCol, EMPTY);
badMove = !isMoveValid(board, player, fromRow, fromCol, toRow, toCol);
if (badMove)
System.out.println("\nThis is an illegal move");
}
// Apply move/jump
board = playMove(board, player, fromRow, fromCol, toRow, toCol);
showBoard(board);
// Get extra jumps
if (jumpingMove) {
boolean longMove = (getRestrictedBasicJumps(board, player, toRow, toCol).length > 0);
while (longMove) {
fromRow = toRow;
fromCol = toCol;
int[][] moves = getRestrictedBasicJumps(board, player, fromRow, fromCol);
boolean badExtraMove = true;
while (badExtraMove) {
markPossibleMoves(board, moves, fromRow, fromCol, MARK);
System.out.println("Continue jump:");
toRow = getPlayerFullMoveScanner.nextInt();
toCol = getPlayerFullMoveScanner.nextInt();
markPossibleMoves(board, moves, fromRow, fromCol, EMPTY);
badExtraMove = !isMoveValid(board, player, fromRow, fromCol, toRow, toCol);
if (badExtraMove)
System.out.println("\nThis is an illegal jump destination :(");
}
// Apply extra jump
board = playMove(board, player, fromRow, fromCol, toRow, toCol);
showBoard(board);
longMove = (getRestrictedBasicJumps(board, player, toRow, toCol).length > 0);
}
}
return board;
}
/* --------------------------------------------------------- *
* Get a complete (possibly a sequence of jumps) move *
* from a strategy. *
* --------------------------------------------------------- */
public static int[][] getStrategyFullMove(int[][] board, int player, int strategy) {
if (strategy == RANDOM)
board = randomPlayer(board, player);
else if (strategy == DEFENSIVE)
board = defensivePlayer(board, player);
else if (strategy == SIDES)
board = sidesPlayer(board, player);
showBoard(board);
return board;
}
/* --------------------------------------------------------- *
* Get a strategy choice before the game. *
* --------------------------------------------------------- */
public static int getStrategyChoice() {
int strategy = -1;
getStrategyScanner = new Scanner(System.in);
System.out.println("Choose the strategy of your opponent:" +
"\n\t(" + RANDOM + ") - Random player" +
"\n\t(" + DEFENSIVE + ") - Defensive player" +
"\n\t(" + SIDES + ") - To-the-Sides player player");
while (strategy != RANDOM & strategy != DEFENSIVE
& strategy != SIDES) {
strategy=getStrategyScanner.nextInt();
}
return strategy;
}
/* --------------------------------------- *
* Print the possible moves *
* --------------------------------------- */
public static void printMoves(int[][] possibleMoves) {
for (int i = 0; i < 4; i = i+1) {
for (int j = 0; j < possibleMoves.length; j = j+1)
System.out.print(" " + possibleMoves[j][i]);
System.out.println();
}
}
/* --------------------------------------- *
* Mark/unmark the possible moves *
* --------------------------------------- */
public static void markPossibleMoves(int[][] board, int[][] moves, int fromRow, int fromColumn, int value) {
for (int i = 0; i < moves.length; i = i+1)
if (moves[i][0] == fromRow & moves[i][1] == fromColumn)
board[moves[i][2]][moves[i][3]] = value;
showBoard(board);
}
/* --------------------------------------------------------------------------- *
* Shows the board in a graphic window *
* you can use it without understanding how it works. *
* --------------------------------------------------------------------------- */
public static void showBoard(int[][] board) {
grid.showBoard(board);
}
/* --------------------------------------------------------------------------- *
* Print the board *
* you can use it without understanding how it works. *
* --------------------------------------------------------------------------- */
public static void printMatrix(int[][] matrix){
for (int i = matrix.length-1; i >= 0; i = i-1){
for (int j = 0; j < matrix.length; j = j+1){
System.out.format("%4d", matrix[i][j]);
}
System.out.println();
}
}
}
hi. just started coding for , installed ide intellij but i cant run the code.
thanks so much!
As you can see the green arrow of the run command is disabled. in addition when i try to run from the run menu of the toolbar it just says edit configuration.
Just place cursor to the "main" method line and press right button and select run.
Right click in main method code and tap Run.

Tetris in GridWorld won't compile

I have an AP Computer Science assignment to make Tetris using GridWorld. I have to make 4 classes, TetrisBug, TetrisGame, TetrisBlock, and TetrisBlockO.
Here are the codes in that order:
TetrisBug.java
import info.gridworld.actor.*;
import info.gridworld.grid.*;
import java.util.ArrayList;
import java.awt.Color;
public class TetrisBug extends Bug
{
public TetrisBug(Color color)
{
super(color);
setDirection(180);
}
public void move()
{
Grid<Actor> gr = getGrid();
if (gr == null)
return;
Location loc = getLocation();
Location next = loc.getAdjacentLocation(getDirection());
if (gr.isValid(next))
moveTo(next);
else
removeSelfFromGrid();
}
public void act()
{
//this is empty for a reason.
}
}
TetrisGame.java
import info.gridworld.actor.*;
import info.gridworld.grid.*;
import java.util.ArrayList;
import java.awt.Color;
import info.gridworld.*;
public class TetrisGame {
public static ActorWorld world = new ActorWorld(new BoundedGrid<Actor>(19, 17));
public static TetrisBlock currentBlock;
public static int score;
public static void main(String[] args) {
//set up world
for (int i = 0; i < 19; i++) {
world.add(new Location(i,11),new Rock());
world.add(new Location(i,0),new Rock());
}
nextTetrisBlock();
//needed code for keyboard event handling
java.awt.KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(new java.awt.KeyEventDispatcher() {
public boolean dispatchKeyEvent(java.awt.event.KeyEvent event) {
String key = javax.swing.KeyStroke.getKeyStrokeForEvent(event).toString();
if (key.equals("pressed UP"))
currentBlock.rotate();
if (key.equals("pressed RIGHT"))
currentBlock.moveRight();
if (key.equals("pressed DOWN"))
currentBlock.act();
if (key.equals("pressed LEFT"))
currentBlock.moveLeft();
world.show();
return true;
}
});
world.show();
}
/**
* Calls removeCompleteRows and chooses a new TetrisBlock at random
*/
public static void nextTetrisBlock() {
removeCompleteRows();
TetrisBlock randomBlock = new TetrisBlock();//default 2block piece
//choose random block
int randNum = (int)(Math.random()*7)+1;//random number between 1 and 7
//if(randNum == 1)
// randomBlock = new TetrisBlockO();
//if(randNum == 2)
// randomBlock = new TetrisBlockI();
//if(randNum == 3)
// randomBlock = new TetrisBlockT();
//if(randNum == 4)
// randomBlock = new TetrisBlockL();
//if(randNum == 5)
// randomBlock = new TetrisBlock_L();
//if(randNum == 6)
// randomBlock = new TetrisBlockZ();
//if(randNum == 7)
// randomBlock = new TetrisBlock_Z();
currentBlock = randomBlock;
}
/**
* checks each row 1 through 18 (skip row 0) for full rows
* if a row is full, then remove the actor from each cell in that row
* and ask each actor located above the just deleted row to act and
* update the score++
*/
public static void removeCompleteRows() {
int columnsFilled = 0;
Grid grid = world.getGrid();
int row = 0;
//loops through rows only after each column has finished
for(row = grid.getNumRows()-1; row >= 0; row--) { //needed >=
columnsFilled = 0; //need to reinitialize this every iteration
for(int col = 0; col <= grid.getNumCols() - 1; col++) { //needed <=
if (grid.get(new Location(row,col)) != null) {
columnsFilled++;
}
}
if (columnsFilled == 10) {
for(int col = 0; col <= grid.getNumCols(); col++){
world.remove(new Location(row,col));
}
columnsFilled =0;
}
}
}
}
TetrisBlock.java
import info.gridworld.actor.*;
import info.gridworld.grid.*;
import java.util.ArrayList;
import java.awt.Color;
/**
* TetrisBlock is a type of Bug. It will act in GridWorld by moving down
* (direction 180) if it can, otherwise it will ask TetrisGame to make a new
* TetrisBlock for the game.
*/
public class TetrisBlock extends TetrisBug {
/**
* value of the current rotation position {0,1,2 or 3}
*/
protected int rotationPos;
/**
* blocks will have three TetrisBug objects in it... they will be added in the
* constructor
*/
protected ArrayList<TetrisBug> blocks;
/**
* used as a convenient reference to the Grid
*/
protected Grid<Actor> gr;
/**
* default constructor
*/
public TetrisBlock() {
super(Color.blue);
rotationPos = 0;
gr = TetrisGame.world.getGrid();
// ==> LAMEST GAME OVER EVER !!! <==
// if the Grid does not have room for the TetrisBlock.. GameOver
if (gr.get(new Location(0, 5)) != null
|| gr.get(new Location(1, 5)) != null) {
javax.swing.JOptionPane.showMessageDialog(null, "Score: "
+ TetrisGame.score, "GAME OVER!", 0);
System.exit(0);
}
putSelfInGrid(gr, new Location(1, 5));
blocks = new ArrayList<TetrisBug>();
TetrisBug a;
// create TetrisBugs for ArrayList blocks and put them in Grid gr
a = new TetrisBug(Color.blue);
a.putSelfInGrid(gr, new Location(0, 5));
blocks.add(a);
// TetrisBlock subclasses will add two more TetrisBug objects to blocks
}
/**
* TetrisBlock and its TetrisBugs must face down (direction 180) If they can
* move down, they will. Otherwise, it will ask TetrisGame to create a new
* TetrisBlock since this one is stuck at the bottom.
*/
public void act() {
setDirection(180);
for (TetrisBug tb : blocks)
tb.setDirection(180);
if (canMoveDown())
moveDown();
else {
if (!TetrisGame.currentBlock.canMoveDown())
TetrisGame.nextTetrisBlock();
}
}
/**
* Move the TetrisBlock and its TetrisBugs one cell. (they should already be
* facing down) Note: The order in which all the TetrisBugs move is important
* and depends on the current rotationPos.
*/
public void moveDown() {
if (rotationPos == 0) {
move();
blocks.get(0).move();
} else if (rotationPos == 1) {
blocks.get(0).move();
move();
}
}
/**
* Returns true if the TetrisBlock and its TetrisBugs can move (they should
* already be facing down) Otherwise, returns false.
*/
public boolean canMoveDown() {
if (rotationPos == 0)
return canMove();
else if (rotationPos == 1)
return canMove() && blocks.get(0).canMove();
else
return true;
}
/**
* Sets the direction of the TetrisBlock and its TetrisBugs to 90 (right) If
* they can move, they will move one cell (to the right)
*/
public void moveRight() {
setDirection(90);
for (TetrisBug tb : blocks)
tb.setDirection(90);
if (rotationPos == 0) {
if (canMove() && blocks.get(0).canMove()) {
blocks.get(0).move();
move();
}
} else if (rotationPos == 1) {
if (canMove()) {
move();
blocks.get(0).move();
}
}
}
/**
* Sets the direction of the TetrisBlock and its TetrisBugs to 90 (right) If
* they can move, they will move one cell (to the right)
*/
public void moveLeft() {
setDirection(270);
for (TetrisBug tb : blocks)
tb.setDirection(270);
if (rotationPos == 0) {
if (canMove() && blocks.get(0).canMove()) {
blocks.get(0).move();
move();
}
} else if (rotationPos == 1) {
if (canMove() && blocks.get(0).canMove()) {
blocks.get(0).move();
move();
}
}
}
/**
* If the TetrisBlock and its TetrisBugs can rotate, then they will all move
* to their proper location for the given rotation designated by
* rotationPos... Update rotationPos.
*/
public void rotate() {
Location nextLoc;
if (rotationPos == 0) {
// only one block must move
nextLoc = new Location(getLocation().getRow() - 1,
getLocation().getCol() + 1);
if (gr.isValid(nextLoc) && gr.get(nextLoc) == null) {
moveTo(nextLoc);
rotationPos = (rotationPos + 1) % 2;// will be % 4 with 4 blocks
}
} else if (rotationPos == 1) {
nextLoc = new Location(getLocation().getRow() + 1,
getLocation().getCol() - 1);
if (gr.isValid(nextLoc) && gr.get(nextLoc) == null) {
moveTo(nextLoc);
rotationPos = (rotationPos - 1) % 2;// will be % 4 with 4 blocks
}
}
}
}
TetrisBlockO.java
public class TetrisBlockO{
public TetrisBlockO() {
rotationPos = 0;
gr = TetrisGame.world.getGrid();
//GAME OVER!
if (gr.get(new Location(0, 5)) != null
|| gr.get(new Location(1, 5)) != null
|| gr.get(new Location(0, 6)) != null
|| gr.get(new Location(1, 6)) != null) {
javax.swing.JOptionPane.showMessageDialog(null, "Score: " + TetrisGame.score, "GAME OVER!", 0);
System.exit(0);
}
putSelfInGrid(gr, new Location(1, 5));
blocks = new ArrayList<TetrisBrick>();
TetrisBrick a;
a = new TetrisBrick(Color.blue);
a.putSelfInGrid(gr, new Location(0, 5));
blocks.add(a);
TetrisBrick b;
b = new TetrisBrick(Color.blue);
b.putSelfInGrid(gr, new Location(1, 6));
blocks.add(b);
TetrisBrick c;
c = new TetrisBrick(Color.blue);
c.putSelfInGrid(gr, new Location(0, 6));
blocks.add(c);
}
}
The first problem I'm having is in TetrisGame. The last method, to be precise. The grid.length statement is refusing to compile, and when I added a Grid grid = new Grid(); statement, it said it was abstract method and couldn't be instantiated. And compiling any of them give me a compiler warning,
\GridworldTetris\TetrisGame.java uses unchecked or unsafe operations.
Recompile with -Xlint:unchecked for details
The second problem is with the rotate method in TetrisBlock. I am not sure whether it works or not since the TetrisGame wont compile. I cant test it, but a friend of mine keeps telling me it's wrong, though IDK whether to believe him. Some validation would be nice.
Anyway, I have no real time limit on this, but I'd really like to be done with it. Thanks.
~Keelen
UPDATE: Thanks to user3580294 I solved the grid problem. But I found another, GRID DOESNT HAVE A LENGTH METHOD... I know what I was trying to do WOULD work, but cant find a way to do it, besides grid.length, which is invalid. Could someone make me a method that'd successfully remove completed rows? I really am stuck here... And I want to move to the next project...
For your removeCompleteRows() method try this in your if statement:
if (columnsFilled == 10) {
for(int col = 1; col < grid.getNumCols() - 1; col++){
grid.get(new Location( row,col )).removeSelfFromGrid();
}
columnsFilled = 0;
}
I think the World remove() method might work, but generally you won't have access to the World your Actor is on, so using Grid's removeSelfFromGrid() is safer.
Also, I assume you only want to remove the Blocks not your walls so you only want to iterate through Locations your Blocks might occupy, 1 through getNumCols() - 1.

Minesweeper hashset

I am writing a Minesweeper game, and I am trying to use a hashset. My question is can a hashset contain both integers and strings? The hastset I am using has mainly strings and one that is a integer. Can this be done? When I compile it, it gives me the error that the variable _minecount cannot be found, nothing about it not being a string. This is my code:
import java.util.Set;
import java.util.HashSet;
/**
* Represents a single square in Minesweeper.
*
* #author Sophia Ali
*/
public class MineSquare
{
//Constants:
// Fields:
private String _shown; // What a square is showing now
private boolean _mined; // Square is mined or not
private boolean _flagged; // Square is flagged or not
private boolean _questioned; // Square is question marked or not
private int _minecount; // Square's surrounding mine count
private boolean _opened; // Player has opened this square or not
private static final String[] VALID_SHOWN_TEXT = {"X", 0 < minecount && _minecount < 8, " ", "F", "?"};
private HashSet<String> validShownTextSet =
new HashSet<String>(java.util.Arrays.asList(VALID_SHOWN_TEXT));
// Constructors & Methods:
/**
* Default constructor
* Sets _mined and _opened to false.
*/
public MineSquare()
{
_mined = false;
_opened = false;
setShown(" ");
}
/**
* Returns flagged status of square.
* #return _flagged Flagged status
*/
public boolean isFlagged() {
return _flagged;
}
/**
* Sets or unsets flag on a square.
* #param flagged True or false (square is flagged or not)
*/
public void setFlagged(boolean flagged, boolean opened) {
_flagged = flagged;
_opened = opened;
// If Minesquare opened do nothing:
if (opened == true)
setShown(" ");
// If flagged, square should show "F":
if ( isFlagged() == true )
setShown("F");
else
setShown(" ");
}
public int getMinecount() {
return _minecount;
}
public void setMinecount(int minecount) {
_minecount = minecount;
if ( 0 < minecount && minecount < 8 )
{
setShown("Error:" + minecount);
}
}
public boolean isMined() {
return _mined;
}
public void setMined(boolean mined) {
_mined = mined;
}
public boolean isOpened() {
return _opened;
}
/**
* Open a square.
* (Once opened, a square can't be unopened.)
*/
public void setOpened() {
_opened = true;
if ( isMined() == true )
setShown("X");
else if ( getMinecount() > 0 )
setShown(_minecount + "");
else // blank space for _minecount = 0
setShown(" ");
}
public boolean isQuestioned() {
return _questioned;
}
public void setQuestioned(boolean questioned, boolean opened) {
_questioned = questioned;
_opened = opened;
// If Minesquare opened do nothing:
if (opened == true)
setShown(" ");
// If Questioned, square should show "F":
if ( isQuestioned() == true )
setShown("F");
else
setShown(" ");
}
public String getShown() {
return _shown;
}
public void setShown(String shown) {
_shown = shown;
/*if (shown.equals("X")) {
this.shown = shown;
} else if (shown.equals( 0 < minecount && minecount < 8 )) {
this.shown = shown;
} else if (shown.equals(" ")) {
this.shown = shown;
} else if (shown.equals("F")) {
this.shown = shown;
} else if (shown.equals("?")) {
this.shown = shown;
} else {
this.shown = "Error + shown";
}
*/
if (validShownTextSet.contains(shown)) {
this.shown = shown;
} else {
this.shown = "Error" + shown;
}
}
}
This line
private static final String[] VALID_SHOWN_TEXT = {"X", 0 < minecount && _minecount < 8, " ", "F", "?"};
has a few problems. There is no minecount variable in scope here. The variable _minecount is not a static variable, so it is inaccessible from the static scope you have made by making VALID_SHOWN_TEXT static.
And as it looks like you've guessed, you cannot store the boolean from the expression 0 < minecount && _minecount < 8 into a String array. Even if you can get a boolean expression working, you'll have to convert it to a String to store it into a String array.
// or a working boolean expression here.
..., String.valueOf(0 < minecount && _minecount < 8), ...
A HashSet<Object> can contain both integers and strings, but here, it looks like you can simply convert what you need into a string array, which should be able to be converted into a HashSet<String>.

Knight's Tour recursive algorithm

Okay everybody, I know the knight's tour problem is popular for all cs students and I am having trouble getting mine to work. I use this recursive algorithm to progress through the moves, however, once I get to around move 50 I have to backtrack since no moves are available and I end up never completing the tour. I pass a ChessNode (holds things like if node has been visited, move it was visited, etc...), next row, next column, and previous node's move count.
private int moveRecur(ChessNode current, int row, int column, int moveV){
current.moveVisited = moveV+1;
if(current.moveVisited > 63){
return 0;
}
if(current.position==13 && aboard[row-1][column+2].visited != 1){
current.visited = 1;
moveRecur(aboard[row-1][column+2], row-1, column+2, current.moveVisited);
}
else if(current.position==22 && aboard[row-2][column+1].visited != 1){
current.visited = 1;
moveRecur(aboard[row-2][column+1], row-2, column+1, current.moveVisited);
}
else if(current.position == 50 && aboard[row+1][column-2].visited != 1){
current.visited = 1;
moveRecur(aboard[row+1][column-2], row+1, column-2, current.moveVisited);
}
else if(current.position == 41 && aboard[row+2][column-1].visited != 1){
current.visited =1;
moveRecur(aboard[row+2][column-1], row+2, column-1, current.moveVisited);
}
else if(current.position == 46 && aboard[row+2][column+1].visited != 1){
current.visited = 1;
moveRecur(aboard[row+2][column+1], row+2, column+1, current.moveVisited);
}
else if(current.position == 53 && aboard[row+1][column+2].visited != 1){
current.visited = 1;
moveRecur(aboard[row+1][column+2], row+1, column+2, current.moveVisited);
}
else if(current.position == 10 && aboard[row-1][column-2].visited != 1){
current.visited = 1;
moveRecur(aboard[row-1][column-2], row-1, column-2, current.moveVisited);
}
else if (current.position == 17 && aboard[row-2][column-1].visited != 1){
current.visited =1;
moveRecur(aboard[row-2][column-1], row-2, column-2, current.moveVisited);
}
if(row+1>=0 && row+1<8 && column+2>=0 && column+2<8){
if(aboard[row+1][column+2].visited != 1){
current.visited = 1;
moveRecur(aboard[row+1][column+2], row+1, column+2, current.moveVisited);
}
}
if(row+2>=0 && row+2<8 && column+1>=0 && column+1<8){
if(aboard[row+2][column+1].visited != 1){
current.visited = 1;
moveRecur(aboard[row+2][column+1], row+2, column+1, current.moveVisited);
}
}
if(row-1>=0 && row-1<8 && column-2>=0 && column-2<8){
if(aboard[row-1][column-2].visited != 1){
current.visited = 1;
moveRecur(aboard[row-1][column-2], row-1, column-2, current.moveVisited);
}
}
if(row-2>=0 && row-2<8 && column-1>=0 && column-1<8){
if(aboard[row-2][column-1].visited != 1){
current.visited = 1;
moveRecur(aboard[row-2][column-1], row-2, column-1, current.moveVisited);
}
}
if(row+1>=0 && row+1<8 && column-2>=0 && column-2<8){
if(aboard[row+1][column-2].visited != 1){
current.visited = 1;
moveRecur(aboard[row+1][column-2], row+1, column-2, current.moveVisited);
}
}
if(row+2>=0 && row+2<8 && column-1>=0 && column-1<8){
if(aboard[row+2][column-1].visited != 1){
current.visited = 1;
moveRecur(aboard[row+2][column-1], row+2, column-1, current.moveVisited);
}
}
if(row-1>=0 && row-1<8 && column+2>=0 && column+2<8){
if(aboard[row-1][column+2].visited != 1){
current.visited = 1;
moveRecur(aboard[row-1][column+2], row-1, column+2, current.moveVisited);
}
}
if(row-2>=0 && row-2<8 && column+1>=0 && column+1<8){
if(aboard[row-2][column+1].visited != 1){
current.visited = 1;
moveRecur(aboard[row-2][column+1], row-2, column+1, current.moveVisited);
}
}
//System.out.println(current.position + " "+current.moveVisited);
current.visited = 0;
return 0;
}
So, initially I check for the spots that can move to the corner board positions, and then I just make recursive calls based on available moves. So I guess my main question is am I doing something wrong? or is there another condition I can used to make the tour a little more intuitive?
Thanks in advance!
This is the Knight's tour code in java and has a brilliant layout. I did this using backtracking using recursion. This was my class assignment. Do contact me if you have any problem understanding or running this code.
package knights.tour;
import java.awt.*;
import java.awt.event.*;
import java.util.logging.*;
import javax.swing.*;
public class KnightsTour extends JFrame implements ActionListener{
//All the static variables used between action listeners and functions.
public static String path;
public static int btnPressed = 0;
public static int rowSelected;
public static String[] pathArray;
public static int[][] coordinatesArray;
public static int columnSelected;
public static int flag =0;
public static int increment = 0;
public static JPanel panel1 = new JPanel();
public static JPanel panel3 ;
public static JButton btnStart = new JButton("Start Animation");
public static JButton btnClear = new JButton("Clear");
public static JTextArea lblPath = new JTextArea();
public static JLabel lblStartRow = new JLabel();
public static JLabel lblStartColumn = new JLabel();
public static JButton[][] button;
public static int variableForIncrement=0;
static int row ;
static int column ;
static int[][] array = new int[row][column];
public static int count = 1;
KnightsTour(){
//Setting layout of the frame in the constructor and adding buttons to the panel and the frame.
getContentPane().setLayout(new GridLayout(2,1));
lblPath.setLineWrap(true);
lblPath.setColumns(10);
lblPath.setSize(700, 100);
lblPath.setEditable(false);
panel1.add(btnStart);
panel1.add(btnClear);
panel1.add(lblStartRow);
panel1.add(lblStartColumn);
panel1.add(lblPath);
panel3 = new JPanel(new GridLayout(row,column));
// Initializing Array of buttons for the user to click on the chess board.
button= new JButton[row][column];
array = new int[row][column];
coordinatesArray = new int[row*column][2]; // This array stores the coordinates as the Knight
for(int i=0;i<row;i++){
for(int j=0;j<column;j++){
button[i][j] = new JButton();
}
}
//Setting background of the buttons to black and white for chessboard layout.
for(int i=0;i<row;i++){
for(int j=0;j<column;j++){
if(i%2 ==j%2){
button[i][j].setBackground(Color.BLACK);
button[i][j].setForeground(Color.WHITE);
}
else{
button[i][j].setBackground(Color.WHITE);
}
panel3.add(button[i][j]);
button[i][j].addActionListener(this);
}
}
btnClear.addActionListener(this);
btnStart.addActionListener(this);
add(panel3);
add(panel1);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) {
// TODO code application logic here
String input =JOptionPane.showInputDialog("Enter the rows and columns in the format (row,column)");
String[] ar = input.split(",");
row = Integer.parseInt(ar[0]); // Finding out row and column from the user input.
column = Integer.parseInt(ar[1]);
pathArray = new String[row*column]; // This array is kept to store the path of the knight.
JFrame frame = new KnightsTour();
frame.setVisible(true);
frame.setSize(700,700);
}
//All the computation takes place in this function. It checks the neighbour and recursively calls itself.
public static void neighbourRecursion(int a,int b){
pathArray[increment] = Integer.toString(a) + "," + Integer.toString(b); // Storing the path of the Knight
increment++;
array[a][b] = count; //Stroing value of count.
button[a][b].setText(String.valueOf(count));
coordinatesArray[variableForIncrement][0] = button[a][b].getX(); //Finding coordinates of buttons to show animation
coordinatesArray[variableForIncrement][1] = button[a][b].getY();
count++;
variableForIncrement++;
//Checking for valid neighbours and calling itself recursively.
if(a <= row-3 && b<=column-2){
if(alreadyVisited(a+2,b+1)){
neighbourRecursion(a+2,b+1);
}
}
if(a<=row-3 && b>=1){
if(alreadyVisited(a+2,b-1)){
neighbourRecursion(a+2,b-1);
}
}
if(a>=2 && b<=column-2){
if(alreadyVisited(a-2,b+1)){
neighbourRecursion(a-2,b+1);
}
}
if(a>=2 && b>=1){
if(alreadyVisited(a-2,b-1)){
neighbourRecursion(a-2,b-1);
}
}
if(a<=row-2 && b>=2){
if(alreadyVisited(a+1,b-2)){
neighbourRecursion(a+1,b-2);
}
}
if(a<=row-2 && b<=column-3){
if(alreadyVisited(a+1,b+2)){
neighbourRecursion(a+1,b+2);
}
}
if(a>=1 && b>=2){
if(alreadyVisited(a-1,b-2)){
neighbourRecursion(a-1,b-2);
}
}
if(a>=1 && b <=column-3){
if(alreadyVisited(a-1,b+2)){
neighbourRecursion(a-1,b+2);
}
}
//Breaking condition of the function.
if(count == (row*column)+1){
}
// Backtracking condition if there is no neighbour.
else{
button[a][b].setText("");
array[a][b]=0;
count--;
variableForIncrement--;
if(increment >0){
increment--;
}
return ;
}
}
//This function checks if the neighbour is already visited.
public static boolean alreadyVisited(int a,int b){
if(array[a][b] != 0){
return false;
}
else{
return true;
}
}
#Override
public void actionPerformed(ActionEvent e) {
//when clear is pressed all arrays and global variables are set to initial conditon.
if(e.getSource() == btnClear){
for(int i =0;i<row;i++){
for(int j=0;j<column;j++){
array[i][j] = 0;
button[i][j].setText("");
count = 1;
lblPath.setText("");
lblStartRow.setText("");
lblStartColumn.setText("");
flag =0;
variableForIncrement=0;
increment =0;
path =" ";
}
}
}
//If start animation button is pressed animation is started.
else if(e.getSource() == btnStart){
animate();
}
// When the button is pressed.
else{
for(int i=0;i<row;i++){
for(int j=0;j<column;j++){
if(e.getSource() == button[i][j]){
if(flag == 1){
lblPath.setText(" Please press clear before clicking again"); // Button pressed twice without reset.
}
else{
rowSelected = i;
columnSelected =j;
// If odd * odd board and selected postion is odd then No path is possible.
if(row%2 ==1 && column%2 == 1 && rowSelected%2 ==0 && columnSelected%2 == 1 || row%2 ==1 && column%2 == 1 && rowSelected%2 ==1 && columnSelected%2 == 0){
lblPath.setText(" Path not possible from this point");
}
else{
int count;
lblStartRow.setText("Starting Row : "+String.valueOf(rowSelected + 1));
lblStartColumn.setText("Starting Column : "+String.valueOf(columnSelected + 1));
count = 1;
flag = 1;
startTour(); //Start tour function called.
for(int q=0;q<row;q++){
for(int w=0;w<column;w++){
if(array[i][j] == 0){
count++;
}
}
}
if(count > 2){
lblPath.setText(" No Path found");
}
//Printing path of the knight here.
else{
for(int k=0;k<pathArray.length;k++){
path = path+"->"+ pathArray[k];
}
lblPath.setText(" Path : \n"+ path.substring(5));
}
btnPressed = 1;
break;
}
}
}
}
}
} }
//Function for the animation.
void animate(){
if(btnPressed == 1){
btnPressed =0;
Graphics g = getGraphics();
for(int i=0;i<(row*column)-1;i++){
try {
Thread.sleep(600); // this function slows down drawing of lines.
} catch (InterruptedException ex) {
}
g.setColor(Color.RED); // setting colour or line to red.
g.drawLine((coordinatesArray[i][0]+65),(coordinatesArray[i][1]+50),(coordinatesArray[i+1] [0]+65),(coordinatesArray[i+1][1]+50));
}
}
else{
lblPath.setText(" Please clear, select a button to see the animation again"); //Animate button pressed twice without clear.
}
}
//This function calls the neighbour function with the selected row and column by the user.
static void startTour(){
neighbourRecursion(rowSelected,columnSelected);
for(int i=0;i<row;i++){
for(int j=0;j<column;j++){
System.out.print(array[i][j]+" ");
}
System.out.println();
}
}
}
I have an implementation of this program in C#. You can find it here:
http://github.com/danieltian/KnightBoard
It will only find the first solution though. I'm not saying to copy it, but you can take a look at it and see if it helps.

Categories

Resources