From e1cd179833ee335dce86b3e0a11317326c51f630 Mon Sep 17 00:00:00 2001 From: Sandipsinh Rathod Date: Tue, 19 Nov 2024 22:34:14 -0500 Subject: [PATCH] avoid checking just the first char --- main.cpp | 17 ++++++++++++++--- utils.cpp | 10 ++++++++++ utils.h | 3 +++ 3 files changed, 27 insertions(+), 3 deletions(-) diff --git a/main.cpp b/main.cpp index 5d0e9e1..4e5162a 100644 --- a/main.cpp +++ b/main.cpp @@ -38,15 +38,26 @@ int main() { // Read player 2 details cin >> player2Name >> player2Type; + // Validate player types + if (!equalsIgnoreCase(player1Type, "Random") && !equalsIgnoreCase(player1Type, "Strategic")) { + cerr << "Error: Invalid player 1 type. Must be 'Random' or 'Strategic'." << endl; + return 1; + } + + if (!equalsIgnoreCase(player2Type, "Random") && !equalsIgnoreCase(player2Type, "Strategic")) { + cerr << "Error: Invalid player 2 type. Must be 'Random' or 'Strategic'." << endl; + return 1; + } + // Determine player types and initialize gameplay Player *randomPlayerName, *strategicPlayerName; - if (toLowerCase(player1Type[0]) == 'r' && toLowerCase(player2Type[0]) == 's') { + if (equalsIgnoreCase(player1Type, "Random") && equalsIgnoreCase(player2Type, "Strategic")) { randomPlayerName = new RandomPlayer(player1Name); strategicPlayerName = new StrategicPlayer(player2Name); - } else if (toLowerCase(player1Type[0]) == 's' && toLowerCase(player2Type[0]) == 'r') { + } else if (equalsIgnoreCase(player1Type, "Strategic") && equalsIgnoreCase(player2Type, "Random")) { randomPlayerName = new RandomPlayer(player2Name); strategicPlayerName = new StrategicPlayer(player1Name); - } else if (toLowerCase(player1Type[0]) == 'r' && toLowerCase(player2Type[0]) == 'r') { + } else if (equalsIgnoreCase(player1Type, "Random") && equalsIgnoreCase(player2Type, "Random")) { randomPlayerName = new RandomPlayer(player2Name); strategicPlayerName = new RandomPlayer(player1Name); } else { diff --git a/utils.cpp b/utils.cpp index 845e686..96056e5 100644 --- a/utils.cpp +++ b/utils.cpp @@ -1,3 +1,13 @@ +#include + char toLowerCase(const char c) { return c | 32; } + +bool equalsIgnoreCase(const std::string &a, const std::string &b) { + if (a.size() != b.size()) return false; + for (size_t i = 0; i < a.size(); ++i) { + if (tolower(a[i]) != tolower(b[i])) return false; + } + return true; +} \ No newline at end of file diff --git a/utils.h b/utils.h index bf64564..5156bc2 100644 --- a/utils.h +++ b/utils.h @@ -1,4 +1,7 @@ #ifndef UTILS_H #define UTILS_H +#include + char toLowerCase(char c); +bool equalsIgnoreCase(const std::string &a, const std::string &b); #endif //UTILS_H