How to make my game of life continue to the next generation? - java

Main Class
package edu.bsu.cs121.mamurphy;
public class GameOfLifeMain {
public static void main(String[] args) {
{
new GameOfLifeGUI();
System.out.println();
}
}
}
Tester Class
package edu.bsu.cs121.mamurphy;
import java.awt.Color;
import java.awt.Graphics;
import java.io.File;
import java.util.Scanner;
import javax.swing.JPanel;
public class tester extends JPanel
{
final static int ROW = 25, COL = 75;
final static char DOT = '.';
static char[][] grid = new char[ROW + 2][COL + 2];
static char[][] nextgrid = new char[ROW + 2][COL + 2];
boolean sameFlag;
boolean blankFlag;
public static void init(char[][] grid, char[][] nextgrid) {
for (int row = 0; row <= ROW + 1; row++) {
for (int col = 0; col <= COL + 1; col++) {
grid[row][col] = DOT;
nextgrid[row][col] = DOT;
}
}
}
public static void pause() {
try {
Thread.currentThread();
Thread.sleep(1000L);
} catch (InterruptedException e) {
}
}
public void begin() {
init(grid, nextgrid);
read(grid);
repaint(); // calls paintComponent
pause();
while (sameFlag == true && blankFlag == false) {
nextGen(grid, nextgrid);
}
}
public static void read(char[][] grid) {
Scanner world = new Scanner(System.in);
System.out.println("Type the file name of the world you'd like to create.");
String fileName = world.nextLine();
{
try {
world = new Scanner(new File(fileName));
} catch (Exception ex) {
System.out.println("Please insert a valid file name.");
}
for (int row = 1; row <= ROW; row++) {
String s = world.next();
for (int col = 1; col <= COL; col++) {
grid[row][col] = s.charAt(col - 1);
}
}
}
}
public void print(Graphics g) {
int x, y;
y = 20;
for (int row = 1; row <= ROW; row++) {
x = 20;
for (int col = 1; col <= COL; col++) {
g.drawString("" + grid[row][col], x, y);
x = x + 7;
}
y = y + 15;
}
}
public static int neighbors(char[][] grid, int r, int c) {
// counts the # of closest neighbors that are X's
int count = 0;
for (int row = r - 1; row <= r + 1; row++) {
for (int col = c - 1; col <= c + 1; col++) {
if (grid[row][col] == 'X') {
count++;
}
}
}
if (grid[r][c] == 'X') {
count = count - 1;
}
return count;
}
public static void nextGen(char[][] grid, char[][] nextgrid) {
for (int row = 1; row <= ROW; row++) {
for (int col = 1; col <= COL; col++) {
if (grid[row][col] == 'X') {
int count = 0;
{
if (grid[row][col - 1] == 'X')
count = count + 1;
if (grid[row][col + 1] == 'X')
count = count + 1;
if (grid[row - 1][col] == 'X')
count = count + 1;
if (grid[row - 1][col - 1] == 'X')
count = count + 1;
if (grid[row - 1][col + 1] == 'X')
count = count + 1;
if (grid[row + 1][col - 1] == 'X')
count = count + 1;
if (grid[row + 1][col] == 'X')
count = count + 1;
if (grid[row + 1][col + 1] == 'X')
count = count + 1;
}
if (count == 2 || count == 3) {
nextgrid[row][col] = 'X';
} else
nextgrid[row][col] = DOT;
}
if (grid[row][col] == DOT) {
int count1 = 0;
{
if (grid[row][col - 1] == 'X')
count1 = count1 + 1;
if (grid[row][col + 1] == 'X')
count1 = count1 + 1;
if (grid[row - 1][col] == 'X')
count1 = count1 + 1;
if (grid[row - 1][col - 1] == 'X')
count1 = count1 + 1;
if (grid[row - 1][col + 1] == 'X')
count1 = count1 + 1;
if (grid[row + 1][col - 1] == 'X')
count1 = count1 + 1;
if (grid[row + 1][col] == 'X')
count1 = count1 + 1;
if (grid[row + 1][col + 1] == 'X')
count1 = count1 + 1;
}
if (count1 == 3)
nextgrid[row][col] = 'X';
}
}
}
}
public static void copy(char[][] grid, char[][] nextgrid) {
for (int i = 0; i < ROW + 1; i++) {
for (int j = 0; j < COL + 1; j++) {
grid[i][j] = nextgrid[i][j];
}
}
}
public static boolean isEmpty(char[][] grid, char[][] nextgrid) {
boolean blankFlag = true;
for (int i = 0; i < ROW + 1; i++) {
for (int j = 0; j < COL + 1; j++) {
if (grid[i][j] != DOT) {
blankFlag = false;
}
}
}
return blankFlag;
}
public static boolean isSame(char[][] grid, char[][] nextgrid) {
boolean sameFlag = false;
for (int i = 0; i < ROW + 1; i++) {
for (int j = 0; j < COL + 1; j++) {
if (grid[i][j] == nextgrid[i][j]) {
sameFlag = true;
break;
}
}
}
return sameFlag;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);// erases panel Contents
g.setColor(Color.black);
if (sameFlag == false && blankFlag == false) {
print(g);
} else {
if (sameFlag == true) {
g.drawString("This worldis the same as the last one.", 10, 250);
}
if (blankFlag == true) {
g.drawString("Everyone died. Good job.", 10, 250);
}
}
}
}
GUI Class
package edu.bsu.cs121.mamurphy;
import javax.swing.*;
import java.awt.*;
//
public class GameOfLifeGUI extends JFrame {
public GameOfLifeGUI() {
super("Game of Life");
setSize(600, 445);
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(1, 2));
tester test1 = new tester();
test1.setBackground(Color.LIGHT_GRAY);
panel.add(test1);
setContentPane(panel);
setVisible(true);
Temp one = new Temp(test1);
one.start();
}
class Temp extends Thread {
tester anim;
public Temp(tester anim) {
this.anim = anim;
}
public void run()// for each instance of test begin will be executed
{
anim.begin();
}
}
}
Hi stackoverflow. I have been working on this game of life project for the last few days and I have hit one final wall in trying to finish it up. How do I make it proceed to the next generation?
I know for what I am required to do I need to ask the user if they wish to continue to the next generation or not. I know I need to use a scanner and then have a loop that checks to see what the user's input is, as well as a try catch to make sure the program doesn't crash if they type in anything that isn't what the program asks them to.
My only issue is that I do not know where to put this code at in my tester class (if that is actually where it needs to go).
Any help is greatly appreciated.

