Java - Recursively alternate colors in circle - java

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

Related

How to identify a winner in connect four game?

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.

How to layer graphics in java?

I am trying to make my own version of checkers and I have currently written the code to store draw the board and the pieces.
Every time I run the code I get a different result because the board is being drawn over some pieces. How do I get all the pieces to appear over the board all the time? I understand similar questions have been asked but they don't provide any useful help.
Here's the code that is draws the board:
public void paint(Graphics gr) {
Graphics2D gr2D = (Graphics2D) gr;
gr2D.setColor(color1);
BasicStroke stroke = new BasicStroke(strokeThickness,
BasicStroke.CAP_SQUARE, BasicStroke.JOIN_ROUND);
gr2D.setStroke(stroke);
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
gr.setColor((gr.getColor() == color2)
? color1 : color2);
gr.fillRect((int) (start + CHANGEVAL * i),
(int) (start + CHANGEVAL * j),
(int) CHANGEVAL,
(int) CHANGEVAL);
}
gr.setColor((gr.getColor() == color2)
? color1 : color2);
}
}
And here's the code that draws the pieces:
public static void setPieces() {
posX = 0;
posY = 0;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
aryPiecePos[posX][posY] = SQUARE_STATE_RED;
board.repaint(board.getCoordX(posX), board.getCoordY(posY), Color.RED);
posX += 2;
}
posX = (posX == 8 ? 1 : 0);
posY += 1;
}
posX = 1;
posY = 5;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
aryPiecePos[posX][posY] = SQUARE_STATE_BLACK;
board.repaint(board.getCoordX(posX), board.getCoordY(posY), Color.BLACK);
posX += 2;
}
posX = (posX == 8 ? 1 : 0);
posY += 1;
}
}
Also here's a link to all my code:
Here's a hyperlink to what I have currently: https://drive.google.com/open?id=0B2uJqRSB8ckHYW53NmZsZDdxWWs
What you draw first will be in a deeper layer so to speak.
g.setColor(Color.BLUE);
g.fillRect(x, y, width, height);
g.setColor(Color.GREEN);
g.fillRect(x, y, width, height);
With the above code the blue rectangle will not be visible, since the green one is drawn over it.
Therefore to solve your problem you need to draw the board first, then all the pieces.

Repeated lines/stripes using for loops in Java

i want to paint black and white stripes on the image, switching every 20th column both horizontally and vertically on top of an image while staying inside it's borders. so far i can get a black square with 1 pixel wide vertical stripes. i've tried to at least get skinny white stripes on my horizontal lines by switching things around but it's still vertical.
public void zebraStripes() {
Image img = ImageViewer.getImage();
double numPixelsWide = img.getWidth();
int numPixelsHigh = img.getHeight();
Color c = Color.WHITE;
Color b = Color.BLACK;
double i = numPixelsWide;
if (i % 20 == 0) {
for (int x = 0; x < numPixelsHigh; x++) {
for (int y = 0; y < i; y++) {
img.setPixelColor(y, x, b);
}
for (int z = 19; z < i; z = z + 20) {
img.setPixelColor(z, x, c);
}
}
}
}
// paint black and white stripes (left to right) on the image, switching
// every 20th row
public void jailBird() {
Image img = ImageViewer.getImage();
double numPixelsWide = img.getWidth();
double numPixelsHigh = img.getHeight();
Color c = Color.WHITE;
Color b = Color.BLACK;
double i = numPixelsHigh;
if (i % 20 == 0) {
for (int x = 0; x < numPixelsHigh; x++) {
for (int y = 0; y < i; y++) {
img.setPixelColor(y, x, b);
}
for (int z = 19; z < i; z = z + 20) {
img.setPixelColor(z, x, c);
}
}
}
}
}
how do i get the white stripes to be 20 pixels wide and horizontal?
Not tested! Hope it gets you going.
// paint a 20 pixels wide horizontal line for every 40 pixels
for (int y = 0; y < numPixelsHigh; y += 40) {
// paint a stripe
for (int ys = y; ys < y + 20; ys++) {
for (int x = 0; x < numPixelsWide; x++) {
img.setPixelColor(x, ys, Color.BLACK);
}
}
}

Graphics not displaying on JFrame

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

Nested for loops to create pyramid

I was wondering if someone could help figure this out. I've been trying to display a pyramid using nested for loops and I've only been able to get the first row (base row) working. The pyramid is suppose to have 10 rectangles at the bottom and as it increments up, the rectangle count decreases to 9, 8, 7, 6, etc. I've been looking at this for days and have had no luck.
Thank you!
public class Legos2 extends JFrame {
private int startX;
private int startY;
private int legoWidth;
private int legoHeight;
private int baseLength;
private int arcWidth;
private int arcHeight;
// Constructor
public Legos2() {
super("Jimmy's LEGOs");
startX = 20;
startY = 300;
legoWidth = 50;
legoHeight = 20;
baseLength = 10;
arcWidth = 2;
arcHeight = 2;
}
// The drawings in the graphics context
public void paint(Graphics g)
{
// Call the paint method of the JFrame
super.paint(g);
int currentX = startX;
int currentY = startY;
//row = 0 is the bottom row
for (int row = 1; row <= baseLength; row++)
{
currentX = currentX + legoWidth;
if (row % 2 == 0)
g.setColor(Color.blue);
else
g.setColor(Color.red);
System.out.println(row);
for (int col = 0; col <= baseLength; col++)
{
System.out.println(col);
g.fillRoundRect(currentX, currentY, legoWidth, legoHeight, arcWidth, arcHeight);
}
//currentY = currentY - legoHeight;
}
}
// The main method
public static void main(String[] args) {
Legos2 app = new Legos2();
// Set the size and the visibility
app.setSize(700, 500);
app.setVisible(true);
// Exit on close is clicked
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
The currentY value should be decremented at each iteration of the outer loop: for each row, you want to restart from a lower Y. So you should uncomment the line
//currentY = currentY - legoHeight;
The currentX must be incremented after each column, so at the end of the inner loop, and not at the beginning of the outer loop. And it must be reset to the start X position of the current row before you enter the inner loop.
If you just reset currentX to startX, you'll get a wall of bricks. But you need a pyramid. So there should be one less iteration of the inner loop at each iteration of the outer loop, and the startX should also be incremented after each iteration of the outer loop:
for (int row = 1; row <= baseLength; row++) {
currentX = startX;
if (row % 2 == 0) {
g.setColor(Color.blue);
}
else {
g.setColor(Color.red);
}
System.out.println("row = " + row);
for (int col = 0; col <= baseLength - row; col++) {
System.out.println("col = " + col);
g.fillRoundRect(currentX, currentY, legoWidth, legoHeight, arcWidth, arcHeight);
currentX = currentX + legoWidth;
}
currentY -= legoHeight;
startX += legoWidth / 2;
}

Categories