Remove all Occurrence

This is number 2 from handout #4 : string processing.

/*
* RemoveAllOccurences
*/

import acm.program.*;

public class RemoveAllOccurences extends ConsoleProgram{
	public void run(){	
		while(true){													// infinite loop
			String str1 = readLine("Give me a string(q to exit): ");	// q as a sentinel to break out of the loop
			if(str1.equals("q"))				
				break;
			String str2 = readLine("Give me a character to remove: ");	// give me the char
			
			int charIndex = 0;											// get the first char only
			char ch = str2.charAt(charIndex);							// 
			
			println(removeAllOccurrence(str1,ch));						// call removeAllOccurence
		}
	}
	
	// remove all occurrence of a char in a string
	private String removeAllOccurrence(String str, char ch){
		String result = ""; 								// declare a new String object result
		int firstIndex = 0;									// beginning of the string
		int indexChar =str.indexOf(ch);						// find the index of the first occurrence
		while(indexChar!=-1){ 								//loop through the string str until we find all occurrence
			result+=str.substring(firstIndex,indexChar);	//iterate 
			firstIndex = indexChar+1;						// skip the char
			indexChar = str.indexOf(ch, firstIndex);		// get the next index of the next substring
		}
		return result+str.substring(firstIndex);			//add the end of the result string and return it
	}
}

BreakOut somewhat finish

This is a ridiculous game that I was able to build just by following Stanford’s CS106a. This is almost a complete game. The main part is done .It just needs a little polishing. I am moving on to the next assignment for now.


/*
 * File: Breakout.java
 * -------------------
 * Name:
 * Section Leader:
 * 
 * This file will eventually implement the game of Breakout.
 */

import acm.graphics.*;
import acm.program.*;
import acm.util.*;

import java.applet.*;
import java.awt.*;
import java.awt.event.*;

public class Breakout extends GraphicsProgram {

/** Width and height of application window in pixels */
	public static final int APPLICATION_WIDTH = 400;
	public static final int APPLICATION_HEIGHT = 600;

/** Dimensions of game board (usually the same) */
	private static final int WIDTH = APPLICATION_WIDTH;
	private static final int HEIGHT = APPLICATION_HEIGHT;

/** Dimensions of the paddle */
	private static final int PADDLE_WIDTH = 60;
	private static final int PADDLE_HEIGHT = 10;

/** Offset of the paddle up from the bottom */
	private static final int PADDLE_Y_OFFSET = 30;

/** Number of bricks per row */
	private static final int NBRICKS_PER_ROW = 10;

/** Number of rows of bricks */
	private static final int NBRICK_ROWS = 10;

/** Separation between bricks */
	private static final int BRICK_SEP = 4;

/** Width of a brick */
	private static final int BRICK_WIDTH =
	  (WIDTH - (NBRICKS_PER_ROW - 1) * BRICK_SEP) / NBRICKS_PER_ROW;

/** Height of a brick */
	private static final int BRICK_HEIGHT = 8;

/** Radius of the ball in pixels */
	private static final int BALL_RADIUS = 10;

/** Offset of the top brick row from the top */
	private static final int BRICK_Y_OFFSET = 70;

/** Number of turns */
	private static final int NTURNS = 3;
	
/** copied from BouncingBall.java **/
	private static final double INITIAL_SPEED = 3.0;
	
	/** pause time */
	private static final double PAUSE_TIME = 1000 /24;
	
	/** middle space  height*/
	private static final double MID_SPACE = (HEIGHT +BRICK_Y_OFFSET + (NBRICK_ROWS*BRICK_HEIGHT))/2;
	//private static final int NBRICKS_ROWS = 0;

/* Method: run() */
/** Runs the Breakout program. */
	public void run() {
		
		brick_count = NBRICKS_PER_ROW*NBRICK_ROWS; // number of bricks
		setup(); //setup the game method call
	
		int turns =NTURNS; // how many lives we have
		while(turns>0){
			moveBall();
			//gameover();
			if(ballHitsBottom(ball) || brick_count ==0){
				gameover();
				break;
			}
			if(turns != NTURNS){
				setup();
			}
			turns--;	
		}
		gameover();
	}
	
	// setup methods
	private void setup(){
		setup_bricks(); // setup the bricks
		setup_paddle(); // paddle setup
		setup_ball(); // ball setup
	}