Related

How to output players normally in the connect four game

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();
}
}

Randomly choosing First Player in Tic Tac Toe gama java [duplicate]

This question already has answers here:
How do I generate random integers within a specific range in Java?
(72 answers)
Closed 6 years ago.
I am making a tic tac toe game and one of the requirements is to have the game randomly decide who goes first. I assume I should be using Math.random() but I don't know how to implement it. If anyone can, please help adjust my code thanks :)
import java.util.Scanner;
public class TicTacToe
{
public static void main(String[] args)
{
Scanner console = new Scanner (System.in);
Game ticTacToe = new Game();
String no = "no";
System.out.println("~~~Tic Tac Toe~~~");
System.out.println("Would you like to play?");
String playerAnswer = console.nextLine();
while(!playerAnswer.equals(no))
{
ticTacToe.play();
System.out.println("Thanks for playing");
System.out.println("Would you like to play again? Press any key for yes, type no if you don't ");
playerAnswer=console.nextLine();
}
}
}
class Game
{
private final int empty = 0;
private final int player = 1;
private final int com = 2;
private final int size = 3;
private int[][] board;
public void printScreen()
{
int col;
int row;
System.out.println();
System.out.print(" ");
for (col = 0; col < size; col ++)
{
System.out.print(" " + (col+1));
}
System.out.println();
System.out.print(" ");
for (col = 0; col < size; col ++)
{
System.out.print("--");
}
System.out.println("-");
for (row = 0; row < size; row ++)
{
System.out.print((row+1) + "|");
for (col = 0; col < size; col ++)
{
if (board[row][col] == empty)
{
System.out.print(" ");
}
else if (board[row][col] == player)
{
System.out.print("X");
}
else if (board[row][col] == com)
{
System.out.print("O");
}
System.out.print("|");
}
System.out.println();
System.out.print(" ");
for (col = 0; col < size; col ++)
{
System.out.print("--");
}
System.out.println("-");
}
}
public void clear()
{
int col;
int row;
board = new int[size][size];
for (row = 0; row < size; row ++)
{
for (col = 0; col < size; col ++)
{
board[row][col] = empty;
}
}
}
public void computerMove()
{
int col;
int row;
int count;
int select;
count = 0;
for (row = 0; row < size; row ++)
for (col = 0; col < size; col ++)
if (board[row][col] == empty)
count ++;
select = (int) (Math.random() * count);
count = 0;
for (row = 0; row < size; row ++)
{
for (col = 0; col < size; col ++)
{
if (board[row][col] == empty)
{
if (count == select)
{
board[row][col] = com;
System.out.println("The computer selects row" + (row+1) + " column " + (col+1) + ".");
}
count ++;
}
}
}
}
public void playerMove()
{
Scanner console = new Scanner (System.in);
boolean a;
int col;
int row;
a = true;
while (a)
{
System.out.println("What is your move? Select a row number from 1 to " + size + " and a column number from 1 to " + size + ".");
row = console.nextInt();
col = console.nextInt();
if ((row < 1) || (row > size) || (col < 1) || (col > size))
{
System.out.println("Invalid choice, row " + row + " or column " + col + " must be from 1 to " + size + ".");
}
else
{
row --;
col --;
if (board[row][col] != empty)
{
System.out.println("That spot is already filled");
printScreen();
}
else
{
board[row][col] =player;
a = false;
}
}
}
}
public boolean checkWinner()
{
int col;
int row;
int count;
int win;
win = empty;
for (row = 0; row < size; row ++)
{
count = 0;
if (board[row][0] != empty)
for (col = 0; col < size; col ++)
if (board[row][0] == board[row][col])
count ++;
if (count == size)
win = board[row][0];
}
for (col = 0; col < size; col ++)
{
count = 0;
if (board[0][col] != empty)
for (row = 0; row < size; row ++)
if (board[0][col] == board[row][col])
count ++;
if (count == size)
win = board[0][col];
}
count = 0;
if (board[0][0] != empty)
for (row = 0; row < size; row ++)
if (board[0][0] == board[row][row])
count ++;
if (count == size)
win = board[0][0];
count = 0;
if (board[0][size-1] != empty)
for (row = 0; row < size; row ++)
if (board[0][size-1] == board[row][size-row-1])
count ++;
if (count == size)
win = board[0][size-1];
if (win != empty)
{
if (win == player)
System.out.println("Congratz you won");
else if(win == 3)
System.out.println("you lost");
return true;
}
count = 0;
for (row = 0; row < size; row ++)
for (col = 0; col < size; col ++)
if (board[row][col] == empty)
count ++;
if (count == 0)
{
System.out.println("Its a tie!");
return true;
}
return false;
}
public void play()
{
boolean e;
clear();
e=false;
while (!e)
{
printScreen();
playerMove();
printScreen();
e = checkWinner();
if (!e)
{
computerMove();
e = checkWinner();
if (e)
printScreen();
}
}
}
}
There may be many ways to do this including using a Random generator class, but as tic-tac only has two players, this can simply be done as getting a boolean
boolean player1Starts = (System.currentTimeMillis() % 2) == 0;
To implement this you would have to change your play method.
public void play()
{
boolean playerTurn = Math.random() <= .5
//this function returns a value between 0 an 1 exclusive
clear();
printScreen();
while (!checkWinner())
{
if (playerTurn) {
playerMove;
} else {
computerMove();
}
playerTurn = !playerTurn;
printScreen();
}
}
What this does is first determine if the player starts.
Then it clears and prints the empty board.
Then It loops through checking if there is a winner
If there isn't a winner we go into the loop and then if its the players turn they move else the computer moves
Then we update the playerTurn to be the opposite of what it was.
Then print the screen to see the move.
If there is a winner we exit the loop and finish the play method

