java - How to declare chess pieces in a chess game? -
im coding chess game actually. made chessboard cases , can coordinates.
my question : how can make (by example) pawn class attributes (color etc..) game.
thanks everyone!
my code :
package coordboutons; import java.awt.color; import java.awt.container; import java.awt.dimension; import java.awt.eventqueue; import java.awt.gridlayout; import java.awt.event.actionevent; import java.awt.event.mouseadapter; import java.awt.event.mouseevent; import javax.swing.jframe; import javax.swing.jpanel; public class coordboutons extends jframe { coordboutons() { super("gridlayout"); setdefaultcloseoperation(exit_on_close); container contenant = getcontentpane(); contenant.setlayout(new gridlayout(8, 8)); (int = 0; < 8; i++) { (int j = 0; j < 8; j++) { contenant.add(new caseechiquier(i, j)); } } pack(); setvisible(true); } class caseechiquier extends jpanel { private int lin, col; private char column; caseechiquier(int i, int j) { lin = i; col = j; setpreferredsize(new dimension(80, 75)); setbackground((i + j) % 2 == 0 ? color.white : color.gray); addmouselistener(new mouseadapter() { @override public void mousepressed(mouseevent e){ caseechiquier current =(caseechiquier)e.getsource(); // object user pressed int linx = current.getlin(); int coly = current.getcol(); system.out.println(lin+" "+col); } }); } public int getcol() { return col; } public int getlin() { return lin; } } public static void main(string[] args) { eventqueue.invokelater(new runnable() { @override public void run() { jframe.setdefaultlookandfeeldecorated(true); coordboutons coordboutons = new coordboutons(); } }); } }
probably way go first defining abstract piece class (which define functions getcolor()
, getposition()
, setposition(x,y)
, , require implementation of getmovementoptions
, , on). can make 6 different classes extend piece
: pawn, rook, knight, bishop, queen, , king. each of these can implement getmovementoptions
appropriate.
the advantage of using base class can treat pieces same way when you're writing code play game: choose piece p
, , move legal square defined call p.getmovementoptions()
(or end defining method; needs access board position, instance).
public abstract class piece { public color getcolor() { return this.color; } public void setcolor(color c) { this.color = c; } public square getposition() { return this.position; } public void setposition(square p) { this.position = p; } public list<square> getmovementoptions(board b); } public class pawn extends piece { public list<square> getmovementoptions(board b) { // forward zero, one, or 2 squares, or capture diagonally 1 square ahead! // list based on this.position , given board. } }
Comments
Post a Comment