所以,基本上我现在正在尝试为我的游戏原型(prototype)使用字符数组作为角色 Sprite ,但我找不到一种有效的方法来读取正确“行”中的每个元素以打印出角色(尝试找到一种通过逐行数组填充矩形来绘制 Sprite 的方法)。同样,我尝试了很多方法,例如 if (i % 5 == 0) y_temp += 5;
用于“缩进”以在新行上填充 Sprite 的矩形,但都没有正在工作。
建议/帮助任何人?
代码:
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);
}
}
}
}
}
最佳答案
如果我没理解错的话,你应该得到这样的正确坐标:x = i % 5; y = i/5;
。那么,您可以 fillRect(x*5, y*5, 5, 5);
。
编辑: 我刚刚看到那个额外的空间。这意味着您必须先减去一个:
x = (i-1) % 5; y = (i-1)/5;
编辑 2: 是的,然后您当然必须添加 y_pos
和 x_pos
:fillRect(x_pos + x *5, y_pos + y*5, 5, 5);
关于java - 如何使用 for 循环从 char 数组中绘制 Sprite ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10488071/