how to output a grid of ovals from a 2d array [duplicate] - java

I am currently making an android app which plays the puzzle game hashi. I am currently struggling to output the game grid. i want to output a 2d array like bellow-
1 0 0 0 1
0 2 0 0 2
2 0 3 0 1
0 0 0 0 0
0 0 2 0 2
however when i run the application in the emulator it outputs just a blank white screen.
main activity-
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new boardView(this));
//sets the view to the board view to show the puzzle on open.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
game board class-
public class boardView extends View {
public float IslandX;
public float IslandY;
public int islandDiameter;
private Canvas canvas;
public boardView(Context context) {
super(context);
}
int gameBoard[][] = {{0, 1, 0, 0, 1}, {0, 2, 0, 0, 2}, {2, 0, 3, 0, 1}, {0, 0, 0, 0, 0}, {0, 0, 2, 0, 2}};
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
public void DrawBoard(Canvas canvas){
Paint Island = new Paint();
Island.setStyle(Paint.Style.FILL);
Island.setStyle(Paint.Style.FILL);
float stepX = canvas.getWidth() / 5.f;
float stepY = canvas.getHeight() / 5.f;
for (int i = 0; i < 5; i++) {
for (int R = 0; R < 5; R++) {
IslandX = i * stepX;
IslandY = R * stepY;
if (gameBoard[i][R] == 0) {
Island.setColor(Color.BLUE);
canvas.drawOval(IslandX, IslandY, 50, 50, Island);
} else if (gameBoard[i][R] == 1) {
Island.setColor(Color.BLACK);
canvas.drawOval(IslandX, IslandY, 50, 50, Island);
} else if (gameBoard[i][R] == 2) {
Island.setColor(Color.BLUE);
canvas.drawOval(IslandX, IslandY, 50, 50, Island);
}
}
}
}
}

To make your board visible, you have to move your code from Drawboard to the overwritten method onDraw and in the onCreate method, you have to call invalidate() on an instance of the class boardView, that calls the onDraw method to update the screen, if visible.

Related

android tile game not outputting map

I am making a tile based game in Android Studio. I want the map to output circles (islands) if it loops past a 1, and the circle should be in the correct grid coordinates however when I run it nothing happens at all.
int gameBoard[][] = {{1, 0, 1, 0, 0}, {0, 2, 0, 0, 2}, {2, 0, 3, 0, 1}, {0, 0, 0, 0, 0}, {0, 0, 2, 0, 2}};
public void onDraw(Canvas canvas) {
for (int i = 0; i < 4; i++) {
for (int R = 0; R < 4; R++) {
if (gameBoard[i][R] == 1) {
Paint Blue = new Paint();
Blue.setColor(Color.BLUE);
canvas.drawCircle(i, R, 10, Blue);
}
}
}
}
Along with color, you also need to set a few other things:
paint.setStyle(Paint.Style.STROKE);
or
paint.setStyle(Paint.Style.FILL);
It's possible that your onDraw method isn't being called. If adding the paint style doesn't fix your problem entirely, you should probably verify that onDraw is being called with a log at the beginning of the method.

hashi a puzzle game, how to output the puzzle [duplicate]

I am making a tile based game in Android Studio. I want the map to output circles (islands) if it loops past a 1, and the circle should be in the correct grid coordinates however when I run it nothing happens at all.
int gameBoard[][] = {{1, 0, 1, 0, 0}, {0, 2, 0, 0, 2}, {2, 0, 3, 0, 1}, {0, 0, 0, 0, 0}, {0, 0, 2, 0, 2}};
public void onDraw(Canvas canvas) {
for (int i = 0; i < 4; i++) {
for (int R = 0; R < 4; R++) {
if (gameBoard[i][R] == 1) {
Paint Blue = new Paint();
Blue.setColor(Color.BLUE);
canvas.drawCircle(i, R, 10, Blue);
}
}
}
}
Along with color, you also need to set a few other things:
paint.setStyle(Paint.Style.STROKE);
or
paint.setStyle(Paint.Style.FILL);
It's possible that your onDraw method isn't being called. If adding the paint style doesn't fix your problem entirely, you should probably verify that onDraw is being called with a log at the beginning of the method.

