Scrolling text effect on 2D array - java

For a project I am working on I would like to be abbe to "scroll" an array like so:
Here is the code I have so far:
private boolean[][] display = this.parseTo8BitMatrix("Here");
private int scroll = 0;
public void scroll() {
this.scroll++;
}
//sets the clock's display
public void setDisplay(String s) {
this.display = this.parseTo8BitMatrix(s);
}
//determines the current frame of the clock
private boolean[][] currentFrame() {
boolean[][] currentFrame = new boolean[8][32];
int length = this.display[0].length;
if(length == 32) { //do nothing
currentFrame = this.display;
} else if(length <= 24) { //center
for(int i = 0; i < 8; i++) {
for(int j = 0; j < length; j++) {
currentFrame[i][j+((32-length)/2)] = this.display[i][j];
}
}
this.display = currentFrame; //set display to currentFrame so the display doesn't get centered each time
} else { //scroll
for(int i = 0; i < 8; i++) {
for(int j = 0; j < length; j++) {
if(this.scroll+j <= 32) {
currentFrame[i][j] = this.display[i][j+this.scroll];
} else {
//?
}
}
}
}
return currentFrame;
}
The code I have is effective up until the the array needs to "wrap around" to the other side. Where have I gone wrong?

I'm assuming that you're looking for a formula that would work for the else.
Usually Modulos are very helpful for wrapping around.
What you are looking for is basically
currentFrame[i][j]= this.display[i][(j+this.scroll)%length];
which works even when it's not wrapped around.

Related

Game loop of a turn-based game

