So, basically I'm trying to use a char array for a character sprite for my game prototype right now, but I cannot find a working way to read each element in the correct 'row' to print out the character (trying to find a way to draw the sprite by using fill rects line by line of arrays). Again, I've tried many ways such as if (i % 5 == 0) y_temp += 5;
for "indenting" to fill rectangles of the sprite on a new row, but none of it is working.
Suggestions/help anyone?
Code:
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);
}
}
}
}
}
If I understand you correctly, you should get the right coordinates like this: x = i % 5; y = i / 5;
x = i % 5; y = i / 5;
. So then, you can fillRect(x*5, y*5, 5, 5);
.
EDIT: I just saw that additional space. This means you will have to subtract one first:
x = (i-1) % 5; y = (i-1) / 5;
EDIT 2: Yeah, and then of course you will have to add y_pos
and x_pos
: fillRect(x_pos + x*5, y_pos + y*5, 5, 5);
int x = (i-1)%5;
int y = (i-1)/5;
fillRect( x_pos + x*5, y_pos + y*5, 5, 5 );
*Note that it is important to divide then multiply because
n (not always)== (n/5)*5
in integer arithmetic.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.