	// gameover if the ball hits bottom or there is no more bricks
	private void gameover(){
		//return (ballHitsBottom() || noMoreBricks());
		GLabel gameover = new GLabel("GAME OVER");
		gameover.setColor(Color.RED);
		add(gameover,(WIDTH-gameover.getWidth())/2,(MID_SPACE - gameover.getAscent())/2);
		//return gameover;
	}
	
	private boolean ballHitsBottom(GOval ball){
		return ball.getY() >= HEIGHT - ball.getHeight() ;
	}
	
	// create a brick
	private void createbrick(Color color,double x, double y){
		brick = new GRect(BRICK_WIDTH,BRICK_HEIGHT); // brick is a new GRect object
		brick.setFilled(true); // it is filled
		brick.setColor(Color.WHITE); // the color is white
		brick.setFillColor(color); // set the fill color with color parameter
		add(brick,x,y); // add the brick to the x , y parameter location
	}
	// setup the bricks
	
	private void setup_bricks(){
		int init_x = 0; // initial x , the left margin of the window
		
		for (int i = 1; i <= NBRICKS_PER_ROW;i++) {  // loop through the bricks per row
			for (int j = 0;j < NBRICK_ROWS;j++){      // loop through the no. of rows
				// compute the x position which starts at 0 then add a brick then a brick separator
				int x = init_x+(j * BRICK_WIDTH)+ (j*BRICK_SEP); 
				
				//compute the y by adding offset and a brick plus separator
				int y = BRICK_Y_OFFSET+(i * BRICK_HEIGHT)+(i*BRICK_SEP);
				
				// colorize base on the row index i
				if (i==1 || i==2){
					createbrick(Color.RED,x,y);
				} else if (i==3 || i==4){
					createbrick(Color.ORANGE,x,y);
				} else if (i==5 || i==6){
					createbrick(Color.YELLOW,x,y);
				} else if (i==7 || i==8){
					createbrick(Color.GREEN,x,y);
				} else if (i==9 || i==10){
					createbrick(Color.CYAN,x,y);
				}
			}
		}
	}
		
	// setup the paddle
	private void setup_paddle(){
		// put paddle in the middle
		paddle = new GRect(getWidth()/2-PADDLE_WIDTH/2,getHeight()-PADDLE_Y_OFFSET,PADDLE_WIDTH,PADDLE_HEIGHT); 
		paddle.setFilled(true);
		paddle.setFillColor(Color.BLUE);
		paddle.setColor(Color.BLUE);
		add(paddle);
		addMouseListeners(); //adds mouse listeners
	}
	
	//track the paddle
	public void mouseMoved(MouseEvent e){
		paddle.setLocation(e.getX(), getHeight()-PADDLE_Y_OFFSET);
		if ((e.getX()+PADDLE_WIDTH)>getWidth()){
			paddle.setLocation(getWidth()-PADDLE_WIDTH, getHeight()-PADDLE_Y_OFFSET);

		}
	}
	
	// setup the ball in the middle of the screen
	private void setup_ball(){
		double startX = (WIDTH - BALL_RADIUS)/2;
		double startY = (HEIGHT +BRICK_Y_OFFSET +(BRICK_HEIGHT*NBRICK_ROWS))/2;
		ball = new GOval(BALL_RADIUS, BALL_RADIUS);
		ball.setFilled(true);
		ball.setFillColor(Color.BLACK);
		add(ball,startX,startY);
	}
	
	/*
	 * move the ball
	 */
	private void moveBall(){
		double low_vel = 1.0; // low velocity of the ball
		double high_vel = 3.0; // high velocity of the ball
		double chance = 0.5; // randomize the chance by half
		vx = rgen.nextDouble(low_vel, high_vel); // random x velocity
		if (rgen.nextBoolean(chance)){  // half the chance of ball going left or right
			vx = -vx;  // change to the opposite direction
		}
		vy = INITIAL_SPEED;  //set the initial speed
		
		waitForClick();  //wait for a click to start the game
		//while(isBallOnScreen(ball)){ //keep moving till ball disappears
		while(!ballHitsBottom(ball) || brick_count!=0){
			ball.move(vx, vy); // move by setting vx,vy 
			checkForCollisions(); //check if ball hits something
			pause(PAUSE_TIME);   //pause animation
		}
	}
	
