Question

In: Computer Science

--- TURN this Code into Java Language --- #include <iostream> #include <string> using namespace std; //...

--- TURN this Code into Java Language ---

#include <iostream>
#include <string>

using namespace std;

// constants
const int FINAL_POSITION = 43;
const int INITIAL_POSITION = -1;

const int NUM_PLAYERS = 2;
const string BLUE = "BLUE";
const string GREEN = "GREEN";
const string ORANGE = "ORANGE";
const string PURPLE = "PURPLE";
const string RED = "RED";
const string YELLOW = "YELLOW";
const string COLORS [] = {BLUE, GREEN, ORANGE, PURPLE, RED, YELLOW};
const int NUM_COLORS = 6;

// names of special characters marking specific spaces on the board
const string PLUMPY = "PLUMPY";
const string MR_MINT = "MR. MINT";
const string JOLLY = "JOLLY";

// A partial board for Candyland
// based on the picture at: http://www.lscheffer.com/CandyLand-big.jpg
string board[] = {RED, PURPLE, YELLOW, BLUE, ORANGE, GREEN, RED, PURPLE, PLUMPY, YELLOW,
                  BLUE, ORANGE, GREEN, RED, PURPLE, YELLOW, BLUE, MR_MINT, ORANGE, GREEN,
                  RED, PURPLE, YELLOW, BLUE, ORANGE, GREEN, RED, PURPLE, YELLOW, BLUE,
                  ORANGE, GREEN, RED, PURPLE, YELLOW, BLUE, ORANGE, GREEN, RED, PURPLE,
                  YELLOW, BLUE, JOLLY, ORANGE
                  
               };

int positions[NUM_PLAYERS];

// set all elements of the positions array to INITIAL_POSITION
// Parameters: positions -- will store where the players are
//             numPlayers -- how many there are
void initialize(int positions[], int numPlayers) {
    for (int player = 0; player < numPlayers; player++)
        positions[player] = INITIAL_POSITION;
}

// Description: Test if string is a valid color in the game
// Parameter: str -- string to test
// Returns: true if it is a color in the game, false if not
bool isColor(string str) {
     for (int color = 0; color < NUM_COLORS; color++) {
         if (str == COLORS[color])
             return true;
     }
     return false;
}

// Description: Starting after indicated position search forward on board to find the color
// Parameters: startPos -- index of current space of player -- start looking *after* this space
//             color -- find the next space with this color
// Returns: index of next space of chosen color
int findColor(int startPos, string color) {
    for (int pos = startPos+1; pos < FINAL_POSITION; pos++)
        if (board[pos] == color)
            return pos;
    return FINAL_POSITION;
}

// Description: find position of indicated person
// Parameters: name -- name of person to look for
// Returns: index of space for this name
int findPerson(string name) {
    if (name == PLUMPY) return 8;
    if (name == MR_MINT) return 17;
    if (name == JOLLY) return 42;
    cerr << "No such person in the game" << endl;
    return FINAL_POSITION; // should not get here -- just here to get program to stop
}

// Description: Move a player
// Parameters: player -- index of player to move
//             card -- indicates where to move
//             repeat -- true if card is a "double" color, false if not
//             positions -- where the players are
// Returns: new position of player after move
int move(int player, string card, bool repeat, int positions[]) {
    int nextPos = positions[player];
    
    if (isColor(card)) {
        nextPos = findColor(positions[player], card);
        if (repeat)
            nextPos = findColor(nextPos, card);
        return nextPos;
    }
    else return findPerson(card);
}

// Description: Check for a winner
// Parameters: positions -- where the players are
//             numPlayers -- how many there are
// Returns: true if there are no winners yet
//          false if anyone has won
bool nowinner(int positions[], int numPlayers) {
    for (int player = 0; player < NUM_PLAYERS; player++) {
        if (positions[player] == FINAL_POSITION) // reached the end
            return false;
        }
    return true;
}

// Description: Display welcome string
void printIntro() {
    cout << "This is a crude version of Candyland" << endl << endl;
}

// Generate the next value "drawn"
// Returns: the value of the next card drawn. Returning the empty string indicates
//          there are no more values
string draw() {
    string testRolls[] = {PLUMPY, YELLOW, RED, YELLOW, GREEN, MR_MINT, JOLLY, RED, GREEN};
    const int NUM_CARDS = 9;
    static int next = 0;
    
    if (next >= NUM_CARDS) return "";
    return testRolls[next++];
}

// Indicate if this card is a "double" color
// Returns: true if the color is a double, false if not.
// NOTE: This is a very bad way to do this -- but it does help to motivate structures
bool drawRepeat() {
    bool testRollsRepeat[] = {false, true, false, true, false, false, false, false, false};
    const int NUM_CARDS = 9;
    static int next = 0;
    
    if (next >= NUM_CARDS) return false;
    return testRollsRepeat[next++];
}

