1
\$\begingroup\$

I am a freshman in university. This Pac-Man-ish Game is my final Computer science homework. I know my code is not perfect and has so many to be improved. However, Compared to corrections of this game, I really appreciate to be given the hints or general principles that my code lack, which I could use in the future.

Here is what my professor wants:

  1. Create a Maze.
  2. Add prizes to each square.
  3. Create a creature that the user can move through the maze with the arrows keys, consuming the prizes as it goes.
  4. Create evil things that move through the maze and that the user must avoid.
  5. At the beginning of each game, ask the user for its name
  6. Keep track of the time the user takes to consume all of the prizes. The time will be the user’s score.
  7. Keep a high scores list that displays at the end of each game. Just like with Asteroids, include a button to play again.
  8. Write the high scores list to a file and read the high scores list from the file before it is displayed. That way the high scores will be maintained when the application terminates.
  9. Sort the high scores list before it is displayed using one of the sorting methods we discussed in class.

Square class:

import processing.core.PApplet;

public class Square {
    float xPos;
    float yPos;
    float widthOfSquare = 24;
    float heightOfSquare = 24;
    boolean blocked;
    boolean reached = false;
    boolean hasPrize = false;


    Square pred;


    int row = 0;
    int col = 0;

    Square(int xPos, int yPos, boolean blocked, int row, int col){
        this.xPos=xPos;
        this.yPos=yPos;
        this.blocked=blocked;
        this.row=row;
        this.col=col;
    }//end constructor

    void display(PApplet proc){

        if(blocked){
            proc.fill(0,0,255);
        }else {
            proc.fill(255,255,255);
        }




        proc.rect(xPos,yPos,widthOfSquare,heightOfSquare);

        if(hasPrize){
            proc.fill(0,255,0);
            proc.rect(xPos+widthOfSquare/3,yPos+heightOfSquare/3,8,8);
        }// end if







    }//end display;

    boolean setBlocked(boolean x){
        return blocked = x;
    }//end of setBlocked

    public boolean isBlocked(){
        return blocked;
    }//end isBlocked

    public void setReached(Boolean reached){
        this.reached = reached;
    }//end setReached

    public boolean isReached(){
        return reached;
    }//end isRe

    public int getCol(){
        return col;
    }//end getCol

    public int getRow(){
        return row;
    }//end getRow

    boolean hasPrize(boolean Prize){
        return hasPrize = Prize;
    }//end has Prize

    public Square getPred(){
        return pred;
    }//end getPred

    public void setPred(Square pred){
        this.pred = pred;
    }//end setPred

    public float getXPos(){
        return xPos;
    }//end getX

    public float getYPos(){
        return yPos;
    }//end getY





}//end Square class

Maze class:

import java.util.ArrayList;

import processing.core.PApplet;

public class Maze {

    Square[][] rect;
    ArrayList<Square> prizes = new ArrayList<Square>();


      int widthOfSquare = 24;
      int heightOfSquare = 24;
      int numCol;
      int numRow;
      double chanceOfBlocked;

      int currentCol = 0;
      int currentRow = 0;


      int evilsRow;
      int evilsCol;

      int evilsRow1;
      int evilsCol1;

      boolean gameEnd;
      boolean gameWin;




      public static final int LEFT = 1;
      public static final int RIGHT = 2;
      public static final int UP = 3;
      public static final int DOWN = 4;

      Maze(int numRow, int numCol, double chanceOfBlocked){
         this.numRow = numRow;
         this.numCol = numCol;
         this.chanceOfBlocked =chanceOfBlocked;

         setInit();




      }//end constructor

