我用Java创建了一个棋盘游戏,原理上与棋子没有什么不同.它在控制台中工作正常,但现在我正在尝试创建图形.我有一个Piece类,一个Tile类,它检查它是否为空或被白色或黑色的棋子片段占用,Grid类跟踪矩阵中的瓦片,以及Game类.
目前,游戏可以在Grid类中播放; 当我们运行Grid类时,用户在控制台中指定棋盘的大小,然后通过给出用户希望选择的棋子的x和y坐标来玩游戏.我想改变的是在Game类中运行游戏,它是JPanel的扩展并实现MouseListener(下面给出的代码).游戏板将是一个固定的大小(我将从5x5开始),我画了一个应该在游戏背景中的网格图片.将有一个实例变量(Grid g = new Grid(5,5)).我还画了将要使用的不同"跳棋"片段的图片,它们应该在特定的瓷砖上分布在前景中.我想要发生的是当用户点击一块瓷砖时,棋子会移动.理想情况下,我会这样做,以便程序看到鼠标点击的地方的坐标(说JPanel是500x500像素,用户点击带坐标的像素(0,500),然后我们检查是否(0,500)属于一些瓷砖,如果它没有那么没有任何反应,如果它确实属于网格上的瓷砖g然后g.play(某事,某事)).
import java.awt.Color; import java.awt.FlowLayout; import java.awt.Graphics; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.JFrame; import javax.swing.JLabel; import java.util.*; import java.awt.*; import java.awt.event.*; import java.awt.FlowLayout; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.*; public class Game extends JPanel implements MouseListener { private Grid g = new Grid(5,5); public Game() { JFrame frame = new JFrame("Boardgame"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLayout(new FlowLayout()); frame.setLayout(new FlowLayout()); frame.setPreferredSize(new Dimension(500,500)); frame.pack(); frame.setVisible(true); frame.addMouseListener(this); } public void mouseClicked(MouseEvent e) { //here we check if the user clicked on a tile, if that happens then we get the x and y-coordinates of the tile and then g.play(x,y) } public void mouseEntered(MouseEvent e) { // we are not really interested in this method or the following mouse methods but they are necessary for the mouselistener } public void mouseExited(MouseEvent e) { } public void mousePressed(MouseEvent e) { } public void mouseReleased(MouseEvent e) { } public static void main(String args[]) { new Game(); } }
所以从本质上讲,我想做的是:
i)有背景图片(这很容易吗?)[更新:我通过使用JLabel完成了这项工作,如果还有更好的方法可以告诉我].
ii)修复MouseListener,以便在单击图块时移动块.我需要的唯一输入是移动哪个瓷砖,我们不需要知道应该去哪个瓷砖.
任何帮助将非常感谢,请问我是否可以澄清一些事情.这不是学校或任何事情,只是一个私人项目.
您可以使用Shape并附加侦听器来捕获对形状的用户操作.
要使用户能够与您显示的图形进行交互,您需要能够确定用户何时单击其中一个图形.Graphics2D类的命中方法提供了一种方法,可以轻松确定是否在特定Shape对象上发生鼠标单击.或者,您可以获取鼠标单击的位置,并在Shape上调用contains以确定单击是否在Shape的边界内.
请阅读http://docs.oracle.com/javase/tutorial/2d/advanced/user.html