Currently, I'm working on an AI for a simple turn-based game. The way I have the game set up is as following (in pseudo-code):
players = [User, AI];
(for player : players){
player.addEventlistener(MoveListener (moveData)->move(moveData));
}
players[game.getTurn()].startTurn();
the move function:
move(data){
game.doStuff(data);
if(game.isOver())
return;
game.nextTurn();
players[game.getTurn()].startTurn();
}
This results in the following recursion:
start turn
player/AI makes a move
move function gets called
the next player starts their turn
...
This repeats until the game is over - note that the game is of finite length and doesn't go past ~50 moves. Now, even though the recursion is finite, I get a stackoverflow error. My question is: is there any way to fix this? Is there something wrong with the recursion after all? Or should I implement a game loop instead? I understand how this would work if AIs were to play against each other, but how would this work if the program had to wait for user input?
EDIT
Here are the relevant classes to the recursion:
Connect4 class:
package connect4;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.text.Text;
import javafx.stage.Stage;
public class Connect4 extends Application {
Group root = new Group();
GameSquare[][] squares;
GameButton[] buttons;
int currentTurn;
int columns = 7;
int rows = 6;
Text gameState;
Player[] players;
Game game;
#Override
public void start(Stage primaryStage) {
int size = 50;
int padding = 10;
gameState = new Text();
gameState.setX(padding);
gameState.setY((rows+1)*size+(rows+3)*padding);
root.getChildren().add(gameState);
buttons = new GameButton[columns];
for(int i = 0; i < buttons.length; i++){
buttons[i] = new GameButton(i);
buttons[i].setMaxWidth(size);
buttons[i].setMaxHeight(size);
buttons[i].setLayoutX(i*size+(i+1)*padding);
buttons[i].setLayoutY(padding);
buttons[i].setMouseTransparent(true);
buttons[i].setVisible(false);
root.getChildren().add(buttons[i]);
}
players = new Player[2];
players[0] = new UserControlled(buttons);
players[1] = new AI();
MoveListener listener = (int i) -> {move(i);};
for(Player player : players)
player.addListener(listener);
game = new Game(columns, rows, players.length);
squares = new GameSquare[columns][rows];
for(int x = 0; x < columns; x++){
for(int y = 0; y < rows; y++){
squares[x][y] = new GameSquare(
x*size+(x+1)*padding,
(y+1)*size+(y+2)*padding,
size,
size,
size,
size
);
root.getChildren().add(squares[x][y]);
}
}
players[game.getTurn()].startTurn(game);
updateTurn();
updateSquares();
draw(primaryStage);
}
public void move(int i){
game.move(i);
updateSquares();
if(game.isGameOver()){
if(game.isTie()){
tie();
return;
} else {
win();
return;
}
}
updateTurn();
players[game.getTurn()].startTurn(game);
}
private void updateSquares(){
int[][] board = game.getBoard();
for(int x = 0; x < columns; x++){
for(int y = 0; y < rows; y++){
squares[x][y].setOwner(board[x][y]);
}
}
}
private void updateTurn(){
gameState.setText("Player " + game.getTurn() + "'s turn");
}
public static void main(String[] args) {
launch(args);
}
private void draw(Stage primaryStage){
Scene scene = new Scene(root, 500, 500);
primaryStage.setScene(scene);
primaryStage.show();
}
private void win(){
gameState.setText("Player " + game.getWinner() + " has won the game!");
}
private void tie(){
gameState.setText("It's a tie!");
}
}
Game class:
package connect4;
public class Game {
private int turn = 0;
private int[][] board;
private int columns;
private int rows;
private int players;
private boolean gameOver = false;
private boolean tie = false;
private int winner = -1;
public Game(int columns, int rows, int playerCount){
this.columns = columns;
this.rows = rows;
board = new int[columns][rows];
for(int x = 0; x < columns; x++){
for(int y = 0; y < rows; y++){
board[x][y] = -1;
}
}
players = playerCount;
}
public int[][] getBoard(){
return board;
}
public int getTurn(){
return turn;
}
private void updateTurn(){
turn++;
if(turn >= players)
turn = 0;
}
public boolean isGameOver(){
return gameOver;
}
private void win(int player){
gameOver = true;
winner = player;
}
public int getWinner(){
return winner;
}
private void tie(){
gameOver = true;
tie = true;
}
public boolean isTie(){
return tie;
}
public void move(int i){
if(gameOver)
return;
if(columnSpaceLeft(i) == 0){
return;
}
board[i][columnSpaceLeft(i)-1] = turn;
checkWin(turn);
checkFullBoard();
if(gameOver)
return;
updateTurn();
}
private void checkFullBoard(){
for(int i = 0; i < columns; i++){
if(columnSpaceLeft(i) != 0)
return;
}
tie();
}
public int columnSpaceLeft(int column){
for(int i = 0; i < board[column].length; i++){
if(board[column][i] != -1)
return i;
}
return board[column].length;
}
public int[] getAvailableColumns(){
int columnCount = 0;
for(int i = 0; i < board.length; i++){
if(columnSpaceLeft(i) != 0)
columnCount++;
}
int[] columns = new int[columnCount];
int i = 0;
for(int j = 0; j < board.length; j++){
if(columnSpaceLeft(i) != 0){
columns[i] = j;
i++;
}
}
return columns;
}
private Boolean checkWin(int player){
//vertical
for(int x = 0; x < columns; x++){
int count = 0;
for(int y = 0; y < rows; y++){
if(board[x][y] == player)
count++;
else
count = 0;
if(count >= 4){
win(player);
return true;
}
}
}
//horizontal
for(int y = 0; y < rows; y++){
int count = 0;
for(int x = 0; x < columns; x++){
if(board[x][y] == player)
count++;
else
count = 0;
if(count >= 4){
win(player);
return true;
}
}
}
//diagonal
for(int x = 0; x < columns; x++){
for(int y = 0; y < rows; y++){
int count = 0;
//diagonaal /
if(!(x > columns-4 || y < 3) && board[x][y] == player){
count ++;
for(int i = 1; i <= 3; i++){
if(board[x+i][y-i] == player){
count++;
if(count >= 4){
win(player);
return true;
}
} else {
count = 0;
break;
}
}
}
//diagonal \
if(!(x > columns-4 || y > rows-4) && board[x][y] == player){
count ++;
for(int i = 1; i <= 3; i++){
if(board[x+i][y+i] == player){
count++;
if(count >= 4){
win(player);
return true;
}
} else {
count = 0;
break;
}
}
}
}
}
return false;
}
}
UserControlled class:
package connect4;
import java.util.ArrayList;
import java.util.List;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
public class UserControlled implements Player {
private List<MoveListener> listeners = new ArrayList<MoveListener>();
private GameButton[] buttons;
private boolean active = false;
public UserControlled(GameButton[] buttons){
this.buttons = buttons;
}
#Override
public void addListener(MoveListener listener){
listeners.add(listener);
}
#Override
public void startTurn(Game game){
System.out.println(0);
active = true;
for(int i = 0; i < buttons.length; i++){
if(game.columnSpaceLeft(i) != 0){
setButton(i, true);
buttons[i].setOnAction(new EventHandler<ActionEvent>() {
#Override public void handle(ActionEvent e) {
move(( (GameButton) e.getTarget()).getColumn());
}
});
}
}
}
private void move(int i){
if(!active)
return;
active = false;
disableButtons();
for(MoveListener listener : listeners)
listener.onMove(i);
}
private void disableButtons(){
for(int i = 0; i < buttons.length; i++){
setButton(i, false);
}
}
private void setButton(int i, boolean enable){
if(enable){
buttons[i].setMouseTransparent(false);
buttons[i].setVisible(true);
} else {
buttons[i].setMouseTransparent(true);
buttons[i].setVisible(false);
}
}
}
The AI class is basically the same as a stripped down UserControlled class, except the startTurn method:
int[] columns = game.getAvailableColumns();
move(columns[rng.nextInt(columns.length)]);
The MoveListener interface is very simple:
public interface MoveListener {
void onMove(int i);
}
The stack trace:
Exception in thread "JavaFX Application Thread" java.lang.StackOverflowError
at javafx.beans.property.StringPropertyBase.set(StringPropertyBase.java:142)
at javafx.beans.property.StringPropertyBase.set(StringPropertyBase.java:49)
at javafx.scene.text.Text.setText(Text.java:370)
//note that the three lines above this are different every time
//as the application crashes at a different point
at connect4.Connect4.updateTurn(Connect4.java:107)
at connect4.Connect4.move(Connect4.java:93)
at connect4.Connect4.lambda$start$0(Connect4.java:49)
at connect4.AI.move(AI.java:13)
at connect4.AI.startTurn(AI.java:24)
at connect4.Connect4.move(Connect4.java:94)
at connect4.Connect4.lambda$start$0(Connect4.java:49)
at connect4.AI.move(AI.java:13)
...etc
In general, you shouldn't use a recursion except you are pretty sure about what you are doing.
Think this, every time you call the next step, you are saving all the context, with all the local variables in the stack. In a game, it could be a lot of stuff.
A common game loop in a turn based game would be something like:
while(!gameFinished()){
for(player in players){
player.doTurn();
}
}
Take into account too, that recursion is slow, because it has to save all the context and it takes time, so, in general, think three times before trying to use a recursion.
EDIT
To process the input you could use something like this:
CompletableFuture.supplyAsync(this::waitUserInput)
.thenAccept(this::processUserInput)
Here you can find how it works:
http://www.deadcoderising.com/java8-writing-asynchronous-code-with-completablefuture/
With this, your code keeps running, so keep in mind that in the next line of code you won't have the input. When it gets the input, it will call the proccessUserInput method.
Another way to do this, is to check every frame if any key was pressed, and that's okay too.
Here you can find a way to do that:
How do I check if the user is pressing a key?
The way you should do things depends on the size of your project. If you will be checking for key presses all the time, maybe it's a good idea to build some sort of event system for that.
In the other hand, I recommend you to use a game engine like Unreal or Unity. If you want to keep with Java, there are a lot of libraries for games that handle a lot of common problems like this.
For example:
https://www.lwjgl.org/
You can find a lot of tutorials of turn-based games made with that library.
Good luck!

android compare 2 images and highlight difference

2 Images will be provided. We need to find differences between them and highlight them.
So far I have seen this solution in JAVA but as BufferedImage is not supported in android, I am unable to proceed further. I have come close to comparing pixels of 2 Bitmaps but facing issue ahead.
I have also tried comparing pixels of two bitmap, but it highlights all the non-white colors
void findDifference(Bitmap firstImage, Bitmap secondImage)
{
if (firstImage.getHeight() != secondImage.getHeight() && firstImage.getWidth() != secondImage.getWidth())
Toast.makeText(this, "Images size are not same", Toast.LENGTH_LONG).show();
boolean isSame = true;
for (int i = 0; i < firstImage.getWidth(); i++)
{
for (int j = 0; j < firstImage.getHeight(); j++)
{
if (firstImage.getPixel(i,j) == secondImage.getPixel(i,j))
{
}
else
{
differentPixels.add(new Pixel(i,j));
secondImage.setPixel(i,j, Color.YELLOW); //for now just changing difference to yello color
isSame = false;
}
}
}
imgOutput.setImageBitmap(secondImage);
}
Thanks in advance.
With the help of digital color meter I detected there is very slight difference between colors of visually looking similar images quite similar what #taarraas also suggested. so I took a threshold value and solved it like this.
private static final int threashold = 10;
void findDifference(Bitmap firstImage, Bitmap secondImage)
{
if (firstImage.getHeight() != secondImage.getHeight() || firstImage.getWidth() != secondImage.getWidth())
Toast.makeText(this, "Images size are not same", Toast.LENGTH_LONG).show();
boolean isSame = true;
for (int i = 0; i < firstImage.getWidth(); i++)
{
for (int j = 0; j < firstImage.getHeight(); j++)
{
int pixel = firstImage.getPixel(i,j);
int redValue = Color.red(pixel);
int blueValue = Color.blue(pixel);
int greenValue = Color.green(pixel);
int pixel2 = secondImage.getPixel(i,j);
int redValue2 = Color.red(pixel2);
int blueValue2 = Color.blue(pixel2);
int greenValue2 = Color.green(pixel2);
if (Math.abs(redValue2 - redValue) + Math.abs(blueValue2 - blueValue) + Math.abs(greenValue2 - greenValue) <= threashold)
// if (firstImage.getPixel(i,j) == secondImage.getPixel(i,j))
{
}
else
{
differentPixels.add(new Pixel(i,j));
secondImage.setPixel(i,j, Color.YELLOW); //for now just changing difference to yello color
isSame = false;
}
}
}
imgOutput.setImageBitmap(secondImage);
}
Comparing the images pixel by pixel you can do it like this:
private void findDifference(Bitmap firstImage, Bitmap secondImage) {
Bitmap bmp = secondImage.copy(secondImage.getConfig(), true);
if (firstImage.getWidth() != secondImage.getWidth()
|| firstImage.getHeight() != secondImage.getHeight()) {
return;
}
for (int i = 0; i < firstImage.getWidth(); i++) {
for (int j = 0; j < firstImage.getHeight(); j++) {
if (firstImage.getPixel(i, j) != secondImage.getPixel(i, j)) {
bmp.setPixel(i, j, Color.YELLOW);
}
}
}
imgOutput.setImageBitmap(bmp);
}

Movement restriction on GridLayout to only adjacent grid buttons

I am making a game where move across a gridlayout of jbuttons, only allowing movement to adjacent grid jbuttons. The goal is to try and make it to the topleft (From the btm right). I think this is all that is relevant:
//Here is my method to determine whether it is a valid move (i dont want you to be able to move anywhere but adjacent spots
public boolean goodMove(int x, int y) {
int val = Math.abs(current.x - x) + Math.abs(current.y - y);
return val == 1;
}
//Here is the logic in the actionlister, a big if else loop that is now referencing only the jbuttons in my gridlayout (the game panel)
public void actionPerformed(ActionEvent e) {
JButton clicked = (JButton) e.getSource();
if (clicked == SHOWMINES) {
if (SHOWMINES.getText().equals("Show Mines")) {
showMines();
SHOWMINES.setText("Hide Mines");
} else {
hideMines();
}
} else {
if (clicked == NEWGAME) {
newGame();
} else {
if (clicked == SHOWPATH) {
if (SHOWPATH.getText().equals("Show Path")) {
showPath();
SHOWPATH.setText("Hide Path");
} else {
hidePath();
}
} else {
if (clicked == OKAY) {
resetGridSize(Integer.parseInt(gridSizeInput.getText()));
newGame();
} else {
}
int gs = Integer.parseInt(gridSizeInput.getText());
for (int i = 0; i < gs - 1; i++) {
for (int j = 0; j < gs - 1; j++) {
if (clicked == grid[i][j]) {
if (goodMove(i, j)) {//debug tester ,this is where the problem is.
System.out.println("TEST");
current = new Point(i, j);
grid[i][j].setBackground(Color.green);
grid[i][j].setText("=");
}else{System.out.println("TEST2");}
}
}
}
}
}
}
}// end of action listener
Grid[][] is my array of grid buttons, gridSizeInput is the textfield that you can adjust the gridsize in.
Thanks in advance (I'm new to programming, so keep it simple if you can :)
EDIT: I forgot to mention, it is not recognizing my if(goodMove()) loop, its just printing out TWO for my else.
EDIT: My question is why is not working, no buttons will are be recognized as clicked in my grid, I guess I am asking to see if something I have written is glaringly obviously wrong. thanks.
EDIT: Okay here is my entire action listener for all my buttons. This is my first post, sorry I am not more helpful- let me know if anything else I can add.
Your problem may be as simple as your not extending your for loops out far enough. Try changing this:
for (int i = 0; i < gs - 1; i++) {
for (int j = 0; j < gs - 1; j++) {
to this:
for (int i = 0; i < gs; i++) {
for (int j = 0; j < gs; j++) {
Edit
This was the minimal code example that I created to test the concept:
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.Point;
import java.awt.event.*;
import javax.swing.*;
public class Foo extends JPanel {
public static final int GRID_SIZE = 10;
private Point current;
private JButton[][] grid;
public Foo() {
ButtonListener listener = new ButtonListener();
setLayout(new GridLayout(GRID_SIZE, GRID_SIZE));
grid = new JButton[GRID_SIZE][GRID_SIZE];
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; j++) {
grid[i][j] = new JButton(" ");
grid[i][j].addActionListener(listener);
add(grid[i][j]);
}
}
current = new Point(GRID_SIZE - 1, GRID_SIZE - 1);
}
private class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
JButton clicked = (JButton) e.getSource();
// !! int gs = Integer.parseInt(gridSizeInput.getText());
int gs = GRID_SIZE;
// !! for (int i = 0; i < gs - 1; i++) {
// for (int j = 0; j < gs - 1; j++) {
for (int i = 0; i < gs; i++) {
for (int j = 0; j < gs; j++) {
if (clicked == grid[i][j]) {
if (goodMove(i, j)) {
System.out.println("TEST");
current = new Point(i, j);
grid[i][j].setBackground(Color.green);
grid[i][j].setText("=");
} else {
System.out.println("TEST2");
}
}
}
}
}
}
public boolean goodMove(int x, int y) {
int val = Math.abs(current.x - x) + Math.abs(current.y - y);
return val == 1;
}
private static void createAndShowGui() {
Foo mainPanel = new Foo();
JFrame frame = new JFrame("Foo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}

2d Array of objects not retaining values

I am a beginner android "developer" developing a chess app.
There is one variable in the InGameActivity class called currentBoardState which is public static. Every ChessPiece has a boolean[][] possibleMoves. This following method will take the possibleMoves and determine if any of the moves will cause the player to put him/herself in check and set it to false because it is no longer a possible move.
#Override
public void eliminateMovesThatPutYouInCheck() {
ChessPiece[][] originalBoard = InGameActivity.currentBoardState;
final ChessPiece emptyPiece = new EmptyPiece(Color.EMPTY);
final ChessPiece tempKnight = new Knight(side);
//This block eliminates moves that will cause a player
//to put him/her self in check.
InGameActivity.currentBoardState[x][y] = emptyPiece;
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
if (possibleMoves[i][j] == true) {
tempKnight.x = i;
tempKnight.y = j;
InGameActivity.currentBoardState[i][j] = tempKnight;
if (InGameActivity.isPlayerInCheck(side)) {
possibleMoves[i][j] = false;
}
InGameActivity.currentBoardState[i][j] = emptyPiece;
}
}
}
InGameActivity.currentBoardState = originalBoard;
}
The problem is, my currentBoardState variable is being messed up and I dont know why, ive saved the value then reset it at the end of the method why is it losing its values?
EDIT: Here is the isPlayerInCheck method if you need it, thank you.
public static boolean isPlayerInCheck(Color side) {
List<boolean[][]> opponentsMoves = new ArrayList<boolean[][]>();
int xKing = -1;
int yKing = -1;
if (side.equals(Color.WHITE)) {
xKing = whiteKing.x;
yKing = whiteKing.y;
} else {
xKing = blackKing.x;
yKing = blackKing.y;
}
if (side.equals(Color.WHITE)) {
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
if (currentBoardState[i][j].isBlack()) {
opponentsMoves.add(currentBoardState[i][j].possibleMoves);
}
}
}
for (boolean[][] b : opponentsMoves) {
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
if (b[xKing][yKing] == true) {
return true;
}
}
}
}
return false;
} else {
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
if (currentBoardState[i][j].isWhite()) {
opponentsMoves.add(currentBoardState[i][j].possibleMoves);
}
if (currentBoardState[i][j].isBlack() && currentBoardState[i][j].getType().equals(Type.KING)) {
xKing = currentBoardState[i][j].x;
yKing = currentBoardState[i][j].y;
}
}
}
for (boolean[][] b : opponentsMoves) {
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
if (b[xKing][yKing] == true) {
return true;
}
}
}
}
return false;
}
}
Also, I understand and appreciate that my code is probably very inefficient and the design is horrible for chess but that isn't really what I am concerned about at the moment.
I'm assuming by messed up you mean the currentBoardState variable isn't being "reset" to the original board.
This is due to this line:
ChessPiece[][] originalBoard = InGameActivity.currentBoardState;
passing a reference of the current board state to the variable originalBoard.
As you make you modification to currentBoardState, since the originalBoard variable points to the same object, it gets modified as well.
Copy the array to the originalBoard variable like such:
ChessPiece[][] originalBoard = new ChessPiece[InGameActivity.currentBoardState.length][];
for(int i = 0; i < InGameActivity.currentBoardState.length; i++){
ChessPiece[] pieces = InGameActivity.currentBoardState[i];
int len = pieces.length;
originalBoard[i] = new ChessPiece[len];
System.arraycopy(pieces, 0, originalBoard[i], 0, len);
}
//Rest of code here...
Only when you copy by value does a actual copy of the data exist. Disregarding primitive types and some immutable data, using the assignment operator = merely assigns the reference of the RHS to the LHS.
If I understand your code correctly, I think you need to copy the original to a new array, for example:
ChessPiece[][] originalBoard = Arrays.copyOf(
InGameActivity.currentBoardState, InGameActivity.currentBoardState.length);
This prevents modification of the original array.
You have the problem here:
if (possibleMoves[i][j])
{
tempKnight.x = i;
tempKnight.y = j;
InGameActivity.currentBoardState[i][j] = tempKnight;
if (InGameActivity.isPlayerInCheck(side))
{
possibleMoves[i][j] = false;
}
/** whatever was before next line resets the value at i,j: puts empty piece here */
InGameActivity.currentBoardState[i][j] = emptyPiece;
}

