This is my board class
public class Board {
char[][] grid;
int width;
int height;
int count;
char player;
public Board(int height, int width){
count = 0;
grid = new char[height][width];
this.width = width;
this.height = height;
for(int i = 0; i < height; i++) {
for(int j = 0; j < width; j++){
if(i == 0 && j == 0){
grid[i][j] = '┌';
}
else if(j % 2 == 1) {
grid[i][j] = '─';
}
else if (i == 0 && j == width - 1){
grid[i][j] = '┐';
}
else if (i == height-1 && j == 0){
grid[i][j] = '└';
}
else if (i == height - 1 && j == width - 1){
grid[i][j] = '┘';
}
else if (i == 0){
grid[i][j] = '┬';
}
else if (j == 0){
grid[i][j] = '├';
}
else if (i == height - 1){
grid[i][j] = '┴';
}
else if (j == width - 1){
grid[i][j] = '┤';
}
else
grid[i][j] = '┼';
}
}
}
public void print(){
for(int i=0; i<height; i++){
for(int j=0; j<width; j++)
System.out.print(grid[i][j]);
System.out.println();
}
}
Below is the put function of the board class. The problem is the put function. You must enter a line from the selectline function and have the player appear on the desired line.
However, no matter how hard I modify the conditional statement, it only appears in the first line.
How do I modify the conditional statement of the put function?
public void put(SelectLine setLine) {
int y=setLine.getY();
int x = grid.length-1;
if(count%2 == 0) {
player = '●';
}
else {
player = '○';
}
for(int i = grid.length-1; i >=0; i--) {
if(grid[i][(y-1)*2] != player) {
grid[i][(y-1)*2] = player;
count++;
break;
}
}
System.out.println("────────" + player + "'s Turn ────────");
this.print();
}
}
public class SelectLine {
int line;
public void input(){
System.out.print("Select Line : ");
Scanner sc = new Scanner(System.in);
line = sc.nextInt();
}
public int getY(){
return line;
}
}
The goal is to keep stacking up like the picture below.
enter image description here
Modify your SelectLine class as follows:
class SelectLine {
int line;
public int input(){
System.out.print("Select Line : ");
Scanner sc = new Scanner(System.in);
line = sc.nextInt();
return line;
}
public int getY(){
return input();
}
Working code:
https://onlinegdb.com/ryhum-Eu_
You need to take into account that a user may input negative values or such exceeding grid size, though.
Regards.
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Board b = new Board(10, 10);
b.print();
b.put(new SelectLine());
System.out.println("Hello World");
}
}
class Board {
char[][] grid;
int width;
int height;
int count;
char player;
public Board(int height, int width){
count = 0;
grid = new char[height][width];
this.width = width;
this.height = height;
for(int i = 0; i < height; i++) {
for(int j = 0; j < width; j++){
if(i == 0 && j == 0){
grid[i][j] = '┌';
}
else if(j % 2 == 1) {
grid[i][j] = '─';
}
else if (i == 0 && j == width - 1){
grid[i][j] = '┐';
}
else if (i == height-1 && j == 0){
grid[i][j] = '└';
}
else if (i == height - 1 && j == width - 1){
grid[i][j] = '┘';
}
else if (i == 0){
grid[i][j] = '┬';
}
else if (j == 0){
grid[i][j] = '├';
}
else if (i == height - 1){
grid[i][j] = '┴';
}
else if (j == width - 1){
grid[i][j] = '┤';
}
else
grid[i][j] = '┼';
}
}
}
public void print(){
for(int i=0; i<height; i++){
for(int j=0; j<width; j++)
System.out.print(grid[i][j]);
System.out.println();
}
}
public void put(SelectLine setLine) {
int y=setLine.getY();
int x = grid.length-1;
if(count%2 == 0) {
player = '●';
}
else {
player = '○';
}
for(int i = grid.length-1; i >=0; i--) {
if(grid[i][(y-1)*2] != player) {
grid[i][(y-1)*2] = player;
count++;
break;
}
}
System.out.println("────────" + player + "'s Turn ────────");
this.print();
}
}
class SelectLine {
int line;
public int input(){
System.out.print("Select Line : ");
Scanner sc = new Scanner(System.in);
line = sc.nextInt();
return line;
}
public int getY(){
return input();
}
}
Related
public class AirplaneLab
{
private int [][] first;
private int [][] economy;
private boolean [] seat;
private boolean okay;
private boolean okayokay;
public AirplaneLab()
{
}
public AirplaneLab(int [][] first1, int [][] economy1)
{
}
public boolean viewFirstClass(boolean set[], int [][] first, int [][] economy)
{
if (okay = true)
{
boolean seating1[] = new boolean[20];
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 4; j++)
{
if(seat[((j + 1) + (i * 4)) - 1])
{
System.out.print("x ");
seating1[i * j] = true;
}
else
{
System.out.print("o ");
seating1[i * j] = flase;
}
}
System.out.println();
}
System.out.println("The x's are the sets that are taken, o's are not");
return seating1[];
}
else
{
return false;
}
}
public boolean viewEconomyClass(boolean set[], int [][] first, int [][] economy)
{
if (okayokay = true)
{
boolean seating2[] = new boolean[30];
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 3; j++)
{
if(seat[((j + 1) + (i * 3)) - 1])
{
System.out.print("x ");
seating2[i * j] = true;
}
else
{
System.out.print("o ");
seating2[i * j] = false;
}
}
System.out.println();
}
System.out.println("The x's are the sets that are taken, o's are not");
return seating2[];
}
else
{
return false;
}
}
public void decision()
{
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.println("Please choose an option:");
System.out.println("1 for “booking in first class”");
System.out.println("2 for “booing in economy class”");
System.out.println("3 to view seating chart for first class ");
System.out.println("4 to view seating chart for economy class");
System.out.println("0 to exit");
System.out.print("? ");
while(true)
{
int mOpt = input.nextInt();
if ((mOpt == 1) || (mOpt == 3))
{
if (mOpt == 1)
{
okay = true;
System.out.println("Based on the following setting arrangement, please pick a window middle or end seat");
viewFirstClass(boolean set[], int [][] first, int [][] economy);
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 4; j++)
{
if (seating1[i * j] == true)
{
if ((i * j) ________________)
}
}
}
}
}
}
}
}
In the code above, where the blank is:
The last if statement before all of the closed brackets:
I was wondering how you would use module there.
Let's say I wanted to do (i * j) module of 4; how would I do that? Can you fill in the blank? Thank you for your help!
If you are looking for some thing (modulo) like
if ((i * j) mod 4 )
in java ,the syntax would be
if ((i * j) % 4 )
import java.util.Scanner;
public class Recursion
{
//variables to hold string values
public static String s1 = new String(new char[10]);
public static String s2 = new String(new char[10]);
public static String s3 = new String(new char[11]);
public static String charSet = new String(new char[11]);
//variables to hold number values
public static int numberOne;
public static int numberTwo;
public static int numberThree;
public static int maxCharCount;
public static int[] numberSet = new int[10];
//function which generates a number
public static void checkForEquality()
{
numberOne = numberTwo = numberThree = 0;
int i;
int j;
for (i = 0; i < s1.length(); i++)
{
for (j = 0; j < maxCharCount; j++)
{
if (s1.charAt(i) == charSet.charAt(j))
{
if (i == 0 && numberSet[j] == 0)
return;
//generate the number
numberOne = (numberOne * 10) + numberSet[j];
}
}
}
for (i = 0; i < s2.length(); i++)
{
for (j = 0; j < maxCharCount; j++)
{
if (s2.charAt(i) == charSet.charAt(j))
{
if (i == 0 && numberSet[j] == 0)
return;
//generate number
numberTwo = (numberTwo * 10) + numberSet[j];
}
}
}
for (i = 0; i < s3.length(); i++)
{
for (j = 0; j < maxCharCount; j++)
{
if (s3.charAt(i) == charSet.charAt(j))
{
if (i == 0 && numberSet[j] == 0)
return;
//generate the number
numberThree = (numberThree * 10) + numberSet[j];
}
}
}
}
public static void display(){
if (numberOne + numberTwo == numberThree) {
//display the output
int i=0;
System.out.println();
System.out.print(" Summation Puzzle solved. ");
System.out.print("n");
System.out.print(s1);
System.out.print("<==>");
System.out.print(numberOne);
System.out.print("n");
System.out.print(s2);
System.out.print("<==>");
System.out.print(numberTwo);
System.out.print("n");
System.out.print(s3);
System.out.print("<==>");
System.out.print(numberThree);
System.out.print("n");
//loop to show the result
for (i = 0; i < maxCharCount; i++)
{
System.out.println(charSet.charAt(i));
System.out.print("<==>");
System.out.print(numberSet[i]);
System.out.print("n");
}
System.exit(0);
}
}
//recursive function which will call itself
public static void Combinations(int indexCounter, int[] availableSet)
{
int i;
if (indexCounter != 0)
{
for (i = 0; i < 10; i++)
{
numberSet[indexCounter] = i;
if (availableSet[i] == 1)
{
availableSet[i] = 0;
Combinations(indexCounter + 1, availableSet);
availableSet[i] = 1;
}
}
}
if (indexCounter == maxCharCount)
checkForEquality();
}
public static void createCharSet()
{
int i;
int setIndex;
int present;
int j;
setIndex = 0;
for (i = 0; i < s1.length(); i++)
{
present = 0;
for (j = 0; j < setIndex; j++)
{
if (s1.charAt(i) == charSet.charAt(j))
{
present = 1;
}
}
if (present == 0)
{
charSet = StringFunctions.changeCharacter(charSet, setIndex++, s1.charAt(i));
}
}
for (i = 0; i < s2.length(); i++)
{
present = 0;
for (j = 0; j < setIndex; j++)
{
if (s2.charAt(i) == charSet.charAt(j))
{
present = 1;
}
}
if (present == 0)
{
charSet = StringFunctions.changeCharacter(charSet, setIndex++, s2.charAt(i));
}
}
for (i = 0; i < s3.length(); i++)
{
present = 0;
for (j = 0; j < setIndex; j++)
{
if (s3.charAt(i) == charSet.charAt(j))
{
present = 1;
}
}
if (present == 0)
{
charSet = StringFunctions.changeCharacter(charSet, setIndex++, s3.charAt(i));
}
}
maxCharCount = setIndex;
}
public static void calculateSummation()
{
int loop;
if (maxCharCount > 10)
{
System.out.print("Please check the input again");
return;
}
else
{
int[] avaliableSet = new int[10];
for (loop = 0; loop < 10; loop++)
{
avaliableSet[loop] = 1;
}
Combinations(0, avaliableSet);
}
}
//main method
public static void main(String[]args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter the first String :");
s1 = scan.next();
System.out.print("Enter the second String :");
s2 = scan.next();
System.out.print("Enter the thirsd String :");
s3 = scan.next();
createCharSet();
System.out.print(" result of your 3 three strings = ");
System.out.print(charSet);
calculateSummation();
checkForEquality();
display();
}
}
Every time I run the program it just assigns 0 to each value. I want to be able to assign a value from 1-10 to each non numeric character.
can someone help me out.?
it should look something like this
Sample output
First off, you may find debugging easier if you properly format your code. I remember you posting last night where you experienced similar issues resulting from syntax. You may find that your code is easier to read if you format it like this:
//function which generates a number
public static void checkForEquality(){
numberOne = numberTwo = numberThree = 0;
int i;
int j;
for (i = 0; i < s1.length(); i++){
for (j = 0; j < maxCharCount; j++){
if (s1.charAt(i) == charSet.charAt(j)){
if (i == 0 && numberSet[j] == 0)
return;
//generate the number
numberOne = (numberOne * 10) + numberSet[j];
}
}
}
for (i = 0; i < s2.length(); i++){
for (j = 0; j < maxCharCount; j++){
if (s2.charAt(i) == charSet.charAt(j)){
if (i == 0 && numberSet[j] == 0)
return;
//generate number
numberTwo = (numberTwo * 10) + numberSet[j];
}
}
}
Take a look at just this portion of your code and see if it still properly follows your algorithm. You may find an error which you could've located yourself with properly formatted code. If you take a look at a previous question of yours (which I answered) you'll find a helpful link that guides you to writing better code.
Also, I didn't try to compile this in my own IDE, but you should take a look at Eclipse. A lot of the small errors you're getting could be located automatically by Eclipse.
I am programming a minesweeper game, and having a problem making the main method. I cant seem to get the text based game to output to the screen, allowing the user to interact with it. I have tried several ways, but none have worked.
public class Game {
private Board board;
boolean finish = false;
boolean win = false;
int turn = 0;
public void Jogo() {
board = new Board();
Play(board);
}
public void Play(Board board) {
do {
turn++;
System.out.println("Turn " + turn);
board.show();
finish = board.setPosition();
if (!finish) {
board.openNeighbors();
finish = board.win();
}
} while (!finish);
if (board.win()) {
System.out.println("Congratulations, you let the 10 fields with the mines in " + turn
+ " turns");
board.showMines();
} else {
System.out.println("Mine! You lost!");
board.showMines();
}
}
}
import java.util.Random;
import java.util.Scanner;
public class Board extends Game {
private int[][] mines;
private char[][] boardgame;
private int Line, Column;
Random random = new Random();
Scanner input = new Scanner(System.in);
public void Jogo() {
mines = new int[10][10];
boardgame = new char[10][10];
startMines();
randomMines();
fillTips();
startBoard();
}
public boolean win() {
int count = 0;
for (int line = 1; line < 9; line++)
for (int column = 1; column < 9; column++)
if (boardgame[line][column] == '_')
count++;
if (count == 10)
return true;
else
return false;
}
public void openNeighbors() {
for (int i = -1; i < 2; i++)
for (int j = -1; j < 2; j++)
if ((mines[Line + i][Column + j] != -1)
&& (Line != 0 && Line != 9 && Column != 0 && Column != 9))
boardgame[Line + i][Column + j] =
Character.forDigit(mines[Line + i][Column + j], 10);
}
public int getPosition(int Line, int Column) {
return mines[Line][Column];
}
public boolean setPosition() {
do {
System.out.print("\nLine: ");
Line = input.nextInt();
System.out.print("Column: ");
Column = input.nextInt();
if ((boardgame[Line][Column] != '_')
&& ((Line < 9 && Line > 0) && (Column < 9 && Column > 0)))
System.out.println("Field already shown");
if (Line < 1 || Line > 8 || Column < 1 || Column > 8)
System.out.println("Choose a number between 1 and 8");
} while ((Line < 1 || Line > 8 || Column < 1 || Column > 8)
|| (boardgame[Line][Column] != '_'));
if (getPosition(Line, Column) == -1)
return true;
else
return false;
}
public void show() {
System.out.println("\n Lines");
for (int Line = 8; Line > 0; Line--) {
System.out.print(" " + Line + " ");
for (int Column = 1; Column < 9; Column++) {
System.out.print(" " + boardgame[Line][Column]);
}
System.out.println();
}
System.out.println("\n 1 2 3 4 5 6 7 8");
System.out.println(" Columns");
}
public void fillTips() {
for (int line = 1; line < 9; line++)
for (int column = 1; column < 9; column++) {
for (int i = -1; i <= 1; i++)
for (int j = -1; j <= 1; j++)
if (mines[line][column] != -1)
if (mines[line + i][column + j] == -1)
mines[line][column]++;
}
}
public void showMines() {
for (int i = 1; i < 9; i++)
for (int j = 1; j < 9; j++)
if (mines[i][j] == -1)
boardgame[i][j] = '*';
show();
}
public void startBoard() {
for (int i = 1; i < mines.length; i++)
for (int j = 1; j < mines.length; j++)
boardgame[i][j] = '_';
}
public void startMines() {
for (int i = 0; i < mines.length; i++)
for (int j = 0; j < mines.length; j++)
mines[i][j] = 0;
}
public void randomMines() {
boolean raffled;
int Line, Column;
for (int i = 0; i < 10; i++) {
do {
Line = random.nextInt(8) + 1;
Column = random.nextInt(8) + 1;
if (mines[Line][Column] == -1)
raffled = true;
else
raffled = false;
} while (raffled);
mines[Line][Column] = -1;
}
}
}
public class MineSweeper extends Board {
public static void main(String[] args) {
Game game = new Game();
}
}
I am creating a game that is called "Shapeshifter" and can't figure out how to check the 2D array game board to see if the shape that the user made with the cursor is actually the shape wanted. Any amount of code works, it just needs to actually work with the rest of the game.
Here is the code that I have done:
public static final int COLS = 7;
public static final int ROWS = 7;
public static int ZEE = 0;
public static int TEE = 1;
public static int ES = 2;
public static int OH = 3;
public static int JAY = 4;
public static int EL = 5;
public static int NUM_POLYOMINOS = 6;
public static int PIECE_SIZE = 4;
public static int UP = 8;
public static int LEFT = 4;
public static int DOWN = 2;
public static int RIGHT = 6;
public static int QUIT = 5;
public static int EMPTY = 0;
public static int POLY_PIECE = 1;
public static int PLAYER = 2;
private static int[][] getRandomPoly()
{
int rint = new java.util.Random().nextInt(NUM_POLYOMINOS);
if (rint == ZEE)
return new int[][]{{1, 1, 0},
{0, 1, 1}};
else if (rint == TEE)
return new int[][]{{0, 1, 0},
{1, 1, 1}};
else if (rint == ES)
return new int[][]{{0, 1, 1},
{1, 1, 0}};
else if (rint == OH)
return new int[][]{{1, 1},
{1, 1}};
else if (rint == JAY)
return new int[][]{{1, 0, 0},
{1, 1, 1}};
else //if (rint == EL)
return new int[][]{{0, 0, 1},
{1, 1, 1}};
}
public void printCurrentPoly()
{
if (currentPoly == null)
return;
System.out.println("Current polyomino:");
System.out.println();
for (int i = 0; i < currentPoly.length; i++)
{
for (int j = 0; j < currentPoly[0].length; j++)
if (currentPoly[i][j] == 0)
System.out.print(" ");
else
System.out.print("#");
System.out.println();
}
System.out.println();
}
public void initializeBoard()
{
for (int i = 0; i < board.length; i++)
for (int j = 0; j < board[0].length; j++)
board[i][j] = 0;
currentRow = board.length / 2;
currentCol = board[0].length / 2;
board[currentRow][currentCol] = PLAYER;
for (int i = 0; i < PIECE_SIZE; i++)
{
int rrow = new java.util.Random().nextInt(ROWS),
rcol = new java.util.Random().nextInt(COLS);
while ((rrow == 0 || rrow == board.length - 1) ||
(rcol == 0 || rcol == board[0].length - 1) ||
(rrow == board.length / 2 && rcol == board[0].length / 2) ||
(board[rrow][rcol] == POLY_PIECE))
{
rrow = new java.util.Random().nextInt(ROWS);
rcol = new java.util.Random().nextInt(COLS);
}
board[rrow][rcol] = POLY_PIECE;
}
currentPoly = getRandomPoly();
}
public static void main(String args[])
{
boolean done = false;
ShapeShifter ss = new ShapeShifter();
ss.initializeBoard();
ss.printCurrentPoly();
ss.printBoard();
while (!done)
{
int move = ss.getMove();
if (move == QUIT)
done = true;
else
{
ss.executeMove(move);
if (ss.checkForMatch())
done = true;
System.out.println("\n");
ss.printCurrentPoly();
ss.printBoard();
}
}
ss.printResult();
}
private int[][] board = new int[ROWS][COLS];
private int[][] currentPoly;
private int numMoves, currentRow, currentCol;
private boolean winner;
private Scanner stdin = new Scanner(System.in);
public void printBoard()
{
System.out.println("+-------+");
for(int i = 0; i < board.length; i++)
{
System.out.print("|");
for(int j = 0; j < board[0].length; j++)
{
if(board[i][j] == POLY_PIECE)
System.out.print("#");
else if (board[i][j] == PLAYER)
System.out.print("H");
else
System.out.print(" ");
}
System.out.println("|");
}
System.out.println("+-------+");
}
public int getMove()
{
System.out.println("Were do you want to move? (4=left, 2=down, 8=up, 6=right or 5=quit)");
int move = stdin.nextInt();
while(move != LEFT && move != RIGHT && move != UP && move != DOWN && move != QUIT)
{
System.out.println("Invalid, only valid moves allowed are 4=left, 2=down, 8=up, 6=right or 5=quit");
move = stdin.nextInt();
}
return move;
}
public void executeMove(int move)
{
if(move == LEFT)
moveLeft(move);
if(move == RIGHT)
moveRight(move);
if(move == UP)
moveUp(move);
if(move == DOWN)
moveDown(move);
numMoves++;
}
private void moveLeft(int move)
{
int currentRow = 0, currentCol = 0;
for(int i = 0; i < board.length; i++)
for(int j = 0; j < board[0].length; j++)
if(board[i][j] == 2)
{ currentRow = i;
currentCol = j;
}
if(move == LEFT)
{
if(currentCol != 0 && board[currentRow][currentCol - 1] != POLY_PIECE)
{
board[currentRow][currentCol - 1] = PLAYER;
board[currentRow][currentCol] = EMPTY;
}
if(currentCol != 0 && board[currentRow][currentCol - 1] == POLY_PIECE && board[currentRow][currentCol - 2] != POLY_PIECE)
{
board[currentRow][currentCol - 1] = PLAYER;
board[currentRow][currentCol - 2] = POLY_PIECE;
board[currentRow][currentCol] = EMPTY;
}
}
}
private void moveRight(int move)
{
int currentRow = 0, currentCol = 0;
for(int i = 0; i < board.length; i++)
for(int j = 0; j < board[0].length; j++)
if(board[i][j] == 2)
{ currentRow = i;
currentCol = j;
}
if(move == RIGHT)
{ if (currentCol != 6 && board[currentRow][currentCol + 1] != POLY_PIECE)
{
board[currentRow][currentCol + 1] = PLAYER;
board[currentRow][currentCol] = EMPTY;
}
if(currentCol != 6 && board[currentRow][currentCol + 1] == POLY_PIECE && board[currentRow][currentCol + 2] != POLY_PIECE)
{
board[currentRow][currentCol + 1] = PLAYER;
board[currentRow][currentCol + 2] = POLY_PIECE;
board[currentRow][currentCol] = EMPTY;
}
}
}
private void moveUp(int move)
{
int currentRow = 0, currentCol = 0;
for(int i = 0; i < board.length; i++)
for(int j = 0; j < board[0].length; j++)
if(board[i][j] == 2)
{ currentRow = i;
currentCol = j;
}
if(move == UP)
{
if(currentRow != 0 && board[currentRow - 1][currentCol] != POLY_PIECE)
{
board[currentRow - 1][currentCol] = PLAYER;
board[currentRow][currentCol] = EMPTY;
}
if(currentRow != 0 && board[currentRow - 1][currentCol] == POLY_PIECE && board[currentRow - 2][currentCol] != POLY_PIECE)
{
board[currentRow - 1][currentCol] = PLAYER;
board[currentRow - 2][currentCol] = POLY_PIECE;
board[currentRow][currentCol] = EMPTY;
}
}
}
private void moveDown(int move)
{
int currentRow = 0, currentCol = 0;
for(int i = 0; i < board.length; i++)
for(int j = 0; j < board[0].length; j++)
if(board[i][j] == 2)
{ currentRow = i;
currentCol = j;
}
if(move == DOWN)
{ if(currentRow != 6 && board[currentRow + 1][currentCol] != POLY_PIECE)
{
board[currentRow + 1][currentCol] = PLAYER;
board[currentRow][currentCol] = EMPTY;
}
if(currentRow != 6 && board[currentRow + 1][currentCol] == POLY_PIECE && board[currentRow + 2][currentCol] != POLY_PIECE)
{
board[currentRow + 1][currentCol] = PLAYER;
board[currentRow + 2][currentCol] = POLY_PIECE;
board[currentRow][currentCol] = EMPTY;
}
}
}
public void printResult()
{
if(checkForMatch() == false)
System.out.println("You did not win. You used " + numMoves + " moves to fail.");
else
System.out.println("You won!!n/" + "It took " + numMoves + " moves to complete.");
}
}
Here is the final piece to the game that I am having trouble with:
public boolean checkForMatch()
{
}
You didn't say whether the polyomino (not polynomial) can be in any orientation. If so, I think you'll have to loop through the rotations and reflections and test each one. For each orientation there are not many positions where it can line up with the board. For each you need to check each spot and see if the player has filled them all in.
Since your polyominoes are defined in advance, for optimization you could also define constants for each one saying which ways it's symmetrical, so you can avoid redundant tests. Not that extra tests would actually matter.
You can "re-use" a lot of the code you already wrote for printCurrentPoly and printBoard to implement checkForWinner.
The idea is to go through all the cells of the board. For each cell check: if the current poly would start at this cell are all # cells in the poly matched with the player char (o or x) on the board. If yes, the player is a winner. Otherwise go to the next cell.
Here the relevant code:
/**
* Returns true when the current polyTicTacToc can be found at x,y of the
* board, with its cells filled for the given player.
*/
private boolean isPoly(int x, int y, char player) {
if (currentPoly == null)
return false;
for (int i = 0; i < currentPoly.length; i++) {
for (int j = 0; j < currentPoly[0].length; j++) {
char c = currentPoly[i][j];
if (c == '#') {
if (boardCellAt(x + i, y + j) != player) {
return false;
}
}
}
}
return true;
}
private char boardCellAt(int i, int j) {
if (i >= board.length || j >= board[0].length) {
return ' ';
}
return board[i][j];
}
/**
* Check the entire game board to see if the given player has constructed
* the polyomino.
*/
public boolean checkForWinner(char player)// Lab2
{
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[0].length; j++) {
if (isPoly(i, j, player)) {
return true;
}
}
}
return false;
}
BTW: There is a bug in printBoard. The loop should look like this:
for(int j = 0; j < board[0].length; j++)
or you get an ArrayIndexOutOfBoundsException.
Also in printBoard you should change the first print to System.out.print("|"); otherwise it looks like there are extra cells left on the board.
This is a class that creates the game connect four in console and drawing panel, and I am having trouble in the connectedFour method where it determines if someone has gotten 4 discs in a row. The problem is, is that I am not sure how to set up my for loops to check through the array for four discs in a row
Here is my code:
import java.util.*;
import java.awt.*;
public class ConnectFour{
public static void main(String[] args){
//board
DrawingPanel panel = new DrawingPanel(550,550);
int rowAvailable;
Graphics g = panel.getGraphics();
g.drawLine(0,0,0,500);
g.drawLine(0,0,500,0);
g.drawLine(500,0,500,427);
g.drawLine(0,427,500,427);
for(int i = 0; i< 6; i++){
for(int j= 0; j<= 6; j++){
g.setColor(Color.YELLOW);
g.fillRect(j*71,i*71,71,71);
g.setColor(Color.WHITE);
g.fillOval(j*71,i*71,71,71);
}
}
//setBlankArray
Scanner console = new Scanner(System.in);
char[][] board = new char[6][7];
for(int j = 0;j <= 6; j++){
for(int i= 0; i < 6; i++){
board[i][j] = ' ';
}
}
boolean isBlack = true;
boolean isRed = false;
int column = 0;
boolean playersTurn = true;
boolean rightNum = false;
//oneTurn
while(getWinner(board, playersTurn)){
//while(playersTurn == true){
rightNum = false;
if(isBlack == true){
// displayCurrentPlayer
System.out.println("Black's Turn");
g.setColor(Color.WHITE);
g.drawString("Red Disc's Turn",200, 450);
g.setColor(Color.BLACK);
g.drawString("Black Disc's Turn",200, 450);
}
else{
// displayCurrentPlayer
System.out.println("Red's Turn");
g.setColor(Color.WHITE);
g.drawString("Black Disc's Turn",200, 450);
g.setColor(Color.RED);
g.drawString("Red Disc's Turn",200, 450);
}
System.out.print("Choose a column to place your disk (1-7): ");
while(rightNum == false){
column = (console.nextInt()) -1;
if(column >= 0 && column < 7 && board[0][column] == ' '){
rightNum = true;
}
else{
System.out.print("Try again: ");
}
}
drawBoard(column, board, isBlack, isRed, board, g);
isBlack = !isBlack;
}
if(isBlack == false){System.out.println("Congratulations Black Player");}
else{System.out.println("Congratulations Red Player");}
// use the while loop to say try again if the column is filled.
}
public static void drawBoard(int column, char[][] board, boolean isBlack, boolean isRed, char[][] availability,Graphics g){
char player = ' ';
if(isBlack == true){
g.setColor(Color.BLACK);
player = 'b';
}
else{
g.setColor(Color.RED);
player = 'r';
}
int x = 0;
int row = 5;
while(board[row-x][column] != ' '){
x++;
}
row = row-x;
g.fillOval((column * 71),(row * 71), 71,71);
board[row][column] = player;
}
public static boolean getWinner(char[][] board, boolean playersTurn){
int verticalCount = 0;
boolean isVertical = false;
for(int i = 6; i >= 0; i--){
verticalCount = 0;
for(int j = 5; j > 0; j--){
if(board[j][i] == board[j-1][i] && board[j][i] != ' '){
verticalCount++;
}
if(verticalCount == 4){
isVertical = true;
}
}
}
int horizontalCount = 0;
boolean isHorizontal = false;
for(int i =1; i <= 5; i++){
for(int j =1; j<6; j++){
if(board[j][i] == board[j][i+1] && board[j][i] != ' '){
horizontalCount++;
}
if(horizontalCount == 3){
isHorizontal = true;
}
}
}
int diagonalCount = 0;
boolean isDiagonal = false;
// for(int i = 0; i<=6; i++){
// for(int j =0; j<6; j++){
// if(board[i][j-1] == board[i][j]){
// diagonalCount++;
// }
// }
// }
if(isVertical || isHorizontal || isDiagonal){
playersTurn = false;
}
else{
playersTurn = true;}
return playersTurn;
}
}
I would implement this by checking if the game-winning condition is met after a disc has been placed. This way you aren't iterating over the entire board after each move.
Regardless, try this:
replace
while (gameWon == false ){
with
while (!connectedFour(board, playersTurn)) {
I don't think this will completely fix your problems as it looks like there are a handful of other things wrong with the code you've posted.