java - Creating a multicolored board -
i create multicolored board, starting first square black, blue, red, , yellow, squares being filled diagonally , there no empty colored squares. know algorithm wrong, have not clue how fix it. currently, code prints out this
import javax.swing.jframe; import javax.swing.jpanel; import java.awt.color; import java.awt.dimension; import java.awt.graphics; import java.awt.graphics2d; import java.awt.insets; public class grid extends jpanel { private static final long serialversionuid = 1l; public static final int grid_count = 8; private color[] colors = { color.black, color.yellow, color.red, color.blue }; private int colorindex = 0; public void paintcomponent(graphics g) { super.paintcomponent(g); graphics2d graphics = (graphics2d) g; graphics.setcolor(color.black); dimension size = getsize(); insets insets = getinsets(); int w = size.width - insets.left - insets.right; int h = size.height - insets.top - insets.bottom; int sqrwidth = (int)((double)w / grid_count); int sqrheight = (int)((double)h / grid_count); (int row = 0; row < grid_count; row++) { (int col = 0; col < grid_count; col++) { int x = (int) (row * (double) w / grid_count); int y = (int) (col * (double) h / grid_count); if ((row + col) % 2 == 0) { int colorindex = (row + col) % 4; graphics.fillrect(x, y, sqrwidth, sqrheight); graphics.setcolor(colors[colorindex]); colorindex = (colorindex + 1) % colors.length; } } public static void main(string[] args) { grid grid = new grid(); grid.setpreferredsize(new dimension(400, 400)); jframe frame = new jframe("grid"); frame.setdefaultcloseoperation(jframe.exit_on_close); frame.add(grid); frame.pack(); frame.setlocationrelativeto(null); frame.setvisible(true); }
}
let's @ pattern:
bk gr pn bl gr pn bl bk pn bl bk gr bl bk gr pn
but make simpler, let's call bk 0, gr 1, pn 2 , bl 3 get:
0 1 2 3 1 2 3 0 2 3 0 1 3 0 1 2
this pattern produced calculating tile[x][y] = (x + y) % 4
every tile, , using lookup table convert these numbers colours (either use enumeration, or instead of assigning integer value tile use integer look-up in table of colours , assign colour tile)
if you've never seen before, % 4 means 'divide 4 , return remainder of division'.
Comments
Post a Comment