Pieces not being removed when taken - java

I am creating a Chess Game and I just finished the basic Ai, but whenever a piece is taken it disappears and comes back a few turns later. The piece shouldn't even be in the list that renders the pieces.
This is the class that render/adds/sets the new pieces
setPieceLoc() sets the old piece at its new location and removes both the original and the newLoc from all lists.
Does anyone see why this is happening? There is no other class that adds new information to the lists, so as far as I can tell it must be an error here.
package me.xthegamerplayz.FirstGame.board;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import me.xthegamerplayz.FirstGame.board.tiles.ChessImages;
import me.xthegamerplayz.FirstGame.rules.LegalMoves;
public class Board {
public static void addPiece(int x, int y, int piece) {
Point point = new Point();
point.setLocation(x, y);
if(piece > 16)
ChessBoard.black.put(point, piece);
else
ChessBoard.white.put(point, piece);
}
public static void setPieceLoc(Point original, Point newLoc) {
int piece = 8;
if(ChessBoard.white.containsKey(original))
piece = ChessBoard.white.get(original);
else if(ChessBoard.black.containsKey(original))
piece = ChessBoard.black.get(original);
//Remove piece at newLoc
if(ChessBoard.white.containsKey(newLoc))
ChessBoard.white.remove(newLoc);
else if(ChessBoard.black.containsKey(newLoc))
ChessBoard.black.remove(newLoc);
//Remove piece from previous location
if(ChessBoard.white.containsKey(original))
ChessBoard.white.remove(original);
else if(ChessBoard.black.containsKey(original))
ChessBoard.black.remove(original);
if(piece > 16)
ChessBoard.black.put(newLoc, piece);
else
ChessBoard.white.put(newLoc, piece);
}
public void registerPieces() {
//Pawns
for(int x = 0; x < 8; x++) {
addPiece(x, 1, 8);
addPiece(x, 6, 24);
}
//White
addPiece(0, 0, 9);
addPiece(1, 0, 10);
addPiece(2, 0, 11);
addPiece(5, 0, 11);
addPiece(6, 0, 10);
addPiece(7, 0, 9);
addPiece(4, 0, 12);
addPiece(3, 0, 13);
//Black
addPiece(0, 7, 25);
addPiece(1, 7, 26);
addPiece(2, 7, 27);
addPiece(5, 7, 27);
addPiece(6, 7, 26);
addPiece(7, 7, 25);
addPiece(3, 7, 28);
addPiece(4, 7, 29);
}
public void render(Graphics g) {
for(Point point : ChessBoard.white.keySet()) {
int piece = ChessBoard.white.get(new Point(point));
int x = (int) (point.getX()*64) + 20;
int y = (int) (point.getY()*64) + 20;
boolean showTiles = false;
if(showTiles) {
if(piece == 24) {
LegalMoves lm = new LegalMoves(point);
for(Point p : lm.moves()) {
int bx = (int) (p.getX()*64) + 20;
int by = (int) (p.getY()*64) + 20;
g.setColor(Color.green);
g.fillRect(bx, by, 64, 64);
}
}
}
g.drawImage(ChessImages.getPieceImage(piece), x, y, null);
}
for(Point point : ChessBoard.black.keySet()) {
int piece = ChessBoard.black.get(new Point(point));
int x = (int) (point.getX()*64) + 20;
int y = (int) (point.getY()*64) + 20;
boolean showTiles = false;
if(showTiles) {
if(piece == 24) {
LegalMoves lm = new LegalMoves(point);
for(Point p : lm.moves()) {
int bx = (int) (p.getX()*64) + 20;
int by = (int) (p.getY()*64) + 20;
g.setColor(Color.green);
g.fillRect(bx, by, 64, 64);
}
}
}
g.drawImage(ChessImages.getPieceImage(piece), x, y, null);
}
}
}

It looks like you are attempting to make a move a piece from somewhere that is empty.
Note that, when your original is in neither the black nor white maps, it will use piece 8, which appears to be a white pawn. That happens to be the piece reappearing in your video.
You should really be throwing an exception when this happens, because moving a piece from an empty square makes no sense. Doing this should help you debug the circumstance in which this is happening:
if(ChessBoard.white.containsKey(original))
piece = ChessBoard.white.get(original);
else if(ChessBoard.black.containsKey(original))
piece = ChessBoard.black.get(original);
else
throw new IllegalArgumentException("Attempting to move piece from empty square " + original);

