I am writing the code for connect four game.
I am using color as indicators for winners; however, "tie game" continously appears and no winners are identified even if there is a winner.
I am still learning java so I am not entirely confident with the language. Here is my code mainly.
public static class MultiDraw extends JPanel implements MouseListener {
int startX = 10;
int startY = 10;
int cellWidth = 40;
int turn = 2;
int rows = 6;
int cols = 7;
boolean Go = true;
Object winner;
String playerOne = playernames(1);
String playerTwo=playernames(2);
Color c1 = new Color(255,0,0);
Color c2 = new Color(0,255,0);
Color[][] grid = new Color[rows][cols];
Color winner_color;
public MultiDraw(Dimension dimension) {
setSize(dimension);
setPreferredSize(dimension);
addMouseListener(this);
int x = 0;
for (int row = 0; row < grid.length; row++) {
for (int col = 0; col < grid[0].length; col++) {
grid[row][col] = new Color (255, 255, 255);
}
}
}
#Override
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
Dimension d = getSize();
g2.setColor(new Color(0, 0, 0));
g2.fillRect(0,0,d.width,d.height);
startX = 0;
startY = 0;
for (int row = 0; row < grid.length; row++) {
for (int col = 0; col < grid[0].length; col++) {
g2.setColor(grid[row][col]);
g2.fillOval(startX, startY, cellWidth, cellWidth);
startX = startX + cellWidth;
}
startX = 0;
startY = startY +cellWidth;
}
g2.setColor(new Color(255, 255, 255));
if (turn%2==0){
g2.drawString(playerOne,400,20);
}else{
g2.drawString(playerTwo, 400, 20);
}
}
public void mousePressed(MouseEvent e) {
int x = e.getX();
int y = e.getY();
int xSpot = x/cellWidth;
int ySpot = y/cellWidth;
//play a turn
//while (turn <= 42){
ySpot= testForOpenSpot(xSpot);
if(ySpot<0){
System.out.println("Not a valid entry");
}else{
grid[ySpot][xSpot]= c2;
if (turn%2==0){
grid[ySpot][xSpot]= c1;
checkWinner(c1, grid);
checkWinner(c2, grid);
}else{
grid[ySpot][xSpot]= c2;
checkWinner(c1, grid);
checkWinner(c2, grid);
}
turn++;
}
repaint();
print_player(winner_color, c1, c2);
}
public String playernames(int i){
Scanner scan = new Scanner(System.in);
System.out.println("Enter the name of the" + i + " player:");
String playerOne = scan.nextLine();
return playerOne;
}
public Color checkWinner(Color c, Color[][] grid){
//check right and left
for(int row = 0; row<grid.length; row++){
for (int col = 0;col < grid[0].length - 3;col++){
if (grid[row][col].equals(c) &&
grid[row][col+1].equals(c)&&
grid[row][col+2].equals(c)&&
grid[row][col+3].equals(c)){
return c ;
}
}
}
//check for 4 up and down
for(int row = 0; row < grid.length - 3; row++){
for(int col = 0; col < grid[0].length; col++){
if (grid[row][col] == c &&
grid[row][col+1] == c &&
grid[row][col+2] == c &&
grid[row][col+3] == c){
return c;
}
}
}
//check upward diagonal
for(int row = 3; row < grid.length; row++){
for(int col = 0; col < grid[0].length - 3; col++){
if (grid[row][col] == c &&
grid[row-1][col+1] == c &&
grid[row-2][col+2] == c &&
grid[row-3][col+3] == c){
return c;
}
}
}
//check downward diagonal
for(int row = 0; row < grid.length - 3; row++){
for(int col = 0; col < grid[0].length - 3; col++){
if (grid[row][col].equals(c) &&
grid[row+1][col+1].equals(c) &&
grid[row+2][col+2].equals(c) &&
grid[row+3][col+3].equals(c)){
return c;
}
}
}
return new Color(255,255,255);
}
public void print_player(Color winner_color, Color c1, Color c2){
//determine if winner is color1(first player):
winner_color = checkWinner(c1,grid);
//determine if winner is color2 (2nd player):
winner_color = checkWinner(c2,grid);
if (winner_color == c1){
System.out.println("Winner is first player");}
else if (winner_color == c2){
System.out.println("Winner is 2nd player");}
else{
System.out.println("Tie game");
}
}
public int testForOpenSpot(int xSpot){
int ySpot = rows-1;
while (!(grid[ySpot][xSpot].equals(new Color(255,255,255))|| ySpot<0)){
ySpot--;
}
return ySpot;
}
I keep on getting this error while running the code:
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 6
One of the loops for your array is going out of bounds. Step through your code and see where it is stepping out of bounds. This error can easily be fixed by stepping through your code and seeing when it happens.
Related
I'm trying to set up a depth system of sorts in processing.
The goal is for it to function similar to a (Windows) window.
I have a class called 'Window' and that can take some arguments and it will successfully draw a window that can be dragged around.
The depth system works as it stands right now. I can't click on windows 'under' the current window and if I click on another window, the order of the windows is switched correctly.
The problem is that whenever I switch between windows, the previously selected window flashes (is not drawn) for a frame, and then appears again.
I cannot work out why this happens at all. Here's my code, let me know if you need any further info.
Windows.pde:
Window[] wins;
int win_count = 0;
boolean win_drag = false;
int win_selected = 2;
void setup()
{
size(800, 600);
wins = new Window[3];
wins[0] = new Window("Test", 20, 20, 300, 200);
wins[1] = new Window("Test 2", 20, 260, 350, 225);
wins[2] = new Window("Test 3", 400, 20, 250, 150);
}
void draw()
{
background(10);
for (int i = 0; i < wins.length; i ++)
{
wins[i].draw_window();
}
}
void bringToTop(Window winID)
{
Window[] new_wins;
new_wins = new Window[wins.length];
int win_pos = -1;
for (int i = 0; i < wins.length; i ++)
{
if (wins[i] == winID)
{
win_pos = i;
break;
}
}
arrayCopy(wins, 0, new_wins, 0, win_pos);
arrayCopy(wins, win_pos + 1, new_wins, win_pos, wins.length - win_pos - 1);
new_wins[wins.length - 1] = winID;
arrayCopy(new_wins, wins);
}
boolean isOnTop(Window winID)
{
int win_pos = -1;
for (int i = 0; i < wins.length; i ++)
{
if (wins[i] == winID)
{
win_pos = i;
break;
}
}
Window[] top_wins;
top_wins = new Window[wins.length];
int winTopCount = 0;
for (int i = 0; i < wins.length; i ++)
{
if (mouse_in_rect(wins[i].winX, wins[i].winY, wins[i].winW, wins[i].winH + 24))
{
top_wins[winTopCount] = wins[i];
winTopCount ++;
}
}
int last_real_win = -1;
for (int i = 0; i < top_wins.length; i ++)
{
if (top_wins[i] != null)
{
last_real_win = i;
}
}
return (wins[win_pos] == top_wins[last_real_win]);
}
WindowObj.pde:
class Window
{
String winT;
int winX;
int winY;
int winW;
int winH;
boolean dragging;
int winXOff;
int winYOff;
int winTH;
int my_id;
Window(String ttl, int WX, int WY, int WW, int WH)
{
winT = ttl;
winX = WX;
winY = WY;
winW = WW;
winH = WH;
dragging = false;
winXOff = 0;
winYOff = 0;
winTH = 24;
my_id = win_count ++;
}
void draw_window()
{
if (win_selected == my_id)
{
fill(60);
}
else
{
fill(40);
}
rect(winX, winY, winW, winTH);
fill(25);
rect(winX, winY + 24, winW, winH);
if (dragging == true)
{
winX = mouseX + winXOff;
winY = mouseY + winYOff;
if (winX < 0)
{
winX = 0;
}
if (winX > width - winW - 1)
{
winX = width - winW - 1;
}
if (winY < 0)
{
winY = 0;
}
if (winY > height - winH - winTH - 1)
{
winY = height - winH - winTH - 1;
}
}
Window win_pos = wins[0];
for (int i = 0; i < wins.length; i ++)
{
if (wins[i].my_id == my_id)
{
win_pos = wins[i];
}
}
if (mouse_in_rect(winX, winY, winW, 24) && mousePressed && mouseButton == LEFT && dragging == false && isOnTop(win_pos) && win_drag == false)
{
dragging = true;
winXOff = winX - mouseX;
winYOff = winY - mouseY;
win_drag = true;
win_selected = my_id;
bringToTop(win_pos);
}
if (mouse_in_rect(winX, winY + 24, winW, winH) && mousePressed && mouseButton == LEFT && dragging == false && isOnTop(win_pos) && win_drag == false)
{
win_selected = my_id;
bringToTop(win_pos);
}
if (dragging == true)
{
if (mouseButton != LEFT)
{
win_drag = false;
dragging = false;
winXOff = 0;
winYOff = 0;
}
}
}
}
mouseFunctions.pde:
boolean mouse_in_rect(int mX, int mY, int mW, int mH)
{
int but_x = mX;
int but_y = mY;
int but_w = mW;
int but_h = mH;
if (mouseX > but_x && mouseY > but_y && mouseX < but_x + but_w && mouseY < but_y + but_h)
{
return true;
}
else
{
return false;
}
}
The issue is caused, because you do the calculation of the window order and the drawing in a single loop.
If the position of a window has changed, the drawing of a window may be omitted, while the drawing of an other window is done twice. Note, the index of the windows in the array wins changed.
Split the drawing and the update of the windows to 2 separate methods:
class Window
{
// ...
void draw_window()
{
if (win_selected == my_id)
{
fill(60);
}
else
{
fill(40);
}
rect(winX, winY, winW, winTH);
fill(25);
rect(winX, winY + 24, winW, winH);
}
void update_window()
{
if (dragging == true)
{
// ...
}
// ...
}
First update the order of the windows and calculate its new position. After that draw all the windows in a separate loop:
void draw()
{
background(10);
for (int i = 0; i < wins.length; i ++) {
wins[i].update_window();
}
for (int i = 0; i < wins.length; i ++) {
wins[i].draw_window();
}
}
I'm a newbie in programming and I need some lights and help.I'm developing a game in which two players have to play with tokens (say red and blue) by placing them in cells (75x75 grid). The goal is to "capture" opponent's tokens by surrounding them. (See the image, which is the actual game output, the surrounding is drawn by hand)
To do so, I need to make the tokens "listen" to neighborhood, meaning other cells in the grid. A token has to check for itself in the grid(what is its position in the grid) and check of there is another token close to it, checks it color (blue or red) then,a in certain conditions, trigger the capturing mechanism
[![Game board with tokens][1]][1]
What I have done, technically:
Created the grid ( Grid/board is a 2 dimensional array of Token objects.)
The token (which is an enumeration: EMPTY, BLUE_TOKEN, RED_TOKEN.
A currentPlayer is also a Token .
When it's the user turn, they select an empty cell at which they point. They place the currentPlayer into the grid/board at cell rowSelected, colSelected then repaint the canvas with the newly added cell in the grid/board.
Now i'm stuck on how to make the tokens listen the next cell surrounding them in order to see if there is an opponent or an ally.
PS: I've posted the same here, got downgraded because i didn't respect rules (ignorant I was)
Here is my code:
import javax.swing.JFrame;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.*;
public class Phagocyte extends JFrame {
public static final int ROWS = 75;
public static final int COLS = 75;
public static final int CELL_SIZE = 18;
public static final int CANVAS_WIDTH = CELL_SIZE * COLS;
public static final int CANVAS_HEIGHT = CELL_SIZE * ROWS;
public static final int GRID_WIDTH = 8;
public static final int GRID_WIDHT_HALF = GRID_WIDTH / 2;
// Symbols (Blue token/Red Token) are displayed inside a cell with padding from borders
public static final int CELL_PADDING = CELL_SIZE / 5;
public static final int SYMBOL_SIZE = CELL_SIZE - CELL_PADDING * 2;
public static final int SYMBOL_STROKE_WIDTH = 3;
//This represent the various states of the game
public enum GameState {
PLAYING, DRAW, BLUE_TOKEN_WON, RED_TOKEN_WON //Haven't created a scenario yet
}
private GameState currentState; // The current state of the game
//This represent the Tokens and cell contents
public enum Token {
EMPTY, BLUE_TOKEN, RED_TOKEN
}
private Token currentPlayer; // The current player (whether red or blue)
private Token[][] board ; // This is the game board of cells (ROWS by COLS)
private DrawCanvas canvas;
private JLabel statusBar;
/**The components of the the game and the GUI are setup here */
public Phagocyte() {
canvas = new DrawCanvas();
canvas.setPreferredSize(new Dimension(CANVAS_WIDTH, CANVAS_HEIGHT));
canvas.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
int mouseX = e.getX();
int mouseY = e.getY();
// Here to get the row and column that is clicked
int rowSelected = mouseY / CELL_SIZE;
int colSelected = mouseX / CELL_SIZE;
if (currentState == GameState.PLAYING) {
if (rowSelected >= 0 && rowSelected < ROWS && colSelected >= 0
&& colSelected < COLS && board[rowSelected][colSelected] == TOKEN.EMPTY) {
board[rowSelected][colSelected] = currentPlayer;
updateGame(currentPlayer, rowSelected, colSelected);
// Here's to switch player
currentPlayer = (currentPlayer == Token.BLUE_TOKEN) ? Token.RED_TOKEN : Token.BLUE_TOKEN;
}
} else {
initGame();
}
// Drawing canvas are refresh
repaint();
}
});
// Setup the status bar (JLabel) to display status message
statusBar = new JLabel(" ");
statusBar.setFont(new Font(Font.DIALOG_INPUT, Font.BOLD, 15));
statusBar.setBorder(BorderFactory.createEmptyBorder(2, 5, 4, 5));
Container cp = getContentPane();
cp.setLayout(new BorderLayout());
cp.add(canvas, BorderLayout.CENTER);
cp.add(statusBar, BorderLayout.NORTH);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setTitle("Phagocyte by esQmo");
setVisible(true);
board = new Token[ROWS][COLS];
initGame();
}
/** The game board contents and the status are initialised here*/
public void initGame() {
for (int row = 0; row < ROWS; ++row) {
for (int col = 0; col < COLS; ++col) {
board[row][col] = Token.EMPTY;
}
}
currentState = GameState.PLAYING;
currentPlayer = Token.RED_TOKEN;
}
/*this part need some improvements since hasWon and isDraw are not yet definied*/
public void updateGame(Token theToken, int rowSelected, int colSelected) {
if (hasWon(theToken, rowSelected, colSelected)) {
currentState = (theToken == Token.RED_TOKEN) ? GameState.RED_TOKEN_WON : GameState.BLUE_TOKEN_WON;
} else if (isDraw()) {
currentState = GameState.DRAW;
}
}
/** This is supposed to return true if it is a draw (no more empty cell for exemple) */
/** need to be improved **/
/* public boolean isDraw() {
for (int row = 0; row < ROWS; ++row) {
for (int col = 0; col < COLS; ++col) {
if (board[row][col] == Token.EMPTY) {
return false;
}
}
}
return true;
} */
/**Need to implement a Win scenario as well **/
public boolean hasWon(Token theToken, int rowSelected, int colSelected){
//
}
class DrawCanvas extends JPanel {
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
setBackground(Color.WHITE);
//Grid lines
g.setColor(Color.LIGHT_GRAY);
for (int row = 1; row < ROWS; ++row) {
g.fillRoundRect(0, CELL_SIZE * row - GRID_WIDHT_HALF,
CANVAS_WIDTH-1, GRID_WIDTH, GRID_WIDTH, GRID_WIDTH);
}
for (int col = 1; col < COLS; ++col) {
g.fillRoundRect(CELL_SIZE * col - GRID_WIDHT_HALF, 0,
GRID_WIDTH, CANVAS_HEIGHT-1, GRID_WIDTH, GRID_WIDTH);
}
// This draw the Tokkens in the cells if they are not empty
Graphics2D g2d = (Graphics2D)g;
g2d.setStroke(new BasicStroke(SYMBOL_STROKE_WIDTH, BasicStroke.CAP_ROUND,
BasicStroke.JOIN_ROUND));
for (int row = 0; row < ROWS; ++row) {
for (int col = 0; col < COLS; ++col) {
int x1 = col * CELL_SIZE + CELL_PADDING;
int y1 = row * CELL_SIZE + CELL_PADDING;
if (board[row][col] == Token.RED_TOKEN) {
int x2 = (col + 1) * CELL_SIZE - CELL_PADDING;
int y2 = (row + 1) * CELL_SIZE - CELL_PADDING;
g2d.setColor(Color.RED);
g2d.drawOval(x1, y1, SYMBOL_SIZE, SYMBOL_SIZE);
g2d.fillOval(x1, y1, SYMBOL_SIZE, SYMBOL_SIZE);
} else
if (board[row][col] == Token.BLUE_TOKEN) {
g2d.setColor(Color.BLUE);
g2d.drawOval(x1, y1, SYMBOL_SIZE, SYMBOL_SIZE);
g2d.fillOval(x2, y1, SYMBOL_SIZE, SYMBOL_SIZE);
}
}
}
// Print status-bar message
if (currentState == GameState.PLAYING) {
statusBar.setForeground(Color.BLACK);
if (currentPlayer == Token.RED_TOKEN) {
statusBar.setText("Red, it's your move");
statusBar.setForeground(Color.RED);
} else {
statusBar.setText("Blue, it's your move");
statusBar.setForeground(Color.BLUE);
statusBar.addMouseMotionListener(null);
}
} else if (currentState == GameState.DRAW) {
statusBar.setForeground(Color.RED);
statusBar.setText("It's a draw!");
} else if (currentState == GameState.RED_TOKEN_WON) {
statusBar.setForeground(Color.RED);
statusBar.setText("Red wow!");
} else if (currentState == GameState.BLUE_TOKEN_WON) {
statusBar.setForeground(Color.BLUE);
statusBar.setText("Blue Won! ");
}
}
}
public static void main(String[] args){
SwingUtilities.invokeLater(() -> {
Phagocyte phagocyte = new Phagocyte();
});
}
}
I'm unable to post image, due to my reputation :'(
Lately I've been working on a grid line detection system, I know that there was an algorithm out there that did excactly what I wanted it to do, but I'm that kind of person who wants to make stuff themselves. ;)
So I've had some succes when checking with 1 line, but now that I use a grid of 20x20 to check the lines it doesn't work anymore.
The problem is found somewhere in the collision class I made for this system.
Somehow the numbers get out of the grid array and I don't know why
here is the code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
/**
*
* beschrijving
*
* #version 1.0 van 22-6-2016
* #author
*/
public class gridline extends JApplet {
// Begin variabelen
int[][] grid = new int[20][20];
int[] light = new int[2];
int[][] line = new int[2][2];
// Einde variabelen
public void init() {
Container cp = getContentPane();
cp.setLayout(null);
cp.setBounds(0, 0, 600, 600);
// Begin componenten
for (int a=0; a<20; a++) {
for (int b=0; b<20; b++) {
grid[a][b] = (int) (Math.random()*10);
} // end of for
} // end of for
line[0][0] = (int) (Math.random()*20);
line[0][1] = (int) (Math.random()*20);
line[1][0] = (int) (Math.random()*20);
line[1][1] = (int) (Math.random()*20);
light[0] = (int) (Math.random()*20);
light[1] = (int) (Math.random()*20);
// Einde componenten
} // end of init
//Custom classes
private boolean collide(int x1, int y1,int x2, int y2) {
boolean collide = true;
int tempx = x1 - x2;
int tempy = y1 - y2;
int sx = 0;
int sy = 0;
int x = 0;
int y = 0;
if (tempx == 0) {
tempx = 1;
sx = 1;
} // end of if
if (tempy == 0) {
tempy = 1;
sy = 1;
} // end of if
if (sx == 0) {
x = tempx + tempx/Math.abs(tempx);
} // end of if
else {
x = tempx;
} // end of if-else
if (sy == 0) {
y = tempy + tempy/Math.abs(tempy);
} // end of if
else {
y = tempy;
} // end of if-else
int absx = Math.abs(x);
int absy = Math.abs(y);
int nex = x/absx;
int ney = y/absy;
int off = 0;
float count = 0;
float step = 0;
if (absx != absy) {
if (absx == Math.min(absx,absy)) {
step = (float) absx/absy;
calc1: for (int a=0; a<absy; a++) {
count += step;
if (count > 1 && x1+off != x2) {
count -= 1;
off += nex;
} // end of if
if (grid[x1+off][y1+a*ney] == 9) {
collide = false;
break calc1;
} // end of if
} // end of for
} // end of if
else{
step = (float) absy/absx;
calc2: for (int a=0; a<absx; a++) {
count += step;
if (count > 1 && y1+off != y2) {
count -= 1;
off += ney;
} // end of if
if (grid[x1+a*nex][y1+off] == 9) {
collide = false;
break calc2;
} // end of if
} // end of for
}
} // end of if
else {
calc3: for (int a=0; a<absx; a++) {
if (grid[x1+a*nex][y1+a*ney] == 9) {
collide = false;
break calc3;
} // end of if
} // end of for
} // end of if-else
return collide;
}
private int length(int x1, int y1, int x2, int y2) {
double distance = Math.sqrt(Math.pow(x1-x2,2)+Math.pow(y1-y2,2));
return (int) distance;
}
// Begin eventmethoden
public void paint (Graphics g){
boolean draw = true;
Color col;
for (int a=0; a<20; a++) {
for (int b=0; b<20; b++) {
draw = collide(a,b,light[0],light[1]);
if (draw) {
int len = Math.max(255-length(a*30+15,b*30+15,light[0]*30+15,light[1]*30+15),0);
col = new Color(len,len,len);
g.setColor(col);
g.fillRect(a*30,b*30,30,30);
} // end of if
else{
col = new Color(0,0,0);
g.setColor(col);
g.fillRect(a*30,b*30,30,30);
}
} // end of for
} // end of for
}
// Einde eventmethoden
} // end of class gridline
I'll understand it if nobody wants to look through a code as big as this, but it could be helpful for your own projects and I'm completely okay with it if you copy and paste my code for your projects.
Many thanks in advace.
I'm am new to graphics in java and for some reason the graphics are not displaying on the jframe. I am confused of how to set up and instantiate the graphics. There could also be a stupid error in the code that im just not seeing. Thanks for any feedback!
Map Class
public class Map extends JPanel{
private static int WIDTH;
private static int HEIGHT;
private static int ROWS;
private static int COLS;
private static int TILE_SIZE;
private static int CLEAR = 0;
private static int BLOCKED = 1;
private static int[][] GRID;
public Map(int w, int h, int t){
WIDTH = w;
HEIGHT = h;
TILE_SIZE = t;
ROWS = HEIGHT/TILE_SIZE;
COLS = WIDTH/TILE_SIZE;
GRID = new int[ROWS][COLS];
for (int row = 0; row < ROWS; row++){
for (int col = 0; col < COLS; col++){
GRID[row][col] = BLOCKED;
}
}
randomMap();
}
public void randomMap(){
int row = 0;
int col = 0;
int turn;
Random rand = new Random();
GRID[row][col] = CLEAR;
do{
turn = rand.nextInt(2)+1;
if (turn == 1)
row++;
else
col++;
GRID[row][col] = CLEAR;
}while(row<ROWS-1 && col<COLS-1);
if (row == ROWS-1){
for (int i = col; i < COLS; i++){
GRID[row][i] = CLEAR;
}
}
else{
for (int i = row; i < ROWS; i++){
GRID[i][col] = CLEAR;
}
}
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
for (int row = 0; row < WIDTH; row++){
for (int col = 0; col < HEIGHT; col++){
if (GRID[row][col] == 1){
g2d.setColor(Color.BLACK);
g2d.fillRect(row*TILE_SIZE, col*TILE_SIZE, TILE_SIZE, TILE_SIZE);
}else{
g2d.setColor(Color.WHITE);
g2d.fillRect(row*TILE_SIZE, col*TILE_SIZE, TILE_SIZE, TILE_SIZE);
}
}
}
}
public void displayConsole(){
for (int row = 0; row < ROWS; row++){
for (int col = 0; col < COLS; col++){
System.out.print(GRID[row][col] + " ");
}
System.out.println("");
System.out.println("");
}
}
}
Game Class
public class Game extends JFrame{
private Map map;
public Game(){
setLayout(null);
setBounds(0,0,500,500);
setSize(500,500);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Map map = new Map(500,500,50);
map.displayConsole();
add(map);
repaint();
setVisible(true);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Game game = new Game();
}
}
It is likely the painted component is of size 0x0. A custom painted component should return the preferred size of the component.
After the component is added to a frame, pack the frame to ensure the frame is the exact size needed to display the component.
Of course, either use or set an appropriate layout/constraint in the frame. In this case, I would use the default layout of BorderLayout and the default constraint of CENTER.
Andrew is correct. I had to re-do the layout to get this to work. I added the code for perferredSize() and minimumSize(), and I added a call to pack() and removed the setLayout(null). Also, you have a problem calculating your HEIGHT and WIDTH, they don't line up to ROWS and COLS and will throw Index Out Of Bounds.
Corrected code below.
class Game extends JFrame
{
private Map map;
public Game()
{
// setLayout( null );
setBounds( 0, 0, 500, 500 );
setSize( 500, 500 );
setResizable( false );
setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
Map map = new Map( 500, 500, 50 );
map.displayConsole();
add( map );
pack();
repaint();
setVisible( true );
}
public static void main( String[] args )
{
// TODO Auto-generated method stub
Game game = new Game();
}
}
class Map extends JPanel
{
private static int WIDTH;
private static int HEIGHT;
private static int ROWS;
private static int COLS;
private static int TILE_SIZE;
private static int CLEAR = 0;
private static int BLOCKED = 1;
private static int[][] GRID;
public Map( int w, int h, int t )
{
WIDTH = w;
HEIGHT = h;
TILE_SIZE = t;
ROWS = HEIGHT / TILE_SIZE;
COLS = WIDTH / TILE_SIZE;
GRID = new int[ ROWS ][ COLS ];
for( int row = 0; row < ROWS; row++ )
for( int col = 0; col < COLS; col++ )
GRID[row][col] = BLOCKED;
randomMap();
}
public void randomMap()
{
int row = 0;
int col = 0;
int turn;
Random rand = new Random();
GRID[row][col] = CLEAR;
do {
turn = rand.nextInt( 2 ) + 1;
if( turn == 1 )
row++;
else
col++;
GRID[row][col] = CLEAR;
} while( row < ROWS - 1 && col < COLS - 1 );
if( row == ROWS - 1 )
for( int i = col; i < COLS; i++ )
GRID[row][i] = CLEAR;
else
for( int i = row; i < ROWS; i++ )
GRID[i][col] = CLEAR;
}
#Override
public Dimension preferredSize()
{
// return super.preferredSize(); //To change body of generated methods, choose Tools |
return new Dimension( WIDTH, HEIGHT );
}
#Override
public Dimension minimumSize()
{
return preferredSize();
}
public void paintComponent( Graphics g )
{
super.paintComponent( g );
Graphics2D g2d = (Graphics2D) g;
for( int row = 0; row < ROWS; row++ )
for( int col = 0; col < COLS; col++ )
if( GRID[row][col] == 1 ) {
g2d.setColor( Color.BLACK );
g2d.fillRect( row * TILE_SIZE, col * TILE_SIZE,
TILE_SIZE, TILE_SIZE );
} else {
g2d.setColor( Color.WHITE );
g2d.fillRect( row * TILE_SIZE, col * TILE_SIZE,
TILE_SIZE, TILE_SIZE );
}
}
public void displayConsole()
{
for( int row = 0; row < ROWS; row++ ) {
for( int col = 0; col < COLS; col++ )
System.out.print( GRID[row][col] + " " );
System.out.println( "" );
System.out.println( "" );
}
}
}
How would I go about modifying my current code for a checker board so that the checker pieces recursively alternate in color? Just to be clear, I don't want each piece to be a solid color - I want them to have levels that alternate in color in on itself. So for example, the currently yellow pieces would change to being yellow and blue pieces, having an outer level of yellow, followed by a level of blue, then yellow, etc. I hope that makes sense? I don't believe I can highlight code, but the checker pieces start after the first nested for statement in the checkerBoard method. There are 2 cases, the first being the top 2 rows, and the second being the bottom two.
import java.awt.*;
import java.applet.*;
public class Checkerboard extends Applet
{
private final int DIST = 100;
private final int SIZE = 1000;
public void checkerBoard(int row, int col, int x, int y, boolean b, Graphics g)
{
for ( row = 0; row < 8; row++ )
{
for ( col = 0; col < 8; col++)
{
x = col * 100;
y = row * 100;
if ( (row % 2) == (col % 2) )
g.setColor(Color.black);
else
g.setColor(Color.red);
g.fillRect(x, y, 100, 100);
}
}
for ( row = 0; row < 2; row++ )
{
for ( col = 0; col < 8; col++)
{
x = col * 100;
y = row * 100;
g.setColor(Color.yellow);
g.fillOval(x, y, 100, 100);
}
}
for ( row = 7; row > 5; row-- )
{
for ( col = 0; col < 8; col++)
{
x = col * 100;
y = row * 100;
g.setColor(Color.green);
g.fillOval(x, y, 100, 100);
}
}
}
public void paint(Graphics g)
{
checkerBoard(0, 0, 0, 0, true, g);
}
}
is this what you want
for ( row = 0; row < 2; row++ )
{
for ( col = 0; col < 8; col++)
{
for ( int ring = 0; ring < 5; ring++) {
x = col * 100 + (ring * 10);
y = row * 100 + (ring * 10);
if((ring & 1) == 0){
g.setColor(Color.yellow);
}else{
g.setColor(Color.blue);
}
g.fillOval(x, y, 100-(ring*20), 100-(ring*20));
}
}
}
recursive method would be like,
private void drawCircle(int x, int y, int circleSize, int ringSize, Color primary, Color alternate, Graphics g){
if(circleSize > 0){
g.setColor(primary);
g.fillOval(x, y, circleSize,circleSize);
drawCircle(x+ringSize/2,y+ringSize/2,circleSize-ringSize,ringSize,alternate,primary, g);
}
}
for ( row = 0; row < 2; row++ )
{
for ( col = 0; col < 4; col++)
{
int y = row * 100;
int x = ((col * 2) + (col & 1)) * 100; // want to alternate squares
drawCircle(x, y, 100, 20, Color.Yellow, Color.Blue,g);
}
}