Demo entry 6714516

test

   

Submitted by Team_B Keyuan on Feb 14, 2018 at 05:21
Language: Java. Code size: 2.7 kB.

import java.util.Scanner;
class Turtle{
	private static int[][] directionValue = {{0,1},{1,0},{0,-1},{-1,0}};
	private int[] curPosition;
	private boolean penDown; //true -> Down, false -> up
	private int direction;
	private int[][] board;
    
	public Turtle(){
        int[] t = {0,0};
		curPosition = t;
        penDown = false;
		direction = 0;
        board = new int[20][20];
	}
	public  void setPen(int x){
		switch(x){
			case 1: penDown = false; break;
			case 2: penDown = true; break;
		}
		if(penDown){
			board[curPosition[0]][curPosition[1]]=1;
		}
	}
	public  void setDirection(int x){
		switch(x){
			case 3:  direction = (direction + 1)%4; break;
			case 4: {
				direction = (direction +3)%4; 
				break;
			}
		}
	}
    public void move(int x){
		if(this.checkInput(x)){
			if(penDown){
				for(; x>0; x--){
					curPosition[0] += directionValue[direction][0];
					curPosition[1] += directionValue[direction][1];
					board[curPosition[0]][curPosition[1]]=1;
				}
			}
			else{
				curPosition[0] += directionValue[direction][0]*x;
				curPosition[1] += directionValue[direction][1]*x;
			}
		}
	}
	public void display(){
		for(int i =0; i< board.length; i++){
			for(int j=0; j<board[0].length; j++){
				System.out.print( board[i][j] + " " );
			}
			System.out.println();
		}
	}
	private boolean checkInput(int x){
		int a = curPosition[0] + directionValue[direction][0]*x;
		int b = curPosition[1] + directionValue[direction][1]*x;
		if( a<0 || a>=board.length || b<0 || b>=board[0].length ) {
			System.out.println("Invalid command: The turtle would be out of the board, please input again.");
			return false;
		}
		else return true;
	}
	public static void main( String[] args ){
		Scanner cin = new Scanner(System.in);
		boolean goAHead = true;
		Turtle ninjia = new Turtle();

        while(goAHead){
			int[] command = ninjia.input(cin.next());
			switch(command[0]){
				case 1:;
				case 2: ninjia.setPen(command[0]); break;
				case 3:;
				case 4:  ninjia.setDirection(command[0]); break;
				case 5: ninjia.move(command[1]); break;
				case 6: ninjia.display(); break;
				case 9: goAHead = false; break;
				default: {
						System.out.println( "Invalid command, please input again." );
					}
			}
		}
	}
	public int[] input(String x){
		int[] res = new int[2];
		if(x.length()==1){
			res[0]=  x.charAt(0)-'0';
		}
		else{
			int j=0;
			for( int i=0; i<x.length(); i++ ){
				if(x.charAt(i)==',') j=1;
				else{
					res[j]= res[j]*10 + (x.charAt(i)-'0');
                    }
                }
            }
        return res;
    }
}

This snippet took 0.01 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).