package battaglianavale; import java.awt.*; /** * Implementazione dell'interfaccia in modalità grafica * * @author Antonio Turi * @version 06 */ class CampoCanvas extends Canvas { /** * costante richiesta per la serializzazione */ private static final long serialVersionUID = 1L; /** * dimensioni del canvas */ private int larghezza, altezza, cellSize; /** * spazio tra le celle */ private final int SPACING = 1; /** * offset del canvas */ private final int OFFSET = 10; /** * griglia associata da rappresentare */ private Griglia campodibattaglia = null; /** * disegna le navi? */ private boolean nascondi_navi = false; /** * Costruttore di classe */ public CampoCanvas(int larghezza, int altezza, int cellSize, boolean nascondi_navi) { int canvasSizeX = larghezza * cellSize + (larghezza - 1) * this.SPACING + this.OFFSET * 2; int canvasSizeY = altezza * cellSize + (altezza - 1) * this.SPACING + this.OFFSET * 2; this.setSize(canvasSizeX, canvasSizeY + this.OFFSET * 2); this.larghezza = larghezza; this.altezza = altezza; this.cellSize = cellSize; this.nascondi_navi = nascondi_navi; } /** * Associa griglia */ public void setCampo(Griglia campodibattaglia) { this.campodibattaglia = campodibattaglia; } /** * paint canvas */ public void paint(Graphics g) { repaintBoard(g); } /** * update canvas */ public void update(Graphics g) { repaintBoard(g); } /** * diplay del canvas */ public void repaintBoard(Graphics g) { int x, y; if (campodibattaglia != null) { for (x = 0; x < larghezza; x++) { int x1 = OFFSET + (x + 1) * (cellSize + SPACING); for (y = 0; y < altezza; y++) { int y1 = OFFSET + (y + 1) * (cellSize + SPACING); if (campodibattaglia.isNave(x, y)) { if (campodibattaglia.isBombardata(x, y)) { g.setColor(Color.red); g.fillRect(x1,y1,cellSize, cellSize); } else { if (!nascondi_navi) { g.setColor(Color.green); g.fillRect(x1,y1,cellSize, cellSize); } } } else { if (campodibattaglia.isBombardata(x, y)) { g.setColor(Color.yellow); g.fillRect(x1,y1,cellSize, cellSize); g.setColor(Color.blue); g.fillOval(x1 + 3,y1 + 3,cellSize - 6, cellSize - 6); } else { g.setColor(Color.yellow); g.fillRect(x1,y1,cellSize, cellSize); } } } } } else { y = 0; for (x = 0; x < larghezza; x++) { int x1 = OFFSET + (x+1) * (cellSize + SPACING); int y1 = OFFSET + y * (cellSize + SPACING); g.setColor(Color.blue); g.fillRect(x1,y1 , cellSize,cellSize); g.setColor(Color.white); g.drawString(new Integer(x).toString(), x1+3, y1 + cellSize-2); } x = 0; for (y = 0; y < altezza; y++) { int x1 = OFFSET + x * (cellSize + SPACING); int y1 = OFFSET + (y+1) * (cellSize + SPACING); g.setColor(Color.blue); g.fillRect(x1,y1, cellSize, cellSize); g.setColor(Color.white); g.drawString(new Integer(y).toString(), x1+3, y1+ cellSize-2); } g.setColor(Color.yellow); for (x = 0; x < larghezza; x++) { for (y = 0; y < altezza; y++) { int x1 = OFFSET + (x+1) * (cellSize + SPACING); int y1 = OFFSET + (y+1) * (cellSize + SPACING); g.fillRect(x1, y1, cellSize, cellSize); } } } } }