2

所以,基本上我现在正在尝试为我的游戏原型的角色精灵使用 char 数组,但我找不到一种工作方法来读取正确“行”中的每个元素以打印出角色(试图找到一个使用逐行填充矩形来绘制精灵的方法)。同样,我尝试了许多方法,例如if (i % 5 == 0) y_temp += 5;“缩进”以在新行上填充精灵的矩形,但没有一种方法有效。
建议/帮助任何人?

代码:

import java.awt.*;
import java.awt.event.*;  
import javax.swing.*;

public class test extends JFrame {
    private int x_pos, y_pos;
    private JFrame frame;
    private draw dr;
    private char[] WARRIOR;
    private Container con;
    public test() {
        x_pos = y_pos = 200;
        frame = new JFrame("StixRPG");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(1000, 500);
        frame.setResizable(false);
        frame.setVisible(true);
        con = frame.getContentPane();
        con.setBackground(Color.black);
        dr = new draw();
        dr.setBackground(Color.black);
        con.add(dr);
        WARRIOR = (
      " " +
        "!!!!!" +
        "!!ooo" +
        "!!!!!" +
        "#####" +
        "#####" +
        "#####" +
        "** **").toCharArray();
    }
    public static void main(String[] args) {
        test tst = new test();
    }
    class draw extends JPanel { 
        public draw() {
        }
        public void paintComponent(Graphics g) {
            super.paintComponents(g);
             int y_temp = y_pos;
            for (int i = 0; i < WARRIOR.length; i++) {
                 if (WARRIOR[i] == '!') {
                     g.setColor(new Color(0, 0, 204));
                    g.fillRect(x_pos+i*5, y_temp, 5, 5);
                }
                else if (WARRIOR[i] == 'o') {
                    g.setColor(new Color(204, 0, 0));
                    g.fillRect(x_pos+i*5, y_temp, 5, 5);
                }
                else if (WARRIOR[i] == '#') {
                    g.setColor(new Color(0, 0, 102));
                    g.fillRect(x_pos+i*5, y_temp, 5, 5);
                }
                else if (WARRIOR[i] == '*') {
                    g.setColor(Color.black);
                     g.fillRect(x_pos+i*5, y_temp, 5, 5);
                }
            }
        }   
    }   
}
4

2 回答 2

1

如果我理解正确,您应该得到正确的坐标,如下所示:x = i % 5; y = i / 5;. 那么,您可以fillRect(x*5, y*5, 5, 5);.

编辑:我刚刚看到那个额外的空间。这意味着您必须先减去一个:
x = (i-1) % 5; y = (i-1) / 5;

编辑2:是的,然后当然你必须添加y_posx_posfillRect(x_pos + x*5, y_pos + y*5, 5, 5);

于 2012-05-07T19:46:46.437 回答
0
int x = (i-1)%5;
int y = (i-1)/5;

fillRect( x_pos + x*5, y_pos + y*5, 5, 5 );

*请注意,除然后乘很重要,因为

n (not always)== (n/5)*5

在整数算术中。

于 2012-05-07T19:48:07.990 回答