	/**
	 * isBallOnScreen 
	 *  check for the ball location
	 * @param ball
	 * @return
	 */
	private boolean isBallOnScreen(GOval ball){
		return ball.getX() <= WIDTH-(BALL_RADIUS*2) || ball.getX() >= 0 || ball.getY() <=HEIGHT || ball.getY() >=0;
	}
	
	private void checkForCollisions(){
		collider = getCollidingObject(); //get the colliding object
		if(collider != null){
	        bounceClip.play();
			if (collider == paddle){ // if its a paddle go the opposite direction
				/*if(collider.){
					vy = -vy;
					vx = -vx;
				} else {*/
					vy = -vy;
				//}
			
			} else { // if its a brick go the opposite ,remove the brick and subtract brick count
				vy = -vy; // bounce 
				remove(collider);
				brick_count--;
			}	
		}
		
		// top 
		if (ball.getY() <= 0){
			vy = -vy;
		}
			
		// if ball hits right side
		if (ball.getX() >= WIDTH-(BALL_RADIUS) ){
			vx = -vx;
		}
		// if ball hits top 
		
		// if ball hits left side
		if (ball.getX() <= 0 ){
			vx = -vx;
		}
	}

	/**
	 * getcollidingobject
	 *  gets the colliding object by testing all four bounding corners of the ball which is just a GRect
	 * @return
	 */
	private GObject getCollidingObject(){
 		if (getElementAt(ball.getX(), ball.getY()) != null){
 			return (getElementAt(ball.getX(), ball.getY()));
 		}
 		
		if (getElementAt(ball.getX()+2*(BALL_RADIUS), ball.getY()) != null){
			return (getElementAt(ball.getX()+2*(BALL_RADIUS), ball.getY()));
		}
		
		if (getElementAt(ball.getX(),ball.getY()+2*(BALL_RADIUS)) !=null ){
		 return (getElementAt(ball.getX(),ball.getY()+2*(BALL_RADIUS)));
		}
		
		if (getElementAt(ball.getX()+2*(BALL_RADIUS),ball.getY()+2*(BALL_RADIUS)) != null){
		return (getElementAt(ball.getX()+2*(BALL_RADIUS),ball.getY()+2*(BALL_RADIUS)));
		}
		
		return null;	
			
		
		
	}
	/* Private instance variables */
	private int brick_count; // count the number of bricks
	private GRect brick; // the brick object
	private GObject collider; // the object the ball collided
	private GRect paddle; // the paddle
	private GOval ball; // the ball
	private double vx, vy; // the velocity in x and y
	private RandomGenerator rgen = RandomGenerator.getInstance(); // random generator
	AudioClip bounceClip = MediaTools.loadAudioClip("bounce.au");

}

Drawline.java solution

Mouse events with java.

/*
 * DrawLines.java
 * 		draw lines in canvas
 * ralph @today
 *
 */

import acm.graphics.*;
import acm.program.*;
import java.awt.event.*;

public class Drawlines extends GraphicsProgram {

	public void run(){
		/* Tell Java that we're ready for the mouse */
		addMouseListeners();
	}
	
	public void mousePressed(MouseEvent e){
		// start the line with a mousepressed event
		line = new GLine(e.getX(),e.getY(),e.getX(),e.getY());
		add(line);
	}
	
	public void mouseDragged(MouseEvent e){
		/* end the line where we click */
		line.setEndPoint(e.getX(), e.getY());
	}
	
	/* private instance variables */
	private GLine line;
}

Circles

I am so proud of myself that I figured it out how to fit the circles on the window. I was stuck for a while but I finally figured it out today.

/** 
 * Circle.java - Make random circles
 * @author rafiks
 */

import java.awt.Color;

import acm.graphics.*;
import acm.program.*;
import acm.util.*;

public class Circle extends GraphicsProgram {
	// Constants
	// number of circles
	private static final int NUM_CIRCLES=15;
	
	//minimum radius
	private static final int MIN_RAD=20;
	
	//max radius
	private static final int MAX_RAD=200;
	
	//seed for troubleshooting
	//private static final int SEED=1;
	
