Question

Java language: C Write a game program that allows the user to collect 4 tokens hidden...

Java language: C

Write a game program that allows the user to collect 4 tokens hidden in an array (cells) of size 10. The program asks the user to select a cell. Determine if there is a token in that cell or not, and give the user appropriate feedback. This program should keep letting user to select until the all tokens are collected. The program should display the total number of selections. Use rand_position

Example input/output:

There are four tokens. Select from the following cells for the tokens: 0 1 2 3 4 5 6 7 8 9

Enter your selection: 2 Output: Sorry, there is no token in cell #2

Enter your selection: 5

Output: Congrats! You have collected a token from cell #5

Enter your selection: 7

Output: Sorry, there is no token in cell #2

Enter your selection: 3

Output: Congrats! You have collected a token from cell #3

Enter your selection: 9

Output: Congrats! You have collected a token from cell #9

Enter your selection: 1

Output: Sorry, there is no token in cell #1

Enter your selection: 0

Output: Congrats! You have collected a token from cell #0 All tokens are collected! You have made 6 selections.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

JAVA PROGRAM

package test;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
* TheGame class
*/
public class TheGame {
  
   public static void main(String[] args){
      
       TheGame tg = new TheGame(); //create an instance of TheGame class
      
       //this will create gameArray of size 10 with 4 hidden tokens in random indexes
       //hidden tokens will be identified with value 1
       int[] gameArray = tg.rand_position(10,4);
      
       //If the array needs to be printed the following line can be uncommemted
       //System.out.println(Arrays.toString(gameArray));
      
       int tokenCounter = 0 ; //to check number of hidden tokens collected
       int numberOfSelections = 0; // to check total selections made
       Scanner sc = new Scanner(System.in); // Scanner instance is created to read user selection
      
       System.out.println("There are four tokens. Select from the following cells for the tokens: 0 1 2 3 4 5 6 7 8 9");
      
       while(tokenCounter < 4){ //iterate as long as all tokens are not collected
           System.out.println("Enter your selection:");
           int indexSelected = sc.nextInt();
           if(indexSelected>=0 && indexSelected < 10){ //if this is a valid selection
               if(gameArray[indexSelected]==1){ //if this is a hidden token
                   tokenCounter++; // increase the counter by 1 as a token is collected
                   System.out.println("Congrats! You have collected a token from cell #"+indexSelected);
               }else{ //if this cell does not contain a token
                   System.out.println("Sorry, there is no token in cell #"+indexSelected);
               }
           }else{ //if the selection is improper
               System.out.println("This is not a valid selection!");
           }
          
           numberOfSelections++;//increase the number of selection attempt
       }
      
       //end of while loop - means all tokens are collected
       sc.close();//close scanner
       System.out.println("All tokens are collected! You have made "+numberOfSelections+" selections.");
      
   }
  
   /**
   * This method will create int array of arrSize , having numOfTokens number of hidden token in it
   * at random indexes
   * @param arrSize
   * @param numOfTokens
   * @return
   */
   private int[] rand_position(int arrSize, int numOfTokens){
       int[] arr = new int[arrSize]; //initialize array with arrSize
      
       List<Integer> s= new ArrayList<Integer>(); //this will hold random index location
       int currentRandom ;
      
       //create numOfTokens times of random index for hidden tokens
       for(int p = 1; p <= numOfTokens ; p++){
           //This do-while loop will generate random index
           //as long as the random index generated is there in list s
           do{
               currentRandom = (int)(Math.random()*arrSize);
           }while(s.contains(currentRandom));
          
           s.add(currentRandom);   //means currentIndex is a unique to the list s, hence add it
       }
      
       //populate the array
       for(int i = 0 ; i < arrSize; i++){
           if(s.contains(i)){
               arr[i] = 1;//mark all hidden token index location with value 1
           }else{
               arr[i] = 0;//all other are 0
           }
       }
      
       return arr;
   }

}

OUTPUT:

There are four tokens. Select from the following cells for the tokens: 0 1 2 3 4 5 6 7 8 9
Enter your selection:
0
Sorry, there is no token in cell #0
Enter your selection:
1
Congrats! You have collected a token from cell #1
Enter your selection:
2
Sorry, there is no token in cell #2
Enter your selection:
3
Sorry, there is no token in cell #3
Enter your selection:
4
Sorry, there is no token in cell #4
Enter your selection:
15
This is not a valid selection!
Enter your selection:
5
Congrats! You have collected a token from cell #5
Enter your selection:
6
Congrats! You have collected a token from cell #6
Enter your selection:
7
Congrats! You have collected a token from cell #7
All tokens are collected! You have made 9 selections.

EXPLANATION

All the required code comments and explanation are given within code.

Add a comment
Know the answer?
Add Answer to:
Java language: C Write a game program that allows the user to collect 4 tokens hidden...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • this assignment should be delivered in C language Program 4 will prompt the user for one...

    this assignment should be delivered in C language Program 4 will prompt the user for one or two token, space delimited, inputs of at most 20 characters. If the user provides more than 20 characters before a newline is reached print the provided error message. If the number of tokens is incorrect, print the appropriate error message. If the input is correct, print the appropriate token types. Prompt the user for input (and provide output) until the user provides a...

  • program should be in c language. thank you for helping me. 1 of 4 CSCI 281...

    program should be in c language. thank you for helping me. 1 of 4 CSCI 281 LAB 5 -STACKS AND A CALCULATOR ASSIGNMENT Using 2 stacks to implement a calculator CALCULATOR 1. User input of two types. Integer values and associated tokens(+ 2. As the user needs to enter the input in the following manner: +5/17-3 9+2 8+7 You should use a looping scanf to allow the user to enter digit, then a char, then a digit, then a car...

  • Java project In a game of tic-tac-toe, two players take turns marking an available cell in...

    Java project In a game of tic-tac-toe, two players take turns marking an available cell in a 3 x 3 grid with their respective tokens (either X or O). When one player has placed three tokens in a horizontal, vertical, or diagonal row on the grid, the game is over and that player has won. A draw (no winner) occurs when all the cells on the grid have been filled with tokens and neither player has achieved a win. Create...

  • 1. Write a Python program that will determine if the user can vote or not. The...

    1. Write a Python program that will determine if the user can vote or not. The program will ask the user to enter integer numbers that represent year, month, and day of birth. Also, the program will ask the user to enter the current year, current month, and current day. The program will determine if the user is allowed to vote or not. If the user age is greater than or equal 18 then the program will print the following...

  • JAVA, please You must write a robust program meaning that your program should not crash with...

    JAVA, please You must write a robust program meaning that your program should not crash with any given data. Data validation must be done any time that user enters an input. Write a program that 1. Gets an infix expression form the user and evaluate the expression using stack ADT a. Finds the postfix equivalent of the given infix expression b. Evaluate the created postfix expression. c. Note: your program should not crash when you enter an invalid expression such...

  • Write a program in the Codio programming environment that allows you to play the game of...

    Write a program in the Codio programming environment that allows you to play the game of Rock / Paper / Scissors against the computer. Within the Codio starting project you will find starter code as well as tests to run at each stage. There are three stages to the program, as illustrated below. You must pass the tests at each stage before continuing in to the next stage.  We may rerun all tests within Codio before grading your program. Please see...

  • For this program you'll write a program that uses a recursive function. This program plays a simp...

    C++ For this program you'll write a program that uses a recursive function. This program plays a simple token-taking game. The rules are simple 1. 2. You start the game with exactly 13 tokens. On each turn, you may do one of two things You may ask for exactly 25 more tokens; or IF the number of tokens you have is an even number, you may give back exactly half of the tokens you have a. b. 3. The object...

  • Please Do it In Java: Objectives: To Java programming language To understand the lexical analysis phase...

    Please Do it In Java: Objectives: To Java programming language To understand the lexical analysis phase of program compilation Assignment: The first phase of compilation is called scanning or lexical analysis. This phase interprets the input program as a sequence of characters and produces a sequence of tokens, which will be used by the parser. Write a Java, program that implements a simple scanner for a source file given as a command-line argument. The format of the tokens is described...

  • You will write a Java program that implements Conway’s Game of Life, a simple cellular automaton...

    You will write a Java program that implements Conway’s Game of Life, a simple cellular automaton discussed in class. See for example: http://www.bitstorm.org/gameoflife/ Our version has a 10 x 10 grid, numbered like this: 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 The grid is represented by a 10 x 10 2­dimensional integer array. If the grid point (i, j) is "populated", the array element [i][j] contains 1;...

  • Write a complete Java program in a file caled Module1Progrom.java that reads all the tokens from...

    Write a complete Java program in a file caled Module1Progrom.java that reads all the tokens from a file named dota.txt that is to be found in the same directory as the running program. The program should ignore al tokens that cannot be read as an integer and read only the ones that can. After reading all of the integers, the program should print all the integers back to the screen, one per line, from the smalest to the largest. For...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
Active Questions
ADVERTISEMENT