Related

Color Picker not Visible

I have an issue where I'm unable to see Color Picker.
I'm trying to generate a lot of lines to make patterns to make me feel accomplished. It's a side project.
I'm not the best at coding so I need help. Also you have to minimize the window and open it back up to make it work when you are running it by the way.
*update I've figured out that the color picker is there but just behind all of my lines that I've drawn.
Here is my code.
import controlP5.ColorPicker;
import controlP5.ControlEvent;
import controlP5.ControlP5;
import processing.core.PApplet;
public class main extends PApplet {
ControlP5 cp5;
ColorPicker cp;
boolean guiState;
int col;
public static void main(String[] args) {
PApplet.main("main");
}
void drawLines() {
float lineLength = sqrt(height * height + width * width);
float nsHueStart = random((float) 10);
float nsSatStart = random((float) 10);
float nsRotStart = random((float) 10);
float nsHStart = random((float) 10);
float nsWStart = random((float) 10);
int lineWidthMax = 50;
for (int lineWidth = 1; lineWidth <= lineWidthMax; ++lineWidth) {
strokeWeight((5 * pow(lineWidth, 2)));
nsHueStart += 001;
float nsHue = nsHueStart;
float nsSat = nsSatStart;
float nsH = nsHStart;
float divH;
float divW;
for (float idxH = 0; idxH < height; idxH += divH) {
divH = map(noise(nsH), 0, 1, 80, 200);
float nsRot = nsRotStart;
float nsW = nsWStart;
for (float idxW = 0; idxW < width; idxW += divW) {
divW = map(noise(nsW), 0, 1, 0, 5); // do not use 2D noise
float brushHue = map(noise(nsHue), 0, 1, 0, 720) % 360; // various colors
float brushSat = map(noise(nsSat), 0, 1, 20, 70) / map(lineWidth, 1, lineWidthMax, 1, (float) 1.8);
float brushBri = map(noise(nsSat), 0, 1, 8, 15) / map(lineWidth, 1, lineWidthMax, 1, (float) (lineWidthMax * 2.8));
float brushAlp = 100;
float brushSiz = lineLength;
float brushRot = map(noise(nsRot), 0, 1, -60, 60);
pushMatrix();
translate(idxW, idxH);
canvasRotation(brushRot);
stroke(brushHue, brushSat, brushBri, brushAlp);
line(-brushSiz, 0, brushSiz, 0);
popMatrix();
nsHue += 002;
nsRot += 005;
nsW += 01 + noise(nsH) / 10; // not to be same shape
}
nsSat += 5;
nsH += 8;
}
}
}
public void settings() {
size(2560, 1395);
smooth(8);
}
public void setup() {
noStroke();
cp5 = new ControlP5(this);
cp = cp5.addColorPicker("picker")
.setPosition(60, 100)
.setColorValue(color(0, 128, 255, 128))
;
colorMode(HSB, 360, 100, 100, 100);
blendMode(SCREEN);
cp5.show();
frameRate(60);
}
public void draw() {
background(cp.getColorValue());
fill(0, 80);
rect(50, 90, 275, 80);
translate(0, 0);
drawLines();
}
public void controlEvent(ControlEvent c) {
if (c.isFrom(cp)) {
float r = (c.getArrayValue(0));
float g = (c.getArrayValue(1));
float b = (c.getArrayValue(2));
float a = (c.getArrayValue(3));
col = color(r, g, b, a);
println("event\talpha:"+a+"\tred:"+r+"\tgreen:"+g+"\tblue:"+b+"\tcol"+col);
}
}
void canvasRotation(float degrees) {
rotate(radians(degrees));
}
public void toggleGUI(boolean state) {
if (state) {
cp5.show();
} else {
cp5.hide();
background(200);
}
guiState = state;
}
public void keyPressed() {
if (keyCode == LEFT) toggleGUI(guiState);
switch (key) {
case ('1'):
cp.setArrayValue(new float[]{120, 0, 120, 255});
break;
case ('2'):
cp.setColorValue(color(255, 0, 0, 255));
break;
}
}
}

Adding Element to Class Array with function. "Paint" in Processing 3

