ZBLOG

import java.awt.*; import java.awt.event.*; import javax.swing.*; public class MyFrame extends JFrame { public static void createAndShow() { //设置窗口 JFrame frame=new JFrame("推箱子游戏--王子救公主"); frame.setDefaultCloseOp

To draw a map on the canvas and insert the map matrix from the Map class into the MyFrame class, you can do the following:

  1. Create a method in the MyCanvas class to draw the map using Graphics.
  2. Pass the map matrix from the GameMapSet object to MyCanvas through its constructor.
  3. Call the drawMap method in MyCanvas from within the actionPerformed method of button1 ActionListener.

Here’s an example code snippet for drawing a simple grid-based map with different colors for different types of tiles:

import java.awt.*;

public class MyCanvas extends Canvas {

private static final int TILE_SIZE = 40; // size of each tile in pixels
private GameMapSet map;

public MyCanvas(GameMapSet map) {
    this.map = map;
}

public void drawMap(Graphics g) {
    for (int row = 0; row < map.getHeight(); row++) {
        for (int col = 0; col < map.getWidth(); col++) {
            int x = col * TILE_SIZE;
            int y = row * TILE_SIZE;

            switch(map.getTile(row, col)) {
                case WALL:
                    g.setColor(Color.GRAY);
                    break;
                case BOX:
                    g.setColor(Color.ORANGE);
                    break;
                case GOAL:
                    g.setColor(Color.YELLOW);
                    break;
                default: // EMPTY
                    g.setColor(Color.WHITE);
                    break;
            }

            g.fillRect(x, y, TILE_SIZE, TILE_SIZE);
        }
    }
}

}

And here’s how you can use it in your button1 ActionListener:

button1.addActionListener(new ActionListener() {

@Override
public void actionPerformed(ActionEvent e) {
    frame.getContentPane().removeAll();

    JPanel panel2=new JPanel();
    panel2.setBackground(new Color(255,217,229));

    Canvas canvas=new MyCanvas(map);
    canvas.setPreferredSize(new Dimension(map.getWidth() * TILE_SIZE, map.getHeight() * TILE_SIZE));

    panel2.add(canvas);
    frame.setContentPane(panel2);

    JButton button8=new JButton("我还是喜欢灰姑娘,不救公主了(闯不过,退出关卡)");
    button8.setBackground(Color.PINK);
    button8.setBorder(BorderFactory.createRaisedBevelBorder());
    panel2.add(button8,BorderLayout.SOUTH);

    frame.revalidate();
    frame.setVisible(true);

    Graphics g = canvas.getGraphics();
    ((MyCanvas)canvas).drawMap(g);
}

});

Note that this is just a simple example and you may need to modify it according to your specific requirements. Also, make sure to handle the case where the map matrix is null or empty.

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=5278

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?