您好,登錄后才能下訂單哦!
本文為大家分享了java畫出五子棋游戲棋盤的方法,供大家參考,具體內容如下
棋盤模塊:
畫五子棋棋盤:19條橫線、19條豎線
步驟一:顯示棋盤
我有一張名為chessboard.png的棋盤,位置為根目錄/res/drawable/chessboard/png,現在我要顯示這張圖片。
DrawChessBoard.java
package xchen.test.simpleGobang; import java.awt.Graphics; import java.awt.Image; import java.awt.Toolkit; import javax.swing.JPanel; public class DrawChessBoard extends JPanel{ public Image boardImg; public DrawChessBoard() { boardImg = Toolkit.getDefaultToolkit().getImage("res/drawable/chessboard.png"); if(boardImg == null) System.err.println("png do not exist"); } @Override protected void paintComponent(Graphics g) { // TODO Auto-generated method stub super.paintComponent(g); int imgWidth = boardImg.getWidth(this); int imgHeight = boardImg.getHeight(this); int FWidth = getWidth(); int FHeight= getHeight(); int x=(FWidth-imgWidth)/2; int y=(FHeight-imgHeight)/2; g.drawImage(boardImg, x, y, null); } }
Main.java
package xchen.test.simpleGobang; import java.awt.Container; import javax.swing.JFrame; import xchen.test.simpleGobang.DrawChessBoard; public class Main extends JFrame{ private DrawChessBoard drawChessBoard; public Main() { drawChessBoard = new DrawChessBoard(); //Frame標題 setTitle("單機五子棋"); Container containerPane =getContentPane(); containerPane.add(drawChessBoard); } public static void main(String[] args) { Main m = new Main(); m.setVisible(true); } }
運行一下
步驟二:為棋盤畫上橫豎線
DrawChessBoard.java
package xchen.test.simpleGobang; import java.awt.Graphics; import java.awt.Image; import java.awt.Toolkit; import javax.swing.JPanel; public class DrawChessBoard extends JPanel{ public Image boardImg; final private int ROWS = 19; public DrawChessBoard() { boardImg = Toolkit.getDefaultToolkit().getImage("res/drawable/chessboard2.png"); if(boardImg == null) System.err.println("png do not exist"); } @Override protected void paintComponent(Graphics g) { // TODO Auto-generated method stub super.paintComponent(g); int imgWidth = boardImg.getWidth(this); int imgHeight = boardImg.getHeight(this); int FWidth = getWidth(); int FHeight= getHeight(); int x=(FWidth-imgWidth)/2; int y=(FHeight-imgHeight)/2; g.drawImage(boardImg, x, y, null); int margin = x; int span_x=imgWidth/ROWS; int span_y=imgHeight/ROWS; //畫橫線 for(int i=0;i<ROWS;i++) { g.drawLine(x, y+i*span_y, FWidth-x,y+i*span_y); } //畫豎線 for(int i=0;i<ROWS;i++) { g.drawLine(x+i*span_x, y, x+i*span_x,FHeight-y); } } }
Main.java不變
運行一下
遇到的問題:
1)Eclipse不識別文件夾下的圖片
問題:文件夾中有圖片,但是在Eclipse項目欄中不顯示
解決辦法:在Eclipse中,選中根目錄,F5 refresh,就顯示出來了。
更多有趣的經典小游戲實現專題,分享給大家:
C++經典小游戲匯總
python經典小游戲匯總
python俄羅斯方塊游戲集合
JavaScript經典游戲 玩不停
java經典小游戲匯總
javascript經典小游戲匯總
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。