      void setInit(){
          widthOfSquare = 24;
          heightOfSquare = 24;
          numCol=30;
          numRow=10;


          currentCol = 0;
          currentRow = 0;


          evilsRow=0;
          evilsCol=0;

          evilsRow1=0;
          evilsCol1=0;

          gameEnd = false;
          gameWin = false;

          do{
              rect = new Square[numRow][numCol];
              for(int row= 0; row < numRow;row++){
                  for(int col = 0; col < numCol; col++){
                      double x = Math.random();

                      rect[row][col] = new Square(col*widthOfSquare, 
                                                  row*heightOfSquare,
                                                  (x<chanceOfBlocked),row,col);
                  }//end for
              }//end for 

              rect[0][0].setBlocked(false);
              rect[numRow -1][numCol-1].setBlocked(false);
              markReachable();


           }while( ! rect[numRow-1][numCol-1].isReached());

         for(int row= 0; row < numRow;row++){
             for(int col = 0; col < numCol; col++){
                 if(!rect[row][col].isReached()){
                     rect[row][col].setBlocked(true);
                 }//end if
             }//end for 
         }//end for

         for(int row= 0; row < numRow;row++){
             for(int col = 0; col < numCol; col++){
                 if(rect[row][col].isReached()){
                     rect[row][col].hasPrize(true);
                     prizes.add(rect[row][col]);
                     rect[0][0].hasPrize(false);
                 }//end if


             }//end for 
          }//end for

         do{ 
           evilsRow = (int)(Math.random() * numRow);
           evilsCol = (int)(Math.random() * numCol);
        }  while( !rect[evilsRow][evilsCol].isReached());

         do{ 
               evilsRow1 = (int)(Math.random() * numRow);
               evilsCol1 = (int)(Math.random() * numCol);
            }  while( !rect[evilsRow1][evilsCol1].isReached());
    }//end setInit


      void display(PApplet proc){
          for(int row= 0; row < numRow;row++){
              for(int col = 0; col < numCol; col++){

                  rect[row][col].display(proc); 

              }//end for 
          }//end for 
          proc.fill(255,0,0);
          proc.ellipse(currentCol*widthOfSquare+widthOfSquare/2,
                       currentRow*heightOfSquare+heightOfSquare/2,
                       10,10);




          proc.fill(0,0,0);
          proc.ellipse(evilsCol*widthOfSquare+widthOfSquare/2,
                  evilsRow*heightOfSquare+heightOfSquare/2,
                       10,10);

          proc.fill(0,0,0);
          proc.ellipse(evilsCol1*widthOfSquare+widthOfSquare/2,
                  evilsRow1*heightOfSquare+heightOfSquare/2,
                       10,10);
          drawPath(proc);


       }//end display

      void drawPath(PApplet proc){
          drawPath(proc, rect[numRow-1][numCol-1]);
      }//end drawPath

      void drawPath(PApplet proc, Square theEnd){
          Square thePred = theEnd.getPred();
          if(thePred !=null){
              proc.line(theEnd.getXPos()+widthOfSquare/2, theEnd.getYPos()+heightOfSquare/2,
                      thePred.getXPos()+widthOfSquare/2, thePred.getYPos()+heightOfSquare/2);
              drawPath(proc, thePred);
          }//end if


      }//end drawPath


      void move(int x){
          int newCol = currentCol;
          int newRow = currentRow;

          if(x == LEFT){
              newCol--;
          }else if(x == RIGHT){
              newCol++;
          }else if(x == UP){
              newRow--;
          }else if(x == DOWN){
              newRow++;
          }//end if


          if(newRow >= 0 && newRow < numRow && newCol >= 0 && newCol < numCol && !rect[newRow][newCol].isBlocked()){
              currentCol = newCol;
              currentRow = newRow;
          }//end if


          if(rect[currentRow][currentCol].hasPrize(true)){
                     rect[currentRow][currentCol].hasPrize(false);
                     prizes.remove(rect[currentRow][currentCol]);
                     prizes.remove(rect[0][0]);


          }//end if

          markReachable();
          moveEvil();


      }//end move

      void moveEvil(){
          if(rect[evilsRow][evilsCol].getPred() !=null){
              int newRow = rect[evilsRow][evilsCol].getPred().getRow();
              int newCol = rect[evilsRow][evilsCol].getPred().getCol();


               evilsRow = newRow;
               evilsCol = newCol;
          }//end if

          if(rect[evilsRow1][evilsCol1].getPred() !=null){
              int newRow = rect[evilsRow1][evilsCol1].getPred().getRow();
              int newCol = rect[evilsRow1][evilsCol1].getPred().getCol();


               evilsRow1 = newRow;
               evilsCol1 = newCol;
          }//end if
      }//end moveEvils