I'm trying to create a "Paint" application with Processing 3, and I want to add buttons to change the color (later on for brushes, size, etc).
I'm stuck because I'm keep getting a NullPointerException for adding the button to my array.
(I know i could just ask for the mouseX and Y after creating every button without the array but it seems a bit unprofessional to me and would get very messy by time).
ERROR: Line 24 -> "allButtons[counter].name = Name;"
*Sidenote: I'm pretty new to Processing / Java xd
This is my code:
class button
{
public String name;
public int x;
public int y;
public color curColor;
};
color currentColor = color(0, 0, 0);
String currentBrush = "Brush";
int currentBrushSize = 3;
button[] allButtons = new button[100];
int buttonSize = 20;
int counter = 1;
void setup() {
size(800, 600);
background(255);
surface.setResizable(true);
surface.setTitle("Not Skribble");
}
void button(String Name, int X, int Y, color CurColor) {
allButtons[counter].name = Name;
allButtons[counter].x = X;
allButtons[counter].y = Y;
allButtons[counter].curColor = CurColor;
counter += 1;
fill(CurColor);
rect(X, Y, buttonSize, buttonSize);
if (overButton(X, Y, X + buttonSize, Y + buttonSize)) {
fill(0, 0, 0, 80);
rect(X, Y, buttonSize, buttonSize);
}
}
boolean overButton(int minX, int minY, int maxX, int maxY) {
if (mouseX >= minX && mouseX <= maxX) {
if (mouseY >= minY && mouseY <= maxY) {
return true;
}
}
return false;
}
boolean buttonPressed(String name) {
for (int i = 0; i < allButtons.length; i++) {
if (name == allButtons[i].name) {
if (mouseX >= allButtons[i].x && mouseX <= allButtons[i].x + buttonSize) {
if (mouseY >= allButtons[i].y && mouseY <= allButtons[i].y + buttonSize) {
if (mousePressed) {
return true;
}
}
}
}
}
return false;
}
void setColor(color settingColor) {
currentColor = settingColor;
}
void setBrush(String settingBrush) {
currentBrush = settingBrush;
}
void setBrushSize(int settingBrushSize) {
currentBrushSize = settingBrushSize;
}
void colorButtons() {
button("Orange", 10, 10, color(255, 100, 0));
if (buttonPressed("Orange")) setColor(color(255, 100, 0));
button("Blue", 50, 10, color(255, 100, 0));
if (buttonPressed("Blue")) setColor(color(0, 0, 255));
}
void brushButtons(){
}
void settingButtons(){
}
void draw() {
noStroke();
fill(100);
rect(0, 0, width, 70);
colorButtons();
brushButtons();
settingButtons();
}
When you create an array like this:
Button[] allButtons = new Button[100];
You're creating an array that can hold 100 Button instances. But that array starts out as empty. Try doing something like this:
println(allButtons[0]);
You'll see that this prints out null, which means that the value is basically empty. You haven't actually added any Button instances to your array. This is why you're getting an error: because you're trying to use values that don't exist.
To add an instance to your array, you'd do something like this:
allButtons[0] = new Button();
At which point it would be safe to do use that value:
allButtons[0].name = "cancel";
By the way, you might consider just using an ArrayList instead of an array. Or take advantage of Processing's array functions that allow you to add elements to an array instead of creating an array with a size of 100.
Also, in the future please try to use proper naming conventions. Variables should start with a lower-case letter, and classes should start with an upper-case letter. This makes your code much easier to read.

Determining a winner in java race car program