	public void run(){
		
		//rgen.setSeed(SEED);
				
		//for loop to generate the circles base on NUM_CIRCLES
		for(int i=0;i<NUM_CIRCLES;i++){
			//random radius set wit MIN_RAD and MAX_RAD
			int radius = rgen.nextInt(MIN_RAD, MAX_RAD);
			// set x so that it fits the window
			int x = rgen.nextInt(radius,getWidth()-radius);
			// set y so that it fits the window
			int y = rgen.nextInt(radius,getHeight()-radius);
			// set a random color
			Color c = rgen.nextColor();
			//draw the circle
			drawCircle(x,y,radius,c);
		}		
	}
	
	/* Method to Draw a circle base on the parameters */	
	private void drawCircle(int x,int y,int radius,Color c){
		GOval circle = new GOval(x,y,radius,radius);
		circle.setFilled(true);
		circle.setColor(c);
		circle.setFillColor(c);
		add(circle);		
	}
	
/** private instance variable */
	private RandomGenerator rgen = RandomGenerator.getInstance();
}

RobotFace with Methods

/*
 * File: RobotFace.java
 * ---------------------
 * This class is a blank one that you can change at will. Remember, if you change
 * the class name, you'll need to change the filename so that it matches.
 * Then you can extend GraphicsProgram, ConsoleProgram, or DialogProgram as you like.
 */

import acm.program.*;
import acm.graphics.*;
import java.awt.*;

public class RobotFace extends GraphicsProgram {
	private static final int HEAD_WIDTH=265;
	private static final int HEAD_HEIGHT=400;
	private static final int EYE_RADIUS=50;
	private static final int MOUTH_WIDTH=200;
	private static final int MOUTH_HEIGHT=50;
	
	public void run() {
		int middle_x = getWidth()/2;
		int middle_y = getHeight()/2;
		int leftEye_x = middle_x-HEAD_WIDTH/4-EYE_RADIUS/2;
		int rightEye_x = middle_x+HEAD_WIDTH/4-EYE_RADIUS/2;
		
		add(Head(middle_x,middle_y));
		addEyes(leftEye_x,rightEye_x,middle_y);
		add(Mouth(middle_x,middle_y));
		
		}
	
	
	//Head method
	private GRect Head(int x,int y){
		//Head
		GRect myHead = new GRect(x-HEAD_WIDTH/2,y-HEAD_HEIGHT/2,HEAD_WIDTH, HEAD_HEIGHT);
		myHead.setFilled(true);
		myHead.setFillColor(Color.GRAY);
		return myHead;
		
	}
	
	//Eyes method
	private void addEyes( int left_eye,int right_eye ,int y){
		//add left Eye
		add(Eye(left_eye,y));
		
		//add right eye
		add(Eye(right_eye,y));
		
	}
	
	//Mouth method
	private GRect Mouth(int x,int y){
		GRect mouth = new GRect(x-MOUTH_WIDTH/2,y+HEAD_HEIGHT/4,MOUTH_WIDTH,MOUTH_HEIGHT);
		mouth.setFilled(true);
		mouth.setFillColor(Color.WHITE);
		return mouth;
		
	}
	
	//individual Eye method
	private GOval Eye(int x,int y){
		//Eyes
		
		GOval myEye = new GOval(x, y-HEAD_HEIGHT/4, EYE_RADIUS, EYE_RADIUS);
		myEye.setFilled(true);
		myEye.setFillColor(Color.YELLOW);
		return myEye;
		
	}
	
}

Fibonacci.java – solution to HandOut#2

/*
 * File: Fibonacci.java
 * ---------------------
 * This class is a blank one that you can change at will. Remember, if you change
 * the class name, you'll need to change the filename so that it matches.
 * Then you can extend GraphicsProgram, ConsoleProgram, or DialogProgram as you like.
 */

import acm.program.*;

public class Fibonacci extends ConsoleProgram {
	//constant for the 
	private static final int MAX_TERM_VALUE=1000;

	public void run() {
		println("This Program lists the Fibonacci sequence.");
		//we need three variables 
		//fibonacci 0 = 0
		int term = 0;
		
		//fibonacci(1) = 1
		int term2 = 1;
		
		//third variable to store the sum
		int term3 =0;
		
		//print the fibonacci(0) and (1)
		println(term);
		println(term2);
		
		// loop until we finish the number in the MAX_TERM_VALUE
		while (term < MAX_TERM_VALUE){
			// term2(sum) = term plus term2
			term3=term+term2;
			
			//print the sum
			println(term3);
			
			//mv the next number to term
			term=term2;
			
			// and the sum to term2
			term2=term3;
		}
	}
}

