Java实现两人五子棋游戏(二) 画出棋盘
作者:v_xchen_v
这篇文章主要为大家详细介绍了Java实现两人五子棋游戏,画出五子棋的棋盘,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
本文为大家分享了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,就显示出来了。
更多有趣的经典小游戏实现专题,分享给大家:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。