Java Linear Regression

I need to find the best fitting regression line for a set of points.
For example for this matrix:
int b [][] = { { 3, 1, 0, 0, 0, 0, 0, 0, 0 },
{ 1, 2, 3, 1, 0, 1, 0, 0, 0 },
{ 0, 1, 2, 1, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 3, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 1, 3, 0, 0 },
{ 0, 0, 0, 0, 0, 1, 2, 3, 1 },
{ 0, 0, 0, 0, 0, 1, 1, 1, 2 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 1 } };
Every number represents the amount of data points (weight I suppose) at that location (where rows are the X axis and Columns are for the Y).
I have attempted to use the SimpleRegression class from the apache mathematics library and am having some issues.
First, it doesn't appear to support weights. Second I believe that I'm doing something wrong, even for a matrix that is nothing but 1's on the main diagonal the slope/intercept results make no sense.
public static void main(String[] args) {
double a[][] = new double[9][9];
for (int i = 0; i < 9; i++)
a[i][i] = 1;
SimpleRegression r = new SimpleRegression(true);
r.addData(a);
System.out.println("Slope = " + r.getSlope());
System.out.println("Intercept = " + r.getIntercept());
}
This gives me results that are incorrect. I would assume that this matrix represents the function f(x) = x yet the slope I'm getting is -0.12499..
Could anyone point me at what I'm doing wrong?
I have a feeling I'm not only misusing the code but also the mathematics.
As the comments say, addData() expects a 2xN matrix of x y positions or individual x y positions. The following example returns a slope of 1 for a diagonal matrix as expected:
public static void main(String[] args) {
double a[][] = new double[9][9];
for (int i = 0; i < 9; i++)
a[i][i] = 1;
SimpleRegression r = new SimpleRegression(true);
addData(r, a);
System.out.println("Slope = " + r.getSlope());
System.out.println("Intercept = " + r.getIntercept());
}
public static void addData(SimpleRegression r, double[][] data) {
for(int x=0; x<data.length; x++) {
for(int y=0; y<data[0].length; y++) {
for(int i=0; i<data[x][y]; i++) {
r.addData(x, y);
}
}
}
}
The example assumes that index 0 corresponds to a position of 0, index 1 corresponds to a position of 1 and so on. If this is not the case you need to add a function to transform index to position.

Self Traversing Pacman