Hailstone solution -Assignment 2

/*
 * File: Hailstone.java
 * Name: 
 * Section Leader: 
 * --------------------
 * This file is the starter file for the Hailstone problem.
 */

import acm.program.*;

public class Hailstone extends ConsoleProgram {
	public void run() {
		//index for the number of loops to do
		int index =0;
		
		//query for the number
		int number = readInt("Enter a number: ");
		
		//loop until the number ==1
		while(number!=1){
			//increment the loop
			index++;
			
			//if number is even take half
			if(number%2==0){
				println(number+" is even so I take half: "+(number/=2));
			} else {
				//else if odd make it 3n+1
				println(number+" is odd, so I make 3n +1: "+(number = (number*3)+1));
			}
		}
		//print the number of loops
		println("The process took "+index+" to reach 1.");
	}
}

My Pyramid solution for Assignment 2

/*
 * File: Pyramid.java
 * Name: 
 * Section Leader: 
 * ------------------
 * This file is the starter file for the Pyramid problem.
 * It includes definitions of the constants that match the
 * sample run in the assignment, but you should make sure
 * that changing these values causes the generated display
 * to change accordingly.
 */

import acm.graphics.*;
import acm.program.*;
import java.awt.*;

public class Pyramid extends GraphicsProgram {

/** Width of each brick in pixels */
	private static final int BRICK_WIDTH = 30;

/** Width of each brick in pixels */
	private static final int BRICK_HEIGHT = 12;

/** Number of bricks in the base of the pyramid */
	//private static final int BRICKS_IN_BASE = 14;
	private static final int BRICKS_IN_BASE = 20;


	public void run() {
		// get the middle of the window
		double middle = getWidth() /2 ;
		
		// the starting base_width
		double base_width = BRICKS_IN_BASE * BRICK_WIDTH;
		
		// where we put the first block of the row
		double start_base = middle - (base_width/2);
		
		//getting to the bottom layer
		double bottom = getHeight();
		
		// cannot change the constant, so we'll assign another variable for
		// the columns, add 1 to get to the top
		int blk_up = BRICKS_IN_BASE+1;
		
		// the non static brick_base variable
		int blck_side = BRICKS_IN_BASE;
		
		
		// the first loop is for the column 
		for(int i=1;i<blk_up;i++){
			
			// second loop is for the row
			for(int j=0;j<blck_side;j++){
				
				// y coordinate position for the bricks
				double y = bottom -(i * BRICK_HEIGHT);
				
				// x coordinate for the bricks
				double x = start_base + (j * BRICK_WIDTH);
				
				//draws the bricks
				GRect myrect = new GRect(x,y,BRICK_WIDTH,BRICK_HEIGHT);
				add(myrect);
			}
			// subtract 1 brick from the row
			blck_side -=1;
			
			// get a new base width
			base_width = blck_side *BRICK_WIDTH;
			
			//get the new position for the start of the new row
			start_base = middle - (base_width/2);
		}
		// subtract 1 from the column
                // I don't think this is necessary
		//blk_up-=1;	 
	}
}


Target solution updated

Added “setColor” to set the color of the borders. Thanks to my wife ,she notice that the borders need to be changed.

Screen Shot 2013-11-17 at 2.47.54 AM

target
target

Updated code

/*
 * File: Target.java
 * Name: 
 * Section Leader: 
 * -----------------
 * This file is the starter file for the Target problem.
 */

import acm.graphics.*;
import acm.program.*;
import java.awt.*;

public class Target extends GraphicsProgram {
	