I cannot get the write to file part of the code to work

I cannot get my write to file code working the error message- writeFile cannot be resolved. I a trying to write the board positions to a text file so the game can be saved. If the user chooses to save the game then it should call a new subroutine that will write the pieces to the file.
/*
* Skeleton program code for the AQA COMP1 Summer 2016 examination
* This code to be used in conjunction with the Preliminary Material
* written by the AQA Programmer Team
* Developed in the NetBeans 7.3.1. programming environment
* Additional classes AQAConsole2016, AQAReadTextFile2016 and
* AQAWriteTextFile2016 may be used.
*
* A package name may be chosen and private and public modifiers added -
* permission to make these changes to the Skeleton Program does not need
* to be obtained from AQA or the AQA Programmer
*/
import java.util.Random;
public class Aaa {
AQAConsole2016 console = new AQAConsole2016();
Random random = new Random();
int boardSize;
public Aaa() {
char choice;
String playerName;
// int boardSize;
boardSize = 6;
playerName = "";
do {
displayMenu();
choice = getMenuChoice(playerName);
switch (choice) {
case 'p' : playGame(playerName, boardSize);
break;
case 'e' : playerName = getPlayersName();
break;
case 'c' : boardSize = changeBoardSize();
break;
}
} while (choice != 'q');
}
void setUpGameBoard(char[][] board, int boardSize) {
for (int row = 1; row <= boardSize; row++) {
for (int column = 1; column <= boardSize; column++) {
if (row == (boardSize + 1) / 2 && column == (boardSize + 1) / 2 + 1 || column == (boardSize + 1) / 2 && row == (boardSize + 1) / 2 + 1) {
board[row][column] = 'C';
} else {
if (row == (boardSize + 1) / 2 + 1 && column == (boardSize + 1) / 2 + 1 || column == (boardSize + 1) / 2 && row == (boardSize + 1) / 2) {
board[row][column] = 'H';
} else {
board[row][column] = ' ';
}
}
}
}
}
int changeBoardSize() {
int boardSize;
do {
console.print("Enter a board size (between 4 and 9): ");
boardSize = console.readInteger("");
} while (!(boardSize >= 4 && boardSize <= 9));
return boardSize;
}
int getHumanPlayerMove(String playerName) {
int coordinates;
console.print(playerName + " enter the coordinates of the square where you want to place your piece: ");
coordinates = console.readInteger("");
return coordinates;
}
int getComputerPlayerMove(int boardSize) {
return ((random.nextInt(boardSize) + 1) * 10 + (random.nextInt(boardSize) + 1));
}
boolean gameOver(char[][] board, int boardSize) {
for (int row = 1; row <= boardSize; row++) {
for (int column = 1; column <= boardSize; column++) {
if (board[row][column] == ' ')
return false;
}
}
return true;
}
String getPlayersName() {
String playerName;
console.print("What is your name? ");
playerName = console.readLine();
return playerName;
}
boolean checkIfMoveIsValid(char[][] board, int move) {
int row;
int column;
boolean moveIsValid;
row = move % 10;
column = move / 10;
moveIsValid = false;
if (((row<=boardSize) &&(row>0)) && ((column<=boardSize) && (column>0))){
if (board[row][column] == ' ') {
moveIsValid = true;
}
}
return moveIsValid;
}
int getPlayerScore(char[][] board, int boardSize, char piece) {
int score;
score = 0;
for (int row = 1; row <= boardSize; row++) {
for (int column = 1; column <= boardSize; column++) {
if (board[row][column] == piece) {
score = score + 1;
}
}
}
return score;
}
boolean checkIfThereArePiecesToFlip(char[][] board, int boardSize, int startRow, int startColumn, int rowDirection, int columnDirection) {
int rowCount;
int columnCount;
boolean flipStillPossible;
boolean flipFound;
boolean opponentPieceFound;
rowCount = startRow + rowDirection;
columnCount = startColumn + columnDirection;
flipStillPossible = true;
flipFound = false;
opponentPieceFound = false;
while (rowCount <= boardSize && rowCount >= 1 && columnCount >= 1 && columnCount <= boardSize && flipStillPossible && !flipFound ) {
if (board[rowCount][columnCount] == ' ') {
flipStillPossible = false;
} else {
if (board[rowCount][columnCount] != board[startRow][startColumn]) {
opponentPieceFound = true;
} else {
if (board[rowCount][columnCount] == board[startRow][startColumn] && !opponentPieceFound) {
flipStillPossible = false;
} else {
flipFound = true;
}
}
}
rowCount = rowCount + rowDirection;
columnCount = columnCount + columnDirection;
}
return flipFound;
}
void flipOpponentPiecesInOneDirection(char[][] board, int boardSize, int startRow, int startColumn, int rowDirection, int columnDirection) {
int rowCount;
int columnCount;
boolean flipFound;
flipFound = checkIfThereArePiecesToFlip(board, boardSize, startRow, startColumn, rowDirection, columnDirection);
if (flipFound) {
rowCount = startRow + rowDirection;
columnCount = startColumn + columnDirection;
while (board[rowCount][columnCount] != ' ' && board[rowCount][columnCount] != board[startRow][startColumn]) {
if (board[rowCount][columnCount] == 'H') {
board[rowCount][columnCount] = 'C';
} else {
board[rowCount][columnCount] = 'H';
}
rowCount = rowCount + rowDirection;
columnCount = columnCount + columnDirection;
}
}
}
void makeMove(char[][] board, int boardSize, int move, boolean humanPlayersTurn) {
int row;
int column;
row = move % 10;
column = move / 10;
if (humanPlayersTurn) {
board[row][column] = 'H';
} else {
board[row][column] = 'C';
}
flipOpponentPiecesInOneDirection(board, boardSize, row, column, 1, 0);
flipOpponentPiecesInOneDirection(board, boardSize, row, column, -1, 0);
flipOpponentPiecesInOneDirection(board, boardSize, row, column, 0, 1);
flipOpponentPiecesInOneDirection(board, boardSize, row, column, 0, -1);
}
void printLine(int boardSize) {
console.print(" ");
for (int count = 1; count <= boardSize * 2 - 1; count++) {
console.print("_");
}
console.println();
}
void displayGameBoard(char[][] board, int boardSize) {
console.println();
console.print(" ");
for (int column = 1; column <= boardSize; column++)
{
console.print(" ");
console.print(column);
}
console.println();
printLine(boardSize);
for (int row = 1; row <= boardSize; row++) {
console.print(row);
console.print(" ");
for (int column = 1; column <= boardSize; column++) {
console.print("|");
console.print(board[row][column]);
}
console.println("|");
printLine(boardSize);
console.println();
}
}
void displayMenu() {
console.println("(p)lay game");
console.println("(e)nter name");
console.println("(c)hange board size");
console.println("(q)uit");
console.println();
}
char getMenuChoice(String playerName) {
char choice;
console.print(playerName + " enter the letter of your chosen option: ");
choice = console.readChar();
return choice;
}
void playGame(String playerName, int boardSize) {
char[][] board = new char[boardSize + 1][boardSize + 1];
boolean humanPlayersTurn;
int move;
int humanPlayerScore;
int computerPlayerScore;
boolean moveIsValid;
setUpGameBoard(board, boardSize);
humanPlayersTurn = false;
int NoOfMoves=0;
do {
humanPlayersTurn = !humanPlayersTurn;
displayGameBoard(board, boardSize);
moveIsValid = false;
do {
if (humanPlayersTurn) {
move = getHumanPlayerMove(playerName);
} else {
move = getComputerPlayerMove(boardSize);
}
moveIsValid = checkIfMoveIsValid(board, move);
} while (!moveIsValid);
if (!humanPlayersTurn) {
NoOfMoves++;
console.println("The number of moves completed so far: " +NoOfMoves);
console.print("Press the Enter key and the computer will make its move");
console.readLine("");
}
makeMove(board, boardSize, move, humanPlayersTurn);
console.println();
String answer = console.readLine("Do you want to save the board? (y/n)");
if (answer.equalsIgnoreCase("y")){
writeBoard(board, boardSize);
console.println("Saved!");
}
} while (!gameOver(board, boardSize));
displayGameBoard(board, boardSize);
humanPlayerScore = getPlayerScore(board, boardSize, 'H');
computerPlayerScore = getPlayerScore(board, boardSize, 'C');
if (humanPlayerScore > computerPlayerScore) {
console.println("Well done, " + playerName + ", you have won the game!");
}
else {
if (humanPlayerScore == computerPlayerScore) {
console.println("that was a draw!");
} else {
console.println("The computer has won the game!");
}
console.println();
}
}
void writeBoard(char[][] board, int boardSize) {
String filename = "myFile.txt";
String piece = null;
writeFile.openFile(filename);
for(int row=1; row<=boardSize; row++){
for (int column = 1; column <= boardSize; column++) {
piece= Character.toString(board [row][column]);
writeFile.writeToTextFile(piece);
}
}
writeFile.closeFile();
}
public static void main(String[] args) {
new Aaa();
}
}
This Section contains the errors:
void writeBoard(char[][] board, int boardSize) {
String filename = "myFile.txt";
String piece = null;
writeFile.openFile(filename);
for(int row=1; row<=boardSize; row++){
for (int column = 1; column <= boardSize; column++) {
piece= Character.toString(board [row][column]);
writeFile.writeToTextFile(piece);
}
}
writeFile.closeFile();
}
The problematic section contains a variable named writeFile which can not be resolved. No where in the class Aaa that you have shared, neither this variable has been declared nor initialized with an instance of its type. So the method void writeBoard(char[][] board, int boardSize) gives compilation error.
From the usage of this variable it is clear that it belongs to a class which has following instance methods:
1) openFile(String filename)
2) writeToTextFile(String piece)
3) closeFile()
Please search the class which has the above methods and on finding create an instance of that as the first statement inside the method void writeBoard(char[][] board, int boardSize). Hope it helps.

I can't seem to get a working main method for my project

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();
}
}

Check for match method for 2D array 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.

Categories