      void markReachable(){

          ArrayList<Square> openList = new ArrayList<Square>();
          for(int row=0;row<numRow;row++){
              for(int col = 0;col<numCol;col++){
                  rect[row][col].setReached(false);
                  rect[row][col].setPred(null);
              }//end for
          }//end for
          openList.add(rect[currentRow][currentCol]);
          rect[currentRow][currentCol].setReached(true);



          while(openList.size() > 0){


                  Square reachedRect = openList.remove(0);
                  int row  = reachedRect.getRow();
                  int col = reachedRect.getCol();



                  checkAndAddSquare(openList, row+1,col,reachedRect);
                  checkAndAddSquare(openList, row-1,col,reachedRect);
                  checkAndAddSquare(openList, row,col+1,reachedRect);
                  checkAndAddSquare(openList, row,col-1,reachedRect);
          }//end while
      }// end markReachable


      void checkAndAddSquare(ArrayList<Square> openList,int row,int col,Square currentSquare){
          if(row >= 0 && col >=0 && row < numRow && col < numCol 
                  &&! rect[row][col].isBlocked() && ! rect[row][col].isReached() ){
                  rect[row][col].setReached(true);
                  openList.add(rect[row][col]);
                  rect[row][col].setPred(currentSquare);
              }//end if
      }//end check




      void loseGame(){
          if(evilsRow == currentRow && evilsCol == currentCol
                   || evilsRow1 == currentRow && evilsCol1 == currentCol){
             gameEnd = true;
          }//end if
      }//end loseGame

      public boolean gameEnd(){
          return gameEnd;
      }//end if



      void winTheGame(){
          if(prizes.size()==0){     
               gameWin = true;
          }//end if          
      }//end winTheGame

      boolean gameWin(){
          return gameWin;
      }//end gameWin

      boolean setGameWin(boolean x){
        return gameWin= x;
      }//end of setBlocked







}//end Maze

Score class:

import processing.core.PApplet;

public class Score {
      String name;
      int score;


      Score(String n, int s){
          name = n;
          score = s;

      }//end constructor

      void display(PApplet proc){
          proc.text("name: score", 200,200);
      }//end display





      int getPoints(){
          return this.score;
      }//end getPoint

      public String toString(){
          return name+" "+score;
      }//end String


}//end class

MazeMain class:

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Scanner;

import processing.core.PApplet;

public class MazeMain extends PApplet{


    Maze theMaze;
    ArrayList<Character> name = new ArrayList<Character>();



    boolean doneEnteringName = false;
    boolean startAgain = false;
    boolean initGame = true;

    int start = frameCount;
    int elapsedTime = 0;
    double chanceOfBlocked = 0.25;

    PrintStream out;
    Score theScore;

    ArrayList<Score> scoreList = new ArrayList<Score>();


    public void settings(){
        size(1000,600);
    }//end settings

    public void setup(){
        theMaze = new Maze(10,30,chanceOfBlocked);
        theMaze.setInit();
        textSize(30);
        try{
            File inputFile = new File("score");
            Scanner scanFile =new Scanner(inputFile);

            while(scanFile.hasNextLine()){

                String line=scanFile.nextLine();
                Score theScore =readScore(line);



                scoreList.add(theScore);
            }//end while

        } catch(FileNotFoundException e) {
            System.out.println("Bad file");
        }//end try-catch

    }//end setup

