Search code examples
java2d-games

How to print a string in a character array?


I am working on the tortoise and hare game, and everything works except I want to print out "OUCH" when the hare and the tortoise are in the same position. My race track is a character array so I can only put 'O', and whenever I try to print it as a string "OUCH" it prints it as a separate new line. Is there a way to print "OUCH" without breaking up the flow of the game, and outputting it on a different line to everything else?

public static int turtlePosition = 0;        // Turtle location
public static int harePosition = 0;          // Hare location
public static char[] track = new char [70];  // Array for Track


public static void main(String[] args) {

    System.out.println("AND THEY ARE OFF!!");

    while (!gameOver()){

        for (int i = 0; i < track.length; i++){

            track[i] = '-';
        }

        Random random = new Random();
        int r = random.nextInt(10) + 1;

        turtleMove(r);
        hareMove(r);

        if (gameOver()){
            break;
        }

        track[turtlePosition] = 'T';
        track[harePosition] = 'H';

        if (turtlePosition == harePosition){
            String str = String.valueOf(track[turtlePosition]);
            str = "OUCH";
            System.out.println(str);
        }

        for (int i = 0; i < track.length; i++)
        {
            System.out.print(track[i]);
        }

        System.out.println();
    }

    if (turtlePosition >= 70 && harePosition >= 70){
        System.out.println("IT'S A TIE!!");
    }
    else if (turtlePosition >= 70){
        System.out.println ("TORTOISE WINS!!");
    }
    else {
       System.out.println ("HARE WINS!!");
    }

Solution

  • i don't believe so but you could put a text area to the side.

    like this:

    Code changes:

            if (turtlePosition>=6 || harePosition>=6){
                turtlePosition = 7;
                harePosition = 7;
            }
    
            track[turtlePosition] = 'T';
            track[harePosition] = 'H';
            
            if (turtlePosition == harePosition){
                insertintotrack("OUCH |");
            }else {
                insertintotrack("     |");
            }
    

    New Function:

    public static void insertintotrack(String in)
    {
        char[] info = in.toCharArray();
    
        for (int i = 0; i < info.length; i++) {
            track[i] = info[i];
        }
    }