	public void run() {
		
		int center_x = getWidth() /2;
		int center_y = getHeight() /2;
		int out_radius = 72;
		int mid_radius = (int) (out_radius * 0.65);
		int inn_radius = (int) (out_radius * 0.3);
		
		// outer circle
		GOval out = new GOval(center_x-(out_radius/2),center_y-(out_radius/2),out_radius,out_radius);
		out.setFilled(true);
		out.setColor(Color.RED);
		out.setFillColor(Color.RED);
		add(out);
		
		//middle circle
		GOval mid = new GOval(center_x-(mid_radius/2),center_y-(mid_radius/2),mid_radius,mid_radius);
		mid.setFilled(true);
		mid.setColor(Color.WHITE);
		mid.setFillColor(Color.WHITE);
		add(mid);
		
		//inner circle
		GOval inn = new GOval(center_x-(inn_radius/2),center_y-(inn_radius/2),inn_radius,inn_radius);
		inn.setFilled(true);
		inn.setColor(Color.RED);
		inn.setFillColor(Color.RED);
		add(inn);
		
		
		}

	
}

/*
 * File: Target.java
 * Name: 
 * Section Leader: 
 * -----------------
 * This file is the starter file for the Target problem.
 */

import acm.graphics.*;
import acm.program.*;
import java.awt.*;

public class Target extends GraphicsProgram {
	
	public void run() {
		
		int center_x = getWidth() /2;
		int center_y = getHeight() /2;
		int out_radius = 72;
		int mid_radius = (int) (out_radius * 0.65);
		int inn_radius = (int) (out_radius * 0.3);
		
		// outer circle
		GOval out = new GOval(center_x-(out_radius/2),center_y-(out_radius/2),out_radius,out_radius);
		out.setFilled(true);
		out.setFillColor(Color.RED);
		add(out);
		
		//middle circle
		// 
		GOval mid = new GOval(center_x-(mid_radius/2),center_y-(mid_radius/2),mid_radius,mid_radius);
		mid.setFilled(true);
		mid.setFillColor(Color.WHITE);
		add(mid);
		
		//inner circle
		GOval inn = new GOval(center_x-(inn_radius/2),center_y-(inn_radius/2),inn_radius,inn_radius);
		inn.setFilled(true);
		inn.setFillColor(Color.RED);
		add(inn);
		
		
		}

	
}

Karel the Robot Assignment 1 Problem 2

It looks like I got the assignment solved. It looks a bit like spaghetti code but it works on the default world.

/*
 * File: StoneMasonKarel.java
 * --------------------------
 * The StoneMasonKarel subclass as it appears here does nothing.
 * When you finish writing it, it should solve the "repair the quad"
 * problem from Assignment 1.  In addition to editing the program,
 * you should be sure to edit this comment so that it no longer
 * indicates that the program does nothing.
 */

import stanford.karel.*;

public class StoneMasonKarel extends SuperKarel {

	public void run(){
		//iterate 13 times(checking 13 columns)
		for(int i=0;i<13;i++){
			check();
			fixColumn();
			keepmoving();
		}
                //pseudocode
		//go up the column
		//check if there is a beeper
		//if there is one
		//go back to the start and
		//fill in the beeper
		//go check the next column
		//repeat
	}

// move to the wall
	private void movetowall(){
		while(frontIsClear()){
			move();
		}
	}

//keep karel moving through the next column
	private void keepmoving(){
		if(frontIsBlocked()){
			if(facingNorth()){
				backtostart();
			}
		}
			
		if(facingNorth()){
			turnRight();
			move();
			//turnRight();
		}
		if(facingSouth()){
			turnLeft();
			move();
			turnLeft();
		}
		if(facingWest()){
			turnAround();
			move();
		}
		
	}

//skip a beeper
	private void skipbeeper(){
		if(beepersPresent()){
			move();
		}
	}

//fix the broken column
	private void fixColumn(){
		backtostart();
		while(frontIsClear()){
			skipbeeper();
			while(noBeepersPresent()){
				
				if(frontIsClear()){
					while(noBeepersPresent()){
						putBeeper();
						move();
					}
				} else {
					if(noBeepersPresent()){
						putBeeper();
					}
					turnAround();
					movetowall();
				}		
			}
		}		
	}

	//move to the next column
	private void nextcolumn(){
		turnLeft();
		move();
		turnLeft();

	}
	
	//back to starting position
	private void backtostart(){
		turnAround();
		movetowall();
		turnAround();
	}
	
	//check if this a column that needs fixing
	private void check(){
		if(facingEast()){
			turnLeft();
		}
		while(noBeepersPresent()){
			if(frontIsClear()){
				move();
			} else {
				turnAround();
				movetowall();
				nextcolumn();
				backtostart();
			}
		}
	}

}