    public void draw(){
        background(127);
        if( theMaze.gameEnd()==false && theMaze.gameWin() == false){
            if(initGame){

                if(doneEnteringName){

                     theScore = new Score(getNameString(),0);               
                     theMaze = new Maze(10,30, chanceOfBlocked);
                     initGame =false;

                }else {

                    text("Maze Game!", 300,100);
                    text("enter your name   "+getNameString(), 250,300);

                }//end if

            }else {

                theMaze.display(this);
                text("Second =" +(int)((frameCount-start)/frameRate), 250,500);

                theMaze.winTheGame();
                theMaze.loseGame();

            }//end if

        }else if(theMaze.gameEnd){

             elapsedTime =(int)((frameCount-start)/frameRate);
             start = frameCount;
             fill(255,0,0);
             text("You Lose!", 360,125);
             fill(255,255,255);
             rect(350,350,200,60);
             fill(255,255,0);
             text("Start again?", 365,390);

             int heightOfScore = 100;
             for(Score Scores: scoreList){
                 text(Scores.toString(),100,heightOfScore);
                 heightOfScore += 50;
                }//end for

        }else if(theMaze.gameWin()){
            elapsedTime =(int)((frameCount-start)/frameRate);
            start = frameCount;
            fill(255,0,0);


            text("You Win! ", 360 ,125);
            fill(255,255,255);
            rect(350,350,200,60);
            fill(255,255,0);
            text("Start again?", 365,390);


            if(elapsedTime > 0){
                Score theScore = new Score(getNameString(),elapsedTime);
                this.scoreList.add(theScore);
            }//end if
             sort(scoreList,0);
             try{
                    PrintStream out = new PrintStream("score");
                    for(Score theScore: this.scoreList){
                        out.println(theScore);
                    }//end for
                    out.close();

                }catch(FileNotFoundException e){
                    e.printStackTrace();
                }//end try

            int heightOfScore = 100;
            for(Score Scores: scoreList){
                text(Scores.toString(),100,heightOfScore);
                heightOfScore += 50;
            }//end for
        }//end if

    }//end draw

    String getNameString(){
        String result = "";
        for(Character letter: name){
            result = result + letter;
        }//end for

        return result;
    }//end getNameString

    Score readScore(String line){
        Scanner scanLine = new Scanner(line);
        String name = scanLine.next();

        int points = scanLine.nextInt();
        Score result = new Score(name,points);
        return result;
    }//end readScore()


    public void keyPressed(){
        if(key == CODED){
            if(keyCode == LEFT){
                theMaze.move(Maze.LEFT);
            }else if(keyCode == RIGHT){
                theMaze.move(Maze.RIGHT);
            }else if(keyCode == UP){
                theMaze.move(Maze.UP);
            }else if(keyCode == DOWN){
                theMaze.move(Maze.DOWN);
            }//end if
        }//end if

        if(!doneEnteringName){
            if(key !=CODED){
                if(key == ENTER){
                    doneEnteringName = true;
                }else if( key == BACKSPACE){
                    name.remove(name.size()-1);
                }else {
                    name.add(key);
                }//end if
            }//end if
        }//end if
     }//end keyPressed



    public void mousePressed(){
        if(mouseX>300 && mouseX<500 && mouseY>350 && mouseY<410){
            initGame = true;
            theMaze.gameEnd = false;
            theMaze.gameWin = false;
            doneEnteringName = false;
            start = frameCount;
        }//end if
    }//end mousePressed

    public static int findSmallestScore(ArrayList<Score> scoreList, int startIndex ){
        Score minSoFar = scoreList.get(startIndex);
        int minIndex = startIndex;

        for(int index=startIndex+1; index<scoreList.size();index++){
            if(minSoFar.getPoints() >scoreList.get(index).getPoints()){
                minSoFar = scoreList.get(index);
                minIndex = index;

            }//end if
        }//end for
        return minIndex;
    }//end sort

    public static void sort(ArrayList<Score> scoreList, int startIndex){
        if(startIndex < scoreList.size()){
            int minIndex = findSmallestScore(scoreList, startIndex);
            swap(scoreList, startIndex,minIndex);
            sort(scoreList,startIndex+1);
        }//end if
    }//end sort

    public static void swap(ArrayList<Score> scoreList, int first, int second){
        Score temp = scoreList.get(first);
        scoreList.set(first,scoreList.get(second));
        scoreList.set(second,temp);
    }//end swap


    public static void main(String[] agro){
        PApplet.main("MazeMain");
    }//end static
}//end MazeMain
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.