Parsing Arrays in C++An array can be defined as a data structure consisting of a group of elements. Basically, all these elements have the same data type, for example, a string or integer. Arrays are used in C++ and other programming languages to organize data or information, so that, values and var...
Game theory
public class GameStat {
/**
* Has private ints that track the player and computer sentence/years and the number of rounds played
*/
private String strategy;
private int userSentence;
private int computerSentence;
private int roudPlayed;
/**
* returns the string strategy computer used in the game
* @return
*/
public String getComputerStrategy() {
return strategy;
}
/**
* Increments the stats and is called from pdgame
* @param userSentence
* @param compSentence
*/
public void update(int userSentence, int compSentence) {
this.roudPlayed += 1;
this.userSentence = userSentence;
this.computerSentence = compSentence;
}
/**
* returns the winner of the game, after comparing the years of player and computer
* @return
*/
public String getWinner() {
if (computerSentence>= userSentence) {
return "The winner for this game is: Computer.";
}
return "The winner for this game is: you the game player.";
}
/**
* Get the rounds played
* @return
*/
public int getRoudsPlayed() {
return roudPlayed;
}
/**
* Set the rounds played
* @param rounds
*/
public void setRoudsPlayed(int rounds) {
this.roudPlayed = rounds;
}
/**
* Set the strategy
* @param strategy
*/
public void setComputerStrategy(String strategy) {
this.strategy = strategy;
}
public int getUserSentnce() {
return userSentence;
}
public int getComputerSentence() {
return computerSentence;
}
}
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
/**
* This class represents the game itself and controls the logic for it.
* It contains an ArrayList for keeping the user history,
* an array or ArrayList of strings for each of the strategies you implement below,
* a GameStat null reference object that when filled in will record the game stats,
* a Scanner, and an integer to determine the strategy the computer is using
*
*/
public class PDGame {
private ArrayListuserHistory;
private ArrayListtheStrategies;
private GameStatgameStat;
private Scanner scanner = null;
private int strategy;
private String scores;
/**
* The constructor should initialize the Scanner to read from a text file that has random 1, 2,
* etc in it
* @param file : text file name
*/
public PDGame(String file) {
userHistory = new ArrayList<>();
theStrategies = new ArrayList<>();
theStrategies.add("1.Computer Reads Strategy from Input File.");
theStrategies.add("2.Tit-For-Tat");
theStrategies.add("3.Tit-For-Two-Tats");
theStrategies.add("4.Random Choice by Computer");
gameStat = new GameStat();
try {
scanner = new Scanner(new File(file));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
/**
* Method that generates the computer's decision based on the strategy selected,
* determine the outcome based on the two decisions,
* and update the GameStat object according to the scoring above
* @param decision
* @return
*/
public String playRound(int decision) {
userHistory.add(decision);
int computerDecision = 0;
switch (strategy) {
case 1: // From file
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
computerDecision = Integer.parseInt(line);
break;
}
break;
case 2: // Tit for tat
if (gameStat.getRoudsPlayed() == 0) {
computerDecision = 1;
} else {
// Get previous computer decision
computerDecision = userHistory.get(userHistory.size() - 2);
}
break;
case 3: // Tit for two tat
if (gameStat.getRoudsPlayed() == 0 || gameStat.getRoudsPlayed() == 1) {
computerDecision = 1;
} else {
if (userHistory.get(userHistory.size() - 2) == 2 &&userHistory.get(userHistory.size() - 3) == 2) {
computerDecision = 2;
} else {
computerDecision = 1;
}
}
break;
case 4: // Random
computerDecision = (int) (Math.random() * 2 + 1);
break;
default:
break;
}
if (decision == 1) {
switch (computerDecision) {
case 1:
gameStat.update(2, 2);
return "You and your partner remain silent\nYou both get 2 years in prison.";
case 2:
gameStat.update(5, 1);
return "You remain silent and they testify against you.\nYou get 5 years in prison and they get 1.";
default:
break;
}
} else if (decision == 2) {
switch (computerDecision) {
case 1:
gameStat.update(1, 5);
return "You testify against your partner and they remain silent.\nYou get 1 year in prison and they get 5.";
default:
break;
}
}
gameStat.update(3, 3);
return "You and your partner testify against eachother.\nYou both get 3 years in prison";
}
/**
* Returns an ArrayList of strings, in the array list are the 5 strategies
* one can choose for the computer (File, tit for tat, etc)
* @return
*/
public ArrayListgetStrategies() {
return theStrategies;
}
/**
* Returns a string message indicating what the final scores are
* @return
*/
public String getScores() {
return "---Your prison sentence is: " + gameStat.getUserSentnce() + "\n------Your partner's/computer prison sentence is: "
+ gameStat.getComputerStrategy();
}
/**
* Get method for the GameStat data member. Returns the pointer to GameStat for this game
* @return
*/
public GameStatgetStats() {
return gameStat;
}
/**
* Set method for the strategy data member.
* This also calls the GameStat setter with the string obtained
* from the ArrayList at the appropriate index.
*
* Implement 3 out of the following 4 strategies:
* - From File – Cooperates and betray based on input from an input file that has 1’s and 2’s in it.
* - Tit-For-Tat – Cooperate on the first move, otherwise play the player's last move.
* - Tit-For-Two-Tats – Cooperate on the first 2 moves, otherwise betray if the player's last 2 moves were betrayals.
* - Random – Random number of 1 or 2
* @param strategy
*/
public void setStrategy(int strategy) {
this.strategy = strategy;
gameStat.setComputerStrategy(theStrategies.get(strategy - 1));
}
}
import java.util.Date;
import java.util.HashMap;
import java.util.Scanner;
/**
* This class provides an interface for user input
*
*/
public class PDGameApp {
/**
* A game consists of 5 rounds of play.
* In each round, Prompt the user for their move,
* pass the input to the PDGame's method playRound(),
* and receive back a string that prints the outcome returned back from PDGame.
* Print the total years of prison sentences (you will need to get access to the GameStat object)
* after the loop of 5 rounds and prompt for a new game.
* Finally, print an overall summary from the GameStat objects in a HashMap.
* This includes the key, the game winner, and the computer strategy. .
* You can use a "for" each loop to iterate over each entry in
* the HashMap: for(String key : stats.keySet())
* Input for selected strategy and player decision will be an int.
* Prompts should clearly indicate to the user what to input.
* All input MUST be validated for both the correct type as well as range of values
* e.g. the computer rejects '1' or 'L' when the user is prompted for another game and rejects '0' or 'Y'
* when the user is prompted for computer strategy
*/
public static void main(String[] args) {
/**
* Within the main() method you will need a
* Scanner to retrieve the input from the console,
* a PDGame object that will control the play of each game,
* and a HashMap to store the GameStat objects from each PDGame.
*/
Scanner scanner = new Scanner(System.in);
GameStatgameStat = null;
PDGamecurrentGame = null;
HashMapmapGame = new HashMap<>();
booleanisRunning = true;
while (isRunning) {
currentGame = new PDGame("inputs.txt");
System.out.println("***Starting A Game of Prisoner's Dilemma ***-5 rounds in this version of game");
System.out.println();
System.out.println("--HERE ARE STRATEGIES AVAILABLE FOR THE COMPUTER\n");
for (String strategies :currentGame.getStrategies()) {
System.out.println(strategies);
}
System.out.println("\nSelect a strategy from above for the Computer to use in the 5 rounds: ");
int userinput = scanner.nextInt();
if (userinput> 4 || userinput< 1) {
System.out.println("Out of range. Please input correct number.");
continue;
}
currentGame.setStrategy(userinput);
gameStat = currentGame.getStats();
Date date = new Date();
mapGame.put(date.toString(), gameStat);
for (int i = 0; i< 5; i++) {
System.out.println("\n\nBEGIN A ROUND - Here are your 2 choices");
System.out.println("1. Remain silent.");
System.out.println("2. Betray and testify against.\n");
System.out.println("----What is your decision this round? ");
int decision = scanner.nextInt();
if (decision > 2 || decision < 1) {
System.out.println("Please Enter in given 2 choices");
i--;
continue;
}
System.out.println(currentGame.playRound(decision));
}
String scores = currentGame.getScores();
System.out.println("\nEND OF ROUNDS, GAME OVER");
System.out.println(scores);
System.out.println(gameStat.getWinner());
System.out.println("\n--Would you like to play another game (y/n)? ");
if (!scanner.next().equalsIgnoreCase("Y")) {
isRunning = false;
}
}
System.out.println("\t\tSummary of games and session times:");
for (String timeStamp :mapGame.keySet()) {
System.out.println(timeStamp);
System.out.println(mapGame.get(timeStamp).getWinner());
System.out.println("The Computer Used: " + mapGame.get(timeStamp).getComputerStrategy());
}
}
}
Demonstrating arrays in C++
#include
#include
#include "FileReader.h"
FileReader::FileReader(std::istream&inputStream) : inputStream(inputStream)
{
this->order = 0;
this->foundNext = false;
}
bool FileReader::tryNext() {
std::string str;
getline(this->inputStream, str);
try {
this->order = stoi(str);
} catch (std::invalid_argument exception) {
this->foundNext = false;
this->order = 0;
return false;
}
this->foundNext = this->order > 0;
return this->foundNext;
}
MagicSquare* FileReader::readNext() {
return MagicSquare::create(this->order);
}
#include
#include
#include "FileWriter.h"
#include "MagicSquare.h"
#define INVALID_ORDER "INVALID ORDER"
static int countDecimalPlaces(int value) {
int decimalPlaces = 1;
while (value >= 10) {
value = value / 10;
decimalPlaces += 1;
}
return decimalPlaces;
}
FileWriter::FileWriter(std::ostream&outputStream) : outputStream(outputStream)
{
}
void FileWriter::writeNext(MagicSquare* magicSquare) {
if (magicSquare == nullptr) {
this->outputStream<< INVALID_ORDER <
return;
}
int order = magicSquare->getOrder();
int largestValue = order * order;
int decimalPlaces = countDecimalPlaces(largestValue);
for (int y = 0; y < order; y += 1) {
// formatting for all numbers be inside columns, making a table
this->outputStream.width(decimalPlaces);
for (int x = 0; x < order; x += 1) {
int value = magicSquare->getValueAt(x, y);
this->outputStream<<<="" value="" "="" ";="" <="" p="" style="box-sizing: border-box; margin: 0px; padding: 0px;">
}
this->outputStream<<="" p="" style="box-sizing: border-box; margin: 0px; padding: 0px;">
}
this->outputStream<<="" p="" style="box-sizing: border-box; margin: 0px; padding: 0px;">
}
#include "MagicSquare.h"
static int adjust(int order, int coordinate) {
if (coordinate < 0) {
return (order + (coordinate % order));
}
return coordinate % order;
}
MagicSquare::MagicSquare(int order) {
this->order = order;
int length = order * order;
this->values = new int[length];
for (int i = 0; i< length; i += 1) {
this->values[i] = 0;
}
int x, y;
x = order / 2;
y = order / 2;
for (int value = 1; value <= length; value += 1) {
x = adjust(order, x);
y = adjust(order, y);
int otherValue = this->getValueAt(x, y);
if (otherValue != 0) { // already occupied
value -= 1;
x += 1;
y -= 2;
continue;
}
this->setValueAt(x, y, value);
x -= 1;
y += 1;
}
}
MagicSquare::~MagicSquare() {
delete this->values;
}
MagicSquare* MagicSquare::create(int order) {
if (order % 2 == 0) { // even numbers leads to no magic square
return nullptr;
}
MagicSquare* magicSquare = new MagicSquare(order);
return magicSquare;
}
int MagicSquare::getOrder() {
return this->order;
}
int MagicSquare::getValueAt(int x, int y) {
if (x < 0 || y < 0) { // out of bounds, return (-1)
return (-1);
}
if (x >= this->order || y >= this->order) { // out of bounds, return (-1)
return (-1);
}
return this->values[y * this->order + x];
}
void MagicSquare::setValueAt(int x, int y, int value) {
this->values[y * this->order + x] = value;
}
#include "FileReader.h"
#include "FileWriter.h"
#include "MagicSquare.h"
int main(int argc, char *argv[]) {
FileReaderreader(std::cin);
FileWriterwriter(std::cout);
while (reader.tryNext()) {
MagicSquare* magicSquare = reader.readNext();
writer.writeNext(magicSquare);
delete magicSquare;
}
return 0;
}