How to add multiple finish line in traverse? example the player needs to go to the 1st finish line, then to next, then up to the last. this is the code. i want to have 1 up to 4 traversing point. this is the code. i dunno where to put the statement.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class MazeSearchGUI extends JPanel implements ActionListener, Runnable {
private static final long serialVersionUID = 1L;
private final int WALL = 0; // A wall position value
private final int EMPTY = 1; // An empty position value
private final int TRIED = 3; // Previously tried path value
private final int PATH = 7; // Successful path value
private final int HEADERSZ = 60; // Height in header area
private int width, height; // Width and Height
private Image brick; // Brick images for walls
private Image flag; // Flag finish line images
private Image mole; // Flag finish line images
private int brickWidth, brickHeight; // Brick dimensions
private int flagWidth, flagHeight; // Flag image dimensions
private int moleWidth, moleHeight; // Flag image dimensions
private Color backCol = Color.white; // Header background color
private Color mazeCol = Color.yellow; // Maze background color
private Color triedCol = Color.lightGray; // Tried path color
private Color successCol = Color.green; // Successful path color
private Timer timer; // Timer to start game
private int startDelay = 3000; // Delay to start traversal
private int stepDelay = 1000; // Delay between each step
private static JPanel mainPanel; // Main game panel
private static String headLabel; // String at top
private static boolean success = false; // Flags successful path
private static int xPos, yPos; // Current position
// Data structure of Grid
private static int[][] grid = { { 1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1 },
{ 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0, 0, 1 },
{ 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0 },
{ 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1 },
{ 1, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1 },
{ 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1 },
{ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } };
// No Arg Constructor - the thread process runs this
public MazeSearchGUI() {
}
// One Arg Constructor - main panel process runs this
public MazeSearchGUI(String label) {
headLabel = label;
backCol = new Color(255, 182, 193);
xPos = 0;
yPos = 0;
brick = new ImageIcon("brick.png").getImage();
flag = new ImageIcon("flag.png").getImage();
mole = new ImageIcon("mole.png").getImage();
MediaTracker track = new MediaTracker(this);
track.addImage(brick, 0);
track.addImage(flag, 0);
track.addImage(mole, 0);
try {
track.waitForAll();
} catch (InterruptedException e) {
}
brickWidth = brick.getWidth(null);
brickHeight = brick.getHeight(null);
flagWidth = flag.getWidth(null);
flagHeight = flag.getHeight(null);
moleWidth = mole.getWidth(null);
moleHeight = mole.getHeight(null);
width = brickWidth * grid[0].length;
height = brickHeight * grid.length + HEADERSZ;
setBackground(backCol);
setPreferredSize(new Dimension(width, height));
setFocusable(true);
timer = new Timer(startDelay, this);
timer.start();
}
// runs once just to start the traversal thread
public void actionPerformed(ActionEvent event) {
timer.stop();
(new Thread(new MazeSearchGUI())).start();
}
// starts the traversal thread
public void run() {
if (traverse(0, 0)) {
success = true;
headLabel = "I Found A Way Out!";
mainPanel.repaint();
// JOptionPane.showMessageDialog(null,"A successful path was found!");
} else {
headLabel = "There's No Way Out!";
mainPanel.repaint();
// JOptionPane.showMessageDialog(null,"There is no way out of this maze!");
}
}
// Updates the window
public void paintComponent(Graphics page) {
super.paintComponent(page);
page.setColor(backCol);
page.fillRect(0, 0, width, HEADERSZ);
page.setColor(mazeCol);
page.fillRect(0, HEADERSZ, width, height - HEADERSZ);
page.setColor(Color.black);
page.setFont(new Font("Arial", Font.BOLD, 24));
FontMetrics metrics = page.getFontMetrics();
int labelWidth = metrics.stringWidth(headLabel);
page.drawString(headLabel, (width - labelWidth) / 2, HEADERSZ - 20);
page.drawImage(flag, grid[0].length * brickWidth
- (brickWidth + flagWidth) / 2, height
- (brickHeight + flagHeight) / 2, null);
for (int row = 0; row < grid.length; ++row) {
for (int col = 0; col < grid[row].length; ++col) {
if (grid[row][col] == WALL)
page.drawImage(brick, col * brickWidth, row * brickHeight
+ HEADERSZ, null);
else if (success) {
if (grid[row][col] == PATH) {
page.setColor(successCol);
page.fillRect(col * brickWidth, row * brickHeight
+ HEADERSZ, brickWidth, brickHeight);
}
} else if (grid[row][col] == TRIED
&& (row != yPos || col != xPos)) {
page.setColor(triedCol);
page.fillRect(col * brickWidth, row * brickHeight
+ HEADERSZ, brickWidth, brickHeight);
}
}
}
page.drawImage(mole, (xPos + 1) * brickWidth - (brickWidth + moleWidth)
/ 2, HEADERSZ + (yPos + 1) * brickHeight
- (brickHeight + moleHeight) / 2, null);
}
// Attempts to recursively traverse the maze. Inserts special
// characters indicating locations that have been tried and that
// eventually become part of the solution.
public boolean traverse(int row, int col) {
boolean done = false;
if (valid(row, col)) {
pause(stepDelay); // half second waits
xPos = col;
yPos = row;
grid[row][col] = TRIED; // this cell has been tried
mainPanel.repaint();
if (row == grid.length - 1 && col == grid[0].length - 1)
done = true; // the maze is solved
else {
done = traverse(row + 1, col); // down
if (!done)
done = traverse(row, col + 1); // right
if (!done)
done = traverse(row - 1, col); // up
if (!done)
done = traverse(row, col - 1); // left
}
if (done) // this location is part of the final path
grid[row][col] = PATH;
}
return done;
}
// Determines if a specific location is valid.
private boolean valid(int row, int col) {
// check if cell is in the bounds of the matrix
if (row >= 0 && row < grid.length && col >= 0 && col < grid[row].length)
// check if cell is not blocked and not previously tried
if (grid[row][col] == EMPTY)
return true;
return false;
}
public void pause(long millisecs) {
try {
Thread.sleep(millisecs);
} catch (InterruptedException e) {
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("Maze Search GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainPanel = new MazeSearchGUI("Trying To Traverse This Maze...");
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setVisible(true);
}
}
Your code seems pretty procedural (meaning you have lots of code in a single class, without having different objects with state and behaviour). Applying changes will be very difficult and complex. Try to write object oriented code with different classes, each having their own state and responsibility.
This way you could have one class for the character sprite, one for the grid, one for the traversing points. If you want the points to have a certain order in which they need to be visited, an option would be to implement the state pattern.
Have a look at this https://en.wikipedia.org/wiki/State_pattern
and this http://gameprogrammingpatterns.com/state.html for the state pattern.
For more specific answers, please reduce your code example to the minimum needed to understand your question, and provide more information about the game itself.

tiled map in java from array

I am attempting to iterate through a 2D array of integers to generate a tiled map using Java's Graphics2D.
int[][] mapArray = {{1, 1, 1, 1, 1, 1, 1, 1},
{1, 0, 0, 0, 0, 0, 0, 1},
{1, 0, 0, 0, 0, 0, 0, 1},
{1, 0, 0, 0, 0, 0, 0, 1},
{1, 0, 0, 0, 0, 0, 0, 1},
{1, 1, 1, 1, 1, 1, 1, 1}};
public void draw(Graphics2D g2d){
for(int y = 0; y < mapArray.length; y++){
for(int x = 0; x < mapArray[0].length; x++){
if(mapArray[x][y] == 1){
ImageIcon ic = new ImageIcon("/Textures/stone.jpg");
g2d.drawImage(ic.getImage(), x, y, null);
}
else if(mapArray[x][y] == 0){
ImageIcon ic = new ImageIcon("/Textures/water.jpg");
g2d.drawImage(ic.getImage(), x, y, null);
}
I just can't seem to wrap my head around the logic of iterating a 2D array. Ideally, each 0 would represent a water tile while each 1 would represent a stone tile. Every time I run this I get a NullPointerException.
x and y are wrong way around
public void draw(Graphics2D g2d){
for(int y = 0; y < mapArray.length; y++){
for(int x = 0; x < mapArray[y].length; x++){ //you want to use y here not 0
if(mapArray[y][x] == 1){ //first box is outer array second is inner one
ImageIcon ic = new ImageIcon("/Textures/stone.jpg");
g2d.drawImage(ic.getImage(), x, y, null);
} else if(mapArray[y][x] == 0){
ImageIcon ic = new ImageIcon("/Textures/water.jpg");
g2d.drawImage(ic.getImage(), x, y, null);
}
}
}
}
I could see potentially two big issues in your code, in your code "y" represents rows and "x" represents columns but in your if statement you are picking [column][row] and while having a dry run you are probabily counting [row][column] and secondly you are always counting columns that are present in first row. if your data structure is always nXn in such case it will work but in any other case you would have different results and you might encounter ArrayIndexOutofBound exception.

Categories

Resources