Java programming implementation of the whac a mole word game instance code

  • 2020-11-30 08:18:47
  • OfStack

The console enters a number, matches the random number, and returns "Hit!"

A wrong match returns "What a pity! Missed it!"


package hitmouse;
 
import java.util.Random; 
import java.util.Scanner;
 
public class HitMouse {
 
public static void main(String[] args) {
  // TODO Auto-generated method stub
 
  int[] map = new int[5];  // define 1 An array 
  Random rand = new Random(); // Random number variable instantiation 
  Scanner scan = new Scanner(System.in); // Get console input 
  int pos;  //地鼠位置
  int newpos; // User input position, and gopher position judgment 
 
  while(true){
    for(int i=0;i<map.length;i++){
      map[i]=0; // All values are assigned to 0
    }
    pos = rand.nextInt(5); //5 Random number within 
    map[pos]=1; // Gopher location ( 1 Represents the location of the gopher) 
    for(int temp:map){
      System.out.print(temp); // The output array 
    }
    System.out.println(" Please enter the strike location: ");
    newpos = scan.nextInt();  // Assign to the number entered by the console newpos
    if(pos == newpos){     // Determine if the location is correct 
      System.out.println(" Hit! ");
    }
    else{
      System.out.println(" So sorry! Missed it! ");
    }
  }
}

Output effect:


00001 Please enter the strike location:  
4
 Hit!  
00100 Please enter the strike location:  
2
 Hit!  
10000 Please enter the strike location:  
0
 Hit!  
10000 Please enter the strike location:  
3
 So sorry! Missed it!  
01000 Please enter the strike location:  
1
 Hit!  
10000 Please enter the strike location: 

Self-run results:


00010 Please enter the strike location: 
9
 So sorry! Missed it! 
00100 Please enter the strike location: 
1
 So sorry! Missed it! 
00001 Please enter the strike location: 
5
 So sorry! Missed it! 
10000 Please enter the strike location: 
6
 So sorry! Missed it! 
01000 Please enter the strike location: 
4
 So sorry! Missed it! 
00010 Please enter the strike location: 
5
 So sorry! Missed it! 
10000 Please enter the strike location: 
88
 So sorry! Missed it! 
00010 Please enter the strike location: 
4
 So sorry! Missed it! 
10000 Please enter the strike location: 
5
 So sorry! Missed it! 
10000 Please enter the strike location: 
6
 So sorry! Missed it! 
00010 Please enter the strike location: 
3
 Hit! 
01000 Please enter the strike location: 

Bad luck. It took so many shots to hit.

conclusion

That's the end of this article on the Java programming implementation of the Whac-a-mole word game example code, I hope to help you. Interested friends can continue to refer to other related topics in this site, if there is any deficiency, welcome to comment out.


Related articles: