本文為大家分享了java畫出五子棋游戲棋盤的方法,供大家參考,具體內(nèi)容如下
專業(yè)從事成都做網(wǎng)站、成都網(wǎng)站建設,高端網(wǎng)站制作設計,小程序設計,網(wǎng)站推廣的成都做網(wǎng)站的公司。優(yōu)秀技術團隊竭力真誠服務,采用H5網(wǎng)站設計+CSS3前端渲染技術,響應式網(wǎng)站建設,讓網(wǎng)站在手機、平板、PC、微信下都能呈現(xiàn)。建站過程建立專項小組,與您實時在線互動,隨時提供解決方案,暢聊想法和感受。
棋盤模塊:
畫五子棋棋盤:19條橫線、19條豎線
步驟一:顯示棋盤
我有一張名為chessboard.png的棋盤,位置為根目錄/res/drawable/chessboard/png,現(xiàn)在我要顯示這張圖片。
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
Main.java不變
運行一下
遇到的問題:
1)Eclipse不識別文件夾下的圖片
問題:文件夾中有圖片,但是在Eclipse項目欄中不顯示
解決辦法:在Eclipse中,選中根目錄,F(xiàn)5 refresh,就顯示出來了。
更多有趣的經(jīng)典小游戲?qū)崿F(xiàn)專題,分享給大家:
C++經(jīng)典小游戲匯總
python經(jīng)典小游戲匯總
python俄羅斯方塊游戲集合
JavaScript經(jīng)典游戲 玩不停
java經(jīng)典小游戲匯總
javascript經(jīng)典小游戲匯總
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持創(chuàng)新互聯(lián)。