Guest User

Untitled

a guest
Jan 21st, 2018
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import java.util.*;
  2. public class MasterMind {
  3.  
  4.     int[] masterCode = new int[5];
  5.     int[] codeGuess = new int[5];
  6.     int masterCodeLen;
  7.     int guess;
  8.     boolean hasWon = false;
  9.    
  10.     public MasterMind(){
  11.         masterCode = new int[5];
  12.         for(int i = 0; i<4; i++)
  13.             masterCode[i] = (int)(Math.random()*4)+1;
  14.         masterCodeLen = 4;
  15.         guess = 0;
  16.         hasWon = false;
  17.         playGame();
  18.     }
  19.    
  20.     public MasterMind(String level){
  21.         masterCode = new int[5];
  22.         if(level == "intermediate")
  23.             masterCodeLen = 4;
  24.         else{
  25.             masterCodeLen = 5;
  26.         }
  27.         for(int i = 0; i<masterCodeLen; i++)
  28.             masterCode[i] = (int)(Math.random()*7)+1;
  29.         guess = 0;
  30.         hasWon = false;
  31.         playGame();
  32.     }
  33.    
  34.     public int rightSpot(){
  35.         int sum = 0;
  36.         for(int i = 0; i < masterCodeLen; i++){
  37.             if(codeGuess[i] == masterCode[i])
  38.                 sum+=1;
  39.         }
  40.         return sum;
  41.     }
  42.    
  43.     public int wrongSpot(){
  44.         int sum = 0;
  45.         for(int i = 0; i < masterCodeLen; i++){
  46.             if(codeGuess[i] != masterCode[i])
  47.                 sum+=1;
  48.         }
  49.         return sum;
  50.     }
  51.    
  52.     public void playerGuess(){
  53.         Scanner kbInput = new Scanner(System.in);
  54.         System.out.println("Enter a new guess.");
  55.         for(int i = 0; i < masterCodeLen; i++)
  56.             codeGuess[i] = kbInput.nextInt();
  57.         guess++;
  58.     }
  59.    
  60.     public boolean guessChecker(){
  61.         while(guess < 8)
  62.             return true;
  63.         return false;
  64.     }
  65.    
  66.     public boolean hasWon(){
  67.         int sum = 0;
  68.         for(int i = 0; i < masterCodeLen; i++){
  69.             if(codeGuess[i] == masterCode[i])
  70.                 sum+=1;
  71.         }
  72.         if(sum == masterCodeLen)
  73.             return true;
  74.         return false;
  75.     }
  76.    
  77.     public String toString(){
  78.         if(hasWon() == false)
  79.             return "Sorry, you have lost. The computer's code was "+masterCode+".";
  80.         return "You've won! It took you "+guess+" guesses.";           
  81.     }
  82.    
  83.     public void playGame(){
  84.         while(guessChecker() == true){
  85.             playerGuess();
  86.             hasWon();  
  87.         }
  88.     }
  89. }
Add Comment
Please, Sign In to add comment