有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何使用for循环从字符数组中绘制精灵

所以,基本上我现在正在尝试为我的游戏原型使用一个字符数组作为一个角色精灵,但是我找不到一种有效的方法来读取正确“行”中的每个元素以打印出角色(试图找到一种方法通过使用填充矩形逐行数组来绘制精灵)。再一次,我尝试了很多方法,比如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);
                }
            }
        }   
    }   
}

共 (2) 个答案

  1. # 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_pos:fillRect(x_pos + x*5, y_pos + y*5, 5, 5);

  2. # 2 楼答案

    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
    

    在整数算术中