有 Java 编程相关的问题?

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

java需要一种方法来“翻转”这个字符数组,以便游戏精灵向左看

所以,基本上我需要找到一个好方法来“翻转”一个用于精灵的字符数组,以使他/它看起来向左,反之亦然。这是我的阵列->

WARRIOR = (

" " +         
 "!!!!!     " +        
 "!!oo! ^   " +
 "!!!!! ^   " +
 "##### ^   " +
 "#######   " +
 "#####     " +
 "** **     ").toCharArray();

显示例程如下所示:

public void paintComponent(Graphics g) {
    super.paintComponent(g);
    for (int i = 0; i < WARRIOR.length; i++) {
        int x = (i - 1) % 10;
        int y = (i - 1) / 10;
        if (WARRIOR[i] == '!') {
            g.setColor(new Color(0, 0, 204));
            g.fillRect(x_pos + x * 5, y_pos + y * 5, 5, 5);
        }
        else if (WARRIOR[i] == 'o') {
            g.setColor(new Color(204, 0, 0));
            g.fillRect(x_pos + x * 5, y_pos + y * 5, 5, 5);
        }
        // other characters here...
    }
}​

共 (2) 个答案

  1. # 1 楼答案

    在不改变数据结构的情况下,这里有一个解决方案(我相信它可以改进,但它是有效的):

    短版

    char[] flip = new char[warrior.length];
    
    for(int i=0;i<warrior.length;i++){
        flip[9-i%10+ i/10*10] = warrior[i];   
    }
    

    长版本

        char[] warrior= (         
                 "!!!!!     " +        
                 "!!oo! ^   " +
                 "!!!!! ^   " +
                 "##### ^   " +
                 "#######   " +
                 "#####     " +
                 "** **     ").toCharArray();
    
        for(int i=0;i<warrior.length;i++){
            if(i%10==0){
                System.out.println();
            }
            System.out.print(warrior[i]);
        }
    
        char[] flip = new char[warrior.length];
    
        for(int i=0;i<warrior.length;i++){
            //9-: 0 goes to 9, 1 to 8 etc 
            //i: cycles from 0 to 9
            //i/10: provides the row (e.g. 25/10=2)
            //*10: gives me the 2d row in 1d array  
    
            flip[9-i%10+ i/10*10] = warrior[i]; 
        }
    
    
        for(int i=0;i<flip.length;i++){
            if(i%10==0){
                System.out.println();
            }
            System.out.print(flip[i]);
        }
    

    这将输出

    !!!!!     
    !!oo! ^   
    !!!!! ^   
    ##### ^   
    #######   
    #####     
    ** **     
         !!!!!
       ^ !oo!!
       ^ !!!!!
       ^ #####
       #######
         #####
         ** **
    

    但我会使用不同的数据结构(例如2D数组) 或者把它想象成一个矩阵,使用example in this article

  2. # 2 楼答案

    我建议使用另一个显示例程来向后绘制精灵,而不是存储精灵的反向副本

    尝试更改这一行:

    int x = (i - 1) % 10;
    

    为此:

    int x = 10 - (i - 1) % 10;
    

    这应该会将精灵向后拉


    另外,您可能想看看XPM格式,它与您正在做的非常相似