I am trying to find a way to determine a winner and I am not having much luck. The program is suppose to run three laps and which ever car finish all the laps first is the winner. I can get 3 "laps" in but it is not a very good way of doing it. I am hoping someone can show me a better way and also how I can can "count" those laps for the specific winning car. The number of cars is random from 2 - 4 and the "speed" is also random. Can someone help me please. Some code would be nice.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Random;
public class RacingCar extends JFrame {
public RacingCar() {
int x = (int)(Math.random() * 3) + 2;
setLayout(new GridLayout(x, 1, 5,5));
for (int i = 0; i < x; i++){
add(new CarImage());
}
}
public static void main(String[] args) {
JFrame frame = new RacingCar();
frame.setTitle("Racing Car");
frame.setSize(1200, 350);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
class CarImage extends JPanel {
protected int x = 0;
protected int y = 350;
protected int z = 1200;
protected int c = 0;
public CarImage() {
int j = (int)(Math.random() * 500) + 2;
Timer timer1 = new Timer(j, new ActionListener(){
public void actionPerformed(ActionEvent e) {
x += 10;
c ++;
repaint();
}
});
timer1.start();
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
//x = 0;
y = getHeight();
z = getWidth();
g.setColor(Color.WHITE);
g.fillRect(0, 0, z, y);
Polygon polygon = new Polygon();
polygon.addPoint(x + 10, y - 21);
polygon.addPoint(x + 20, y - 31);
polygon.addPoint(x + 30, y - 31);
polygon.addPoint(x + 40, y - 21);
if (x < z - 50) {
g.setColor(Color.BLACK);
g.fillOval(x + 10, y - 11, 10, 10);
g.fillOval(x + 30, y - 11, 10, 10);
g.setColor(Color.BLUE);
g.fillRect(x, y - 21, 50, 10);
g.setColor(Color.GRAY);
g.fillPolygon(polygon);
g.setColor(Color.RED);
}
else {
x = 0;
/*if (c < z - 86) {
g.drawString("Clint's Car", c, y - 51);
}
else {
c = 0;
}*/
}
}
}
}
What I did for the laps loop is this:
if (k < 341){
repaint();
k++;
{
this loop was inserted at the end of:
public void paintComponent(Graphics g) {
I really am stuck here. Thanks for all the help.
Give this code a try
New RacingCar.java
By the way I made your timer be faster in order to not wait 3 laps on really slow races! :P

Custom Swing arrow button repaint() erases customiztion

I have custom arrow class, which extends BasicArrowButton. It is constructed and displayed the way I need, but then, when it is repainted (mouse over, other tab clicked, etc) arrow disappeares. How can I fix it?
public class CustomArrow extends BasicArrowButton {
private transient Color shadow = new Color(241, 241, 241);
private transient Color dark = new Color(150, 150, 150);
private static int defaultSize = 10;
/** The Polygon that points up. */
private static Polygon upIcon = new Polygon(new int[] { 0, 5, 9 },
new int[] { 7, 2, 7 }, 3);
/** The Polygon that points down. */
private static Polygon downIcon = new Polygon(new int[] { 1, 8, 19 },
new int[] { 3, 13, 3 }, 3);
/** The Polygon that points left. */
private static Polygon leftIcon = new Polygon(new int[] { 7, 3, 7 },
new int[] { 1, 5, 9 }, 3);
/** The Polygon that points right. */
private static Polygon rightIcon = new Polygon(new int[] { 3, 7, 3 },
new int[] { 1, 5, 9 }, 3);
private transient Border buttonBorder = new Border()
{
public Insets getBorderInsets(Component c)
{
return new Insets(2, 2, 2, 2);
}
public boolean isBorderOpaque()
{
return true;
}
public void paintBorder(Component c, Graphics g, int x, int y, int w, int h)
{
Color saved = g.getColor();
g.setColor(shadow);
g.drawLine(x + 1, y, x + w - 1, y);
g.setColor(dark);
g.drawLine(x, y, x, y + h + 2);
g.setColor(shadow);
g.drawLine(x + w - 1, y + 1, x + w - 1, y + h - 1);
g.setColor(shadow);
g.drawLine(x + 1, y + h - 1, x + w, y + h - 1);
g.setColor(saved);
}
};
#Override
public synchronized void addKeyListener(KeyListener l) {
super.addKeyListener(l);
}
#Override
public void addActionListener(ActionListener l) {
super.addActionListener(l);
}
public CustomArrow(int direction)
{
super(direction);
setBorder(buttonBorder);
setDirection(direction);
this.setRolloverEnabled(false);
}
public CustomArrow(int direction, Color background, Color shadow, Color darkShadow, Color highlight)
{
this(direction);
setBackground(background);
}
#Override
public void paintTriangle(Graphics g, int x, int y, int size, int direction, boolean isEnabled)
{
Polygon arrow = null;
switch (direction)
{
case NORTH:
arrow = upIcon;
break;
case SOUTH:
arrow = downIcon;
break;
case EAST:
case RIGHT:
arrow = rightIcon;
break;
case WEST:
case LEFT:
arrow = leftIcon;
break;
}
int[] xPoints = arrow.xpoints;
int[] yPoints = arrow.ypoints;
int x1;
int y1;
int x2;
int y2;
x1 = y1 = x2 = y2 = 0;
x = x - 1;
if (size != defaultSize)
{
float scale = size * 1f / defaultSize;
for (int i = 0; i < 3; i++)
{
xPoints[i] *= scale;
yPoints[i] *= scale;
}
}
g.translate(x, y);
switch (direction)
{
case NORTH:
x1 = xPoints[0] + 2;
y1 = yPoints[0];
y2 = y1;
x2 = xPoints[2] - 1;
break;
case SOUTH:
x1 = xPoints[1];
y1 = yPoints[1] + 1;
x2 = xPoints[2] - 1;
y2 = yPoints[2];
break;
case LEFT:
case WEST:
x1 = xPoints[0] + 1;
y1 = yPoints[0] + 1;
x2 = x1;
y2 = yPoints[2] + 1;
break;
case RIGHT:
case EAST:
x1 = xPoints[2];
y1 = yPoints[2] + 1;
x2 = xPoints[1] - 1;
y2 = yPoints[1] + 1;
break;
}
Color saved = g.getColor();
g.setColor(dark);
if (arrow != null) {
g.fillPolygon(xPoints, yPoints, 3);
}
g.setColor(saved);
g.translate(-x, -y);
}
public static void main(String[] args) {
// Resize the frame to reproduce
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new CustomArrow(SwingConstants.NORTH));
frame.setSize(400, 400);
frame.setVisible(true);
}
}
Array variables hold references to the array, not the array itself (just like Object variables). When you do something like
int[] xPoints = arrow.xpoints;
int[] yPoints = arrow.ypoints;
you are copying the reference, not the data, meaning that xPoints and arrow.xpoints still point at the same data and modifying either will affect the other. When you later scale these points, you're changing how the arrow will look every future time it is drawn.
If you want to copy the array data to avoid this, you can use System.arraycopy:
int[] xPoints = new int[3]; //arrow.xpoints;
int[] yPoints = new int[3]; //arrow.ypoints;
System.arraycopy(arrow.xpoints, 0, xPoints, 0, 3);
System.arraycopy(arrow.ypoints, 0, yPoints, 0, 3);
However, you can simply scale the graphics object instead of scaling your reference points:
Graphics2D g2 = (Graphics2D) g;
float scale = size * 1f / defaultSize;
g2.scale(scale, scale);

Eclipse: Java, no main method found

I recently took all my code a manually imported it into an eclipse project from BlueJ, I then got use to the settings up "Run Configurations", finally thinking I was home free. Then I ran the code, and I got this error
java.lang.NoSuchMethodError: main
Exception in thread "main"
so I figured I had to add a main method (I never had to do this in BlueJ, why?). So I did that just called the constructor method (in BlueJ I would just create a new object and the JFrame would show). So I did that, same error. After trying different things (such as moving the code in the constructor to a different method etc.). I just put this in for the main method:
public void main(String[] args)
{
System.out.println("Hello, this is main why won't Java find this.");
}
After that I still got the same error, so I then decided to add it to all my classes to make sure it wasn't using another class as the main class. Still same error, so I come to you wondering if any of you have encountered this problem. Also I did search Google and all I found was problems with private classes etc and sense all my classes are public (hey I come from Python :) ). I knew that wasn't the problem. Help Please :)
Picture of my Run Configuration
This is my main method code
WARNING: LONG
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class AppFrame extends JFrame
{
public String status = "Status:";// Status of Applet
public int paint_count = 1;// Number of times applet has been painted
public int[] mousePos = {-1, -1};// Stores Mouse's Last Clicked X and Y Cordinates
public int[] boardPos = {-1, -1};//Stores The Board's X and Y Cordinates
public int[] selectedSquarePos = {-1, -1};
public int[] boardSquare = {-1, -1};//Stores Last Clicked Square
public Color P1_Color = Color.GRAY;
public Color P2_Color = Color.WHITE;
public Color SquareEven = Color.BLACK;
public Color SquareOdd = Color.RED;// pieces move on this one
public int boardHeight = 400;
public int boardWidth = 400;
public boolean pieceSelected = false;
public boolean CheckersPiece = false;
public Board CheckersBoard = new Board();
public Image buffer = null;
public Graphics bg = null;
public void main(String[] args)
{
System.out.println("Hello, this is main why won't Java find this.");
}
public AppFrame()
{
super("JCheckers");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(900,900);
setVisible(true);
buffer = createImage(getWidth(), getHeight());
boardHeight = getHeight() - 40; // 20 pixel border at top and bottom and 20 pixels for blue bar
boardWidth = getWidth() - 40; // 20 pixel border at left and right
bg = buffer.getGraphics();
addMouseListener(new MouseAdapter()
{
public void mouseClicked (MouseEvent e)
{
handleClick(e);
}
}
);
}
public void handleClick(MouseEvent e)
{
/* Handles tracking of mouse clicks; DOES NOT HANDLE DISPLAY, it just updates the data and calls redraw */
mousePos[0] = e.getX();
mousePos[1] = e.getY();
repaint();
}
public void paint(Graphics g)
{
super.paint(g);
render(g);
}
public void render(Graphics g)
{
bg.clearRect(0,0, getWidth(), getHeight());
//Draw Chess Board and Pieces
renderChessBoard(bg, 20, 20);
// Display Info
System.out.println(status);
System.out.println(String.format("Last Mouse Click # (X:%d Y:%d)", mousePos[0], mousePos[1]) );
System.out.println("Paint #" + paint_count );
System.out.println(String.format("Board Square (x:%s, y:%s) %b", boardSquare[0], boardSquare[1], CheckersPiece) );
System.out.println(CheckersBoard.status );
paint_count += 1;
// Draw Image to Screen
g.drawImage(buffer, 0, 25, null);// so it does not get hidden by the blue close/min/max room
}
public boolean isValidSquare(int col, int row)
{
if (col > -1 & col < 8) {return true;}
return false;
}
public void renderChessBoard(Graphics g, int x, int y)
{
/* Renders board and pieces*/
// sense the row squares are well squares then the
// board will be a square also; so we draw it with whatever
// side is smallest, width or height
boardPos[0] = x;
boardPos[1] = y;
drawBoard(g, x, y, boardWidth, boardHeight);
boardSquare = getBoardSquare(mousePos[0], mousePos[1]);
CheckersPiece = isCheckersPiece(boardSquare[0], boardSquare[1]);
boolean validSquare = isValidSquare(boardSquare[0], boardSquare[1]);
if (validSquare)
{
if (CheckersPiece)
{
selectSquare(g, boardSquare[0], boardSquare[1]);
}
else
{
if (pieceSelected)
{
int selectedCol = selectedSquarePos[0];
int selectedRow = selectedSquarePos[1];
int toCol = boardSquare[0];
int toRow = boardSquare[1];
System.out.println(selectedCol + " " + selectedRow + " " + toCol + " " + toRow);
if (!CheckersBoard.move(selectedSquarePos, boardSquare)) // not a valid move;
{
pieceSelected = false;
}
}
}
}
parseBoard(CheckersBoard.board, g);
}
public void drawBoard(Graphics g, int Bx, int By, int Bw, int Bh)
{
int numberRowsDrawed = 0;
int rH = Bh / 8;
int rW = Bw; // Row width is the same as the Board's width because the board and the row share the same sides
while (numberRowsDrawed < 8)
{
int rY = (numberRowsDrawed * rH) + By;
// Row X is the same as the Board X because the board and the row share the same sides
int rX = Bx;
Color EVEN = SquareEven;
Color ODD = SquareOdd;
// Yes Yes The EVEN Color is now odd and vica versa its because rows only now there row counts and so they start at 0 and don't
// include the rows above
if ((numberRowsDrawed % 2) != 0) {EVEN = SquareOdd; ODD = SquareEven;}
drawRow(g, rX, rY, rW, rH, EVEN, ODD);
numberRowsDrawed +=1;
}
}
public void drawRow(Graphics g, int x, int y, int width, int height, Color EVEN, Color ODD)
{
System.out.println("Board Y: " + y);
int squareW = width / 8;
int squareH = height;
int numberSquaresCreated = 0;
while (numberSquaresCreated < 8)
{
// needs a special case because Java's modulo uses division (so it would give a divide by 0 error) STUPID JAVA!!!!!!
if (numberSquaresCreated == 0)
{
g.setColor(EVEN);
g.fillRect(x, y, squareW, squareH);
}
else
{
if (numberSquaresCreated % 2 == 0){g.setColor(EVEN);}
else {g.setColor(ODD);}
int sX = x + (squareW * numberSquaresCreated);
g.fillRect(sX, y, squareW, squareH);
}
numberSquaresCreated +=1;
}
}
public void drawMan(Graphics g, int boardRow, int boardCol, Color pieceColor)
{
int x = boardPos[0];
int y = boardPos[1];
int pixelPosX = x + ((boardWidth / 8) * boardRow);
int pixelPosY = y + ((boardHeight / 8) * boardCol);
g.setColor(pieceColor);
g.fillOval(pixelPosX + 13, pixelPosY + 13, (boardWidth / 8) - 26, (boardHeight / 8) - 26);
}
public void drawKing(Graphics g, int boardRow, int boardCol, Color pieceColor, Color crownColor)
{
drawMan(g, boardRow, boardCol, pieceColor);
g.setColor(crownColor);
int x = boardPos[0];
int y = boardPos[1];
double DsizeFactor = ( (float) boardHeight / 8.0) / 3.75;
int sizeFactor = (int) DsizeFactor;
int pixelPosX = x + ((boardWidth / 8) - sizeFactor) / 2 + ((boardWidth / 8) * boardRow);
int pixelPosY = y + ((boardHeight / 8) - sizeFactor) / 2 + ((boardHeight / 8) * boardCol);
int[] xPoints = {pixelPosX, pixelPosX, pixelPosX + sizeFactor, pixelPosX + sizeFactor, pixelPosX + ((sizeFactor * 3) / 4), pixelPosX + (sizeFactor / 2), pixelPosX + (sizeFactor / 4) };
int[] yPoints = {pixelPosY, pixelPosY + sizeFactor, pixelPosY + sizeFactor, pixelPosY, pixelPosY + (sizeFactor / 2), pixelPosY, pixelPosY + (sizeFactor / 2)};
g.fillPolygon(xPoints, yPoints, 7);
}
public void selectSquare(Graphics g, int bSX, int bSY)
{
g.setColor(Color.YELLOW);
/*+10 is to offset text (the xy cordinates are the bottom left side of the text NOT top left.*/
pieceSelected = true;
int squareX = boardPos[0] + (boardWidth / 8) * bSX;
int squareY = 10 + boardPos[1] + (boardHeight / 8) * bSY;
selectedSquarePos[0] = bSX;
selectedSquarePos[1] = bSY;
g.drawString("Selected", squareX, squareY);
}
// Data Handling and Retreiving methods
public void parseBoard(String[][] Board, Graphics g)
{
int row = 0;
int col = 0;
for (String[] rowOfPieces : Board)
{
for (String piece : rowOfPieces)
{
if (piece != "X")
{
Color PIECE_COLOR = P1_Color;
if (piece.contains("P2")) {PIECE_COLOR = P2_Color;}
if (piece.contains("C"))
{
drawMan(g, col, row, PIECE_COLOR);
}
if (piece.contains("K"))
{
Color Crown_Color = P2_Color;
if (PIECE_COLOR != P1_Color) {Crown_Color = P1_Color;}
drawKing(g, col, row, PIECE_COLOR, Crown_Color);
}
}
col+=1;
}
row +=1;
col = 0;
}
}
public int[] getBoardSquare(int x, int y)
{
//row or col = boardpos - offset / row height or width
if ((x < boardPos[0]) | (y < boardPos[1]) | (x > (boardPos[0] + boardWidth)) | (y > (boardPos[1] + boardHeight)) )
{
int[] BS = {-1, -1};
return BS;
}
int col = (x - boardPos[0]) / (boardWidth / 8);
int row = (y - boardPos[1]) / (boardHeight / 8);
int[] BS = {col, row};
return BS;
}
public boolean isCheckersPiece(int BoardSquareX, int BoardSquareY)
{
int Px = BoardSquareX;
int Py = BoardSquareY;
if (Px == -1 & Py == -1)
{
return false;
}
String Square = CheckersBoard.board[Py][Px];
return Square != "X";
}
}
You forgot static:
public static void main(String[] args)
But in order to really start your application, you should launch it from that method, not merely have it. Here is how to start it:
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
AppFrame frame = new AppFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
});
}
It's important to note the EXIT_ON_CLOSE - this will make the JVM exit when you press the X button. Otherwise your application will continue running, and you might even not notice.
Make main static.

Categories