How to find all connected numbers in an array?

Hey all, back again. Working on a dungeon generator and I'm actually surprising myself with the progress. Yet I still have a straggling room every now and then. I was wondering if there was a way to loop through an array and see if all the '1s' (the floor tiles) are connected, and if not, how to connect them.
Thanks!
EDIT: The array is randomly filled with rooms and corridors; here's the code:
import java.util.Random;
public class Level
{
Random random = new Random();
int[][] A = new int[100][100];
int minimum = 3;
int maximum = 7;
int xFeature = 0;
int yFeature = 0;
private void feature()
{
int i = 0;
while(i>=0)
{
xFeature = random.nextInt(100-1) + 1;
yFeature = random.nextInt(100-1) + 1;
if(A[xFeature][yFeature]==1)//||A[xFeature++][yFeature]==1||A[xFeature][yFeature--]==1||A[xFeature][yFeature++]==1)
break;
i++;
}
}
private void room()
{
int safeFall = 0;
int xCoPLUS = minimum + (int)(Math.random()*minimum);
int yCoPLUS = minimum + (int)(Math.random()*minimum);
if(yCoPLUS >= xCoPLUS)
{
for(int across = xFeature; across < xFeature+xCoPLUS+2; across++)
{
for(int vert = yFeature; vert < yFeature+yCoPLUS+1; vert++)
{
if(A[vert][across] == 0)
safeFall++;
else
break;
}
}
}
if(yCoPLUS < xCoPLUS)
{
for(int across = xFeature; across < xFeature+xCoPLUS+1; across++)
{
for(int vert = yFeature; vert < yFeature+yCoPLUS+2; vert++)
{
if(A[vert][across] == 0)
safeFall++;
else
break;
}
}
}
if((safeFall== (xCoPLUS+1) * (yCoPLUS+2)) || ((safeFall== (xCoPLUS+2) * (yCoPLUS+1))))
{
for(int across = xFeature; across < xFeature+xCoPLUS; across++)
{
for(int vert = yFeature; vert < yFeature+yCoPLUS; vert++)
{
A[vert][across] = 1;
}
}
}
}
private void corridor()
{
int xCoONE = xFeature;
int yCoONE = yFeature;
int xCoTWO = random.nextInt(10)+10;
int yCoTWO = random.nextInt(10)+10;
while(xCoONE > xCoTWO)
{
A[xCoONE][yCoONE] = 1;
xCoONE--;
}
while(xCoONE < xCoTWO)
{
A[xCoONE][yCoONE] = 1;
xCoONE++;
}
while(yCoONE > yCoTWO)
{
A[xCoONE][yCoONE] = 1;
yCoONE--;
}
while(yCoONE < yCoTWO)
{
A[xCoONE][yCoONE] = 1;
yCoONE++;
}
}
public Level()
{
firstroom();
for(int i = 0; i < 500; i++)
{
int x = random.nextInt(50);
feature();
if(x > 1)
room();
else
corridor();
}
troubleShoot();
}
So basically what happens when I create an object of this class is that a 100x100 array is filled with corridors and rooms determined by a random number. (well, a couple of them) But with how I have my room non-overlapping failsafe (safeFall in room()), I get stuck with a room that is one title out of reach every now and then.
The article Maze Generation Algorithm discusses several approaches to generating a maze. It includes links to Java examples.

Categories

Resources