// Print the identity of the winner, if any.
// If there are no winners, do nothing.
// Parameters:
// positions -- the array indicating where the players are located
// numPlayers -- the number of players
void printWinner(int positions[], int numPlayers) {
    for (int player = 0; player < numPlayers; player++) {
        // Would be clearer to use a different constant to
        // explicitly define the winning position
        if (positions[player] == FINAL_POSITION)
            cout << "Player " << player << " wins!" << endl;
    }
}

// Description: Play the game
void playGame() {
    // Use nextPlayer to switch among the players
    int nextPlayer = 0;
    bool done = false;

    initialize(positions, NUM_PLAYERS);
    while (nowinner(positions, NUM_PLAYERS) && !done) {
        string nextCard = draw();
        bool repeat = drawRepeat();

        if ("" != nextCard) {
            positions[nextPlayer] = move(nextPlayer, nextCard, repeat, positions);
            cout << "Player " << nextPlayer << " is at position "
                 << positions[nextPlayer] << endl;
            nextPlayer = (nextPlayer + 1) % NUM_PLAYERS;
        }
        else done = true;
    }
    if (nowinner(positions, NUM_PLAYERS))
        cout << "No winner" << endl;
    else printWinner(positions, NUM_PLAYERS);
}

int main() {
        printIntro();
        playGame();
        return 0;
}

Solutions

Expert Solution

public class Game
{
final static int FINAL_POSITION = 43;
final static int INITIAL_POSITION = -1;

final static int NUM_PLAYERS = 2;
final static String BLUE = "BLUE";
final static String GREEN = "GREEN";
final static String ORANGE = "ORANGE";
final static String PURPLE = "PURPLE";
final static String RED = "RED";
final static String YELLOW = "YELLOW";
final static String COLORS [] = {BLUE, GREEN, ORANGE, PURPLE, RED, YELLOW};
final static int NUM_COLORS = 6;

// names of special characters marking specific spaces on the board
final static String PLUMPY = "PLUMPY";
final static String MR_MINT = "MR. MINT";
final static String JOLLY = "JOLLY";
static int next;

// A partial board for Candyland
// based on the picture at: http://www.lscheffer.com/CandyLand-big.jpg
static String board[] = {"RED", "PURPLE", "YELLOW", "BLUE", "ORANGE", "GREEN", "RED", "PURPLE", "PLUMPY", "YELLOW",
"BLUE", "ORANGE", "GREEN", "RED", "PURPLE", "YELLOW", "BLUE", "MR_MINT", "ORANGE", "GREEN",
"RED", "PURPLE", "YELLOW", "BLUE", "ORANGE", "GREEN", "RED", "PURPLE", "YELLOW", "BLUE",
"ORANGE", "GREEN", "RED", "PURPLE", "YELLOW", "BLUE", "ORANGE", "GREEN", "RED", "PURPLE",
"YELLOW", "BLUE", "JOLLY", "ORANGE"

};

static int positions[] = new int[NUM_PLAYERS];

// set all elements of the positions array to INITIAL_POSITION
// Parameters: positions -- will store where the players are
// numPlayers -- how many there are
static void initialize(int positions[], int numPlayers) {
for (int player = 0; player < numPlayers; player++)
positions[player] = INITIAL_POSITION;
}

// Description: Test if String is a valid color in the game
// Parameter: str -- String to test
// Returns: true if it is a color in the game, false if not
static boolean isColor(String str) {
for (int color = 0; color < NUM_COLORS; color++) {
if (str.equals(COLORS[color]))
return true;
}
return false;
}

// Description: Starting after indicated position search forward on board to find the color
// Parameters: startPos -- index of current space of player -- start looking *after* this space
// color -- find the next space with this color
// Returns: index of next space of chosen color
static int findColor(int startPos, String color) {
for (int pos = startPos+1; pos < FINAL_POSITION; pos++)
if (board[pos].equals(color))
return pos;
return FINAL_POSITION;
}

// Description: find position of indicated person
// Parameters: name -- name of person to look for
// Returns: index of space for this name
static int findPerson(String name) {
if (name.equals(PLUMPY)) return 8;
if (name.equals(MR_MINT)) return 17;
if (name.equals(JOLLY)) return 42;
System.out.println("No such person in the game" );
return FINAL_POSITION; // should not get here -- just here to get program to stop
}

// Description: Move a player
// Parameters: player -- index of player to move
// card -- indicates where to move
// repeat -- true if card is a "double" color, false if not
// positions -- where the players are
// Returns: new position of player after move
static int move(int player, String card, boolean repeat, int positions[]) {
int nextPos = positions[player];

if (isColor(card)) {
nextPos = findColor(positions[player], card);
if (repeat)
nextPos = findColor(nextPos, card);
return nextPos;
}
else return findPerson(card);
}

// Description: Check for a winner
// Parameters: positions -- where the players are
// numPlayers -- how many there are
// Returns: true if there are no winners yet
// false if anyone has won
static boolean nowinner(int positions[], int numPlayers) {
for (int player = 0; player < NUM_PLAYERS; player++) {
if (positions[player] == FINAL_POSITION) // reached the end
return false;
}
return true;
}

// Description: Display welcome String
static void printIntro() {
System.out.println("This is a crude version of Candyland\n");
}

// Generate the next value "drawn"
// Returns: the value of the next card drawn. Returning the empty String indicates
// there are no more values
static String draw() {
String testRolls[] = {PLUMPY, YELLOW, RED, YELLOW, GREEN, MR_MINT, JOLLY, RED, GREEN};
final int NUM_CARDS = 9;
next = 0;

if (next >= NUM_CARDS) return "";
return testRolls[++next];
}

// Indicate if this card is a "double" color
// Returns: true if the color is a double, false if not.
// NOTE: This is a very bad way to do this -- but it does help to motivate structures
static boolean drawRepeat() {
boolean testRollsRepeat[] = {false, true, false, true, false, false, false, false, false};
final int NUM_CARDS = 9;
next = 0;

if (next >= NUM_CARDS) return false;
return testRollsRepeat[next++];
}

// Print the identity of the winner, if any.
// If there are no winners, do nothing.
// Parameters:
// positions -- the array indicating where the players are located
// numPlayers -- the number of players
static void printWinner(int positions[], int numPlayers) {
for (int player = 0; player < numPlayers; player++) {
// Would be clearer to use a different constant to
// explicitly define the winning position
if (positions[player] == FINAL_POSITION)
System.out.println("Player " + player + " wins!");
}
}

// Description: Play the game
static void playGame() {
// Use nextPlayer to switch among the players
int nextPlayer = 0;
boolean done = false;

initialize(positions, NUM_PLAYERS);
while (nowinner(positions, NUM_PLAYERS) && !done) {
String nextCard = draw();
//System.out.println(nextCard);
boolean repeat = drawRepeat();

if (!(nextCard.equals(" "))) {
positions[nextPlayer] = move(nextPlayer, nextCard, repeat, positions);
System.out.println("Player " +nextPlayer + " is at position "
+ positions[nextPlayer]);
nextPlayer = (nextPlayer + 1) % NUM_PLAYERS;
}
else done = true;
}
if (nowinner(positions, NUM_PLAYERS))
System.out.println("No winner" );
else printWinner(positions, NUM_PLAYERS);
}

public static void main(String a[]) {
printIntro();
playGame();

}

}


Related Solutions

C++ Given Code: #include <iostream> #include <string> using namespace std; int main() { //declare variables to...
C++ Given Code: #include <iostream> #include <string> using namespace std; int main() { //declare variables to store user input bool cont = true; //implement a loop so that it will continue asking until the user provides a positive integer // the following provides ONLY part of the loop body, which you should complete { cout <<"How many words are in your message? \n"; cout <<"Enter value: "; // get user input integer here    cout <<"\nInvalid value. Please Re-enter a...
What is the flowchart for this code. Thank You! #include<iostream> #include<iomanip> #include<string> #include<cmath> using namespace std;...
What is the flowchart for this code. Thank You! #include<iostream> #include<iomanip> #include<string> #include<cmath> using namespace std; float series(float r[], int n) {    float sum = 0;    int i;    for (i = 0; i < n; i++)        sum += r[i];    return sum; } float parallel(float r[], int n) {    float sum = 0;    int i;    for (i = 0; i < n; i++)        sum = sum + (1 / r[i]);...
Plz convert this C++ code into JAVA code thanks #include<iostream> using namespace std; //function for calculating...
Plz convert this C++ code into JAVA code thanks #include<iostream> using namespace std; //function for calculating the average sightings from the Total Sightings array float calcAverage(float totalSightings[],int n) {    int i;    float sum=0.0;    for(i=0;i<n;i++)    sum=sum+totalSightings[i];    return sum/n; } int main() {    // n is no. of bird watchers    //flag , flag2 and flag3 are for validating using while loops    int n,i,flag,flag2,flag3;       //ch also helps in validating    char ch;   ...
Can someone covert the code into C language #include<iostream> #include<iomanip> #include<ios> using namespace std; /******************************************************************************** Function...
Can someone covert the code into C language #include<iostream> #include<iomanip> #include<ios> using namespace std; /******************************************************************************** Function name: main Purpose:                   main function In parameters: b,r,i Out paramters: trun,error,total,value Version:                   1.0 Author: ********************************************************************************/ void main() {    int i;//declaring this variable to get value for quitting or calaculating series    do {//do while loop to calaculate series until user quits        cout << "Enter 1 to evaluate the series." << endl;       ...
#include <iostream> #include <string> #include <sstream> using namespace std; int main() { string userInput; getline(cin, userInput);...
#include <iostream> #include <string> #include <sstream> using namespace std; int main() { string userInput; getline(cin, userInput); // Declaring base int N = 30; if (userInput.length() > 10) { cout << 0 << endl; } else { int finalTotal = 0; //Iterates through userInput for(int i = 0; i < 10; i++){ char convertedInput = userInput[i]; // ASCII decimal value of each character int asciiDec = int(convertedInput); //Casts char value from input to int value stringstream chr; chr << convertedInput; int...
#include <iostream> #include <string> #include <fstream> #include <vector> #include <sstream> using namespace std; int main() {...
#include <iostream> #include <string> #include <fstream> #include <vector> #include <sstream> using namespace std; int main() { ifstream infile("worldpop.txt"); vector<pair<string, int>> population_directory; string line; while(getline(infile, line)){ if(line.size()>0){ stringstream ss(line); string country; int population; ss>>country; ss>>population; population_directory.push_back(make_pair(country, population)); } } cout<<"Task 1"<<endl; cout<<"Names of countries with population>=1000,000,000"<<endl; for(int i=0;i<population_directory.size();i++){ if(population_directory[i].second>=1000000000){ cout<<population_directory[i].first<<endl; } } cout<<"Names of countries with population<=1000,000"<<endl; for(int i=0;i<population_directory.size();i++){ if(population_directory[i].second<=1000000){ cout<<population_directory[i].first<<endl; } } } can u pls explain the logic behind this code up to 10 lines pls, many thanks
#include <iostream> #include <string> #include <iomanip> #include <cstdlib> #include "Contact.h" using namespace std; class Contact {...
#include <iostream> #include <string> #include <iomanip> #include <cstdlib> #include "Contact.h" using namespace std; class Contact { public: Contact(string init_name = "", string init_phone = "000-000-0000"); void setName(string name); void setPhone(string phone); string getName()const; string getPhone()const; friend ostream& operator << (ostream& os, const Contact& c); friend bool operator == (const Contact& c1, const Contact& c2); friend bool operator != (const Contact& c1, const Contact& c2); private: string name, phone; }; Contact::Contact(string init_name, string init_phone) { name = init_name; phone = init_phone;...
write the algorithm for this the code?!. #include<iostream> using namespace std; #include<string.h> int main() { char...
write the algorithm for this the code?!. #include<iostream> using namespace std; #include<string.h> int main() { char plain[50], cipher[50]="", decrypt[50]=""; int subkeys[50], len;       cout<<"Enter the plain text:"<<endl; cin>>plain;    cout<<"Enter the first subkey:"<<endl; cin>>subkeys[0];    _strupr(plain);    len = strlen(plain);    /**********Find the subkeys**************/    for(int i=1; i<len; i++) { if ((plain[i-1]>='A') && (plain[i-1]<='Z')) { subkeys[i] = plain[i-1]-65; } }    /****************ENCRYPTION***************/       for(int i=0; i<len; i++) { if ((plain[i]>='A') && (plain[i]<='Z')) {    cipher[i] = (((plain[i]-65)+subkeys[i])%26)+65; }...
#include <iostream> #include <string> #include <vector> using namespace std; class Song{ public: Song(); //default constructor Song(string...
#include <iostream> #include <string> #include <vector> using namespace std; class Song{ public: Song(); //default constructor Song(string t, string a, double d); //parametrized constructor string getTitle()const; // return title string getAuthor()const; // return author double getDurationMin() const; // return duration in minutes double getDurationSec() const; // return song's duration in seconds void setTitle(string t); //set title to t void setAuthor(string a); //set author to a void setDurationMin(double d); //set durationMin to d private: string title; //title of the song string author;...
Complete the C++ code #include <iostream> #include <stdlib.h> #include <time.h> using namespace std; struct Cell {...
Complete the C++ code #include <iostream> #include <stdlib.h> #include <time.h> using namespace std; struct Cell { int val; Cell *next; }; int main() { int MAX = 10; Cell *c = NULL; Cell *HEAD = NULL; srand (time(NULL)); for (int i=0; i<MAX; i++) { // Use dynamic memory allocation to create a new Cell then initialize the // cell value (val) to rand(). Set the next pointer to the HEAD and // then update HEAD. } print_cells(HEAD); }
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT