From c34a119909e8dc1988d3750dcdac5a6550d19e40 Mon Sep 17 00:00:00 2001 From: Phan Tho Date: Sat, 9 Mar 2024 14:10:09 +0700 Subject: [PATCH 01/11] upd --- AdvProg_L0-Hello/hello.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/AdvProg_L0-Hello/hello.cpp b/AdvProg_L0-Hello/hello.cpp index 91eafdd8d..4ba90bd8f 100644 --- a/AdvProg_L0-Hello/hello.cpp +++ b/AdvProg_L0-Hello/hello.cpp @@ -2,6 +2,5 @@ #include "hello.h" std::string printGameOver(){ - // TODO: Return the required string - return ""; + return "Game Over!"; } From 52d2e9a0782ee05bb8b9aff423f179c917db886e Mon Sep 17 00:00:00 2001 From: Phan Tho Date: Wed, 27 Mar 2024 02:36:21 +0700 Subject: [PATCH 02/11] complete --- .DS_Store | Bin 0 -> 6148 bytes .vscode/settings.json | 5 ++++ AdvProg_L1-GuessIt/guessit.cpp | 17 ++++++------ AdvProg_L2-Calculus/calculus.cpp | 6 ++--- AdvProg_L3-HangMan/hangman.cpp | 24 ++++++++++++++--- AdvProg_L4-SimpleAI/simpleai.cpp | 44 +++++++++++++++++++++++++++++++ 6 files changed, 82 insertions(+), 14 deletions(-) create mode 100644 .DS_Store create mode 100644 .vscode/settings.json diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..886c4cd4805f3c084b88f6012fbb3974a703689b GIT binary patch literal 6148 zcmeHKF-inM5Ukb<4onVA4Cey|f)5yvGY|}fdw`-VBCM<^8gJyge45qWgRtxgCMHr1 z-8IwGHOp48y$!(DZ`}#70zJdo5!`I`4SFfCpUT5~s83-3jL&;tU<$ zaW&x|V~a;T;Tb*dS#i<5-u1V`(C@xTSt%d|q<|EV0#e{t3V83OEe{eErGONW0^bVw z_o2`oYr`=yJ{=4(0uUEWhjAUV1hII6SR0Os%+M^U#H3mqF)ZoKmsVFBj)_T!wc*3s zldVlC7EkB>CCXtnQBev=fvE!fxm|hxKd1jN|4&KUNdYPFuN1JwX1iJQm0E9|y`1;j xLcgJV%_rTB>!2`1J0?au=EmFcQ50oe@iotD!!a@F%m> number; + return number; } @@ -46,7 +46,9 @@ string getAnswer(int number, int randomNumber) { If number is equal randomNumber, the answer is "Congratulation! You win." ***/ string answer; - + if (number > randomNumber) answer = "Your number is higher."; + else if (number < randomNumber) answer = "Your number is lower."; + else answer = "Congratulation! You win."; return answer; } @@ -59,8 +61,7 @@ string getAnswer(int number, int randomNumber) { ***/ bool checkSuccess(string answer) { // TODO: return the result after checking that player guessed right or wrong - - return true; + return (answer == "Congratulation! You win."); } @@ -73,7 +74,7 @@ bool checkSuccess(string answer) { bool checkContinuePlaying(char isContinued) { // TODO: return result after checking player continue playing or not bool result = false; - + if(isContinued == 'Y' || isContinued == 'y') result = true; return result; } @@ -86,7 +87,7 @@ bool checkContinuePlaying(char isContinued) { ***/ char getPlayerOpinion() { // TODO: Ask the player about continue playing and return the player's choice - char isContinued; + char isContinued; cin >> isContinued; return isContinued; } diff --git a/AdvProg_L2-Calculus/calculus.cpp b/AdvProg_L2-Calculus/calculus.cpp index 37d8639ea..11a4727e7 100644 --- a/AdvProg_L2-Calculus/calculus.cpp +++ b/AdvProg_L2-Calculus/calculus.cpp @@ -20,7 +20,7 @@ double mySqrt(double x); ***/ double myCos(double x) { - return 0.0; + return cos(x); } /*** @@ -31,7 +31,7 @@ double myCos(double x) ***/ double mySin(double x) { - return 0.0; + return sin(x); } @@ -48,5 +48,5 @@ double mySqrt(double x) { } - return 0; + return sqrt(x); } \ No newline at end of file diff --git a/AdvProg_L3-HangMan/hangman.cpp b/AdvProg_L3-HangMan/hangman.cpp index 6cddadbef..e908aaec7 100644 --- a/AdvProg_L3-HangMan/hangman.cpp +++ b/AdvProg_L3-HangMan/hangman.cpp @@ -17,7 +17,7 @@ using std::cin; int generateRandomNumber(const int min, const int max) { // TODO: Return a random integer number between min and max - return 1; + return rand()%(max - min + 1) + min; } vector readWordListFromFile(const string& filePath) @@ -51,6 +51,9 @@ vector readWordListFromFile(const string& filePath) bool isCharInWord(const char ch, const string& word) { // TODO: return true if ch is in word else return false + for(int i = 0; i < word.size(); i++){ + if (ch == word[i]) return true; + } return true; } @@ -65,7 +68,7 @@ string chooseWordFromList(const vector& wordList, int index) { // TODO: Return a lowercase word in the index position of the vector wordList. string answer; - + answer = wordList[index]; return answer; } @@ -78,7 +81,9 @@ string chooseWordFromList(const vector& wordList, int index) string generateHiddenCharacters(string answerWord){ // TODO: Based on answerWord's length, generate hidden characters in form of "---" string secretWord; - + for(int i = 0; i < answerWord.size(); i++){ + secretWord += '-'; + } return secretWord; } @@ -99,6 +104,9 @@ char getInputCharacter() { void updateSecretWord(string& secretWord, const char ch, const string& word) { // TODO: Update the secret word if the character ch is in the answer word. + for(int i = 0; i < word.size(); i++){ + if (ch == word[i]) secretWord[i] = ch; + } } /*** @@ -110,6 +118,7 @@ void updateSecretWord(string& secretWord, const char ch, const string& word) ***/ void updateEnteredChars(const char ch, string& chars){ // TODO: append the character ch is in end of the text chars + chars += ch; } /*** @@ -120,6 +129,7 @@ void updateEnteredChars(const char ch, string& chars){ ***/ void updateIncorrectGuess(int& incorrectGuess){ // TODO: increase the value of incorrectGuess by 1 + incorrectGuess++; } /*** @@ -146,5 +156,13 @@ void processData(const char ch, const string& word, update incorrectGuess: call updateIncorrectGuess() function update incorrectChars: call updateEnteredChars() function ***/ + if (isCharInWord(ch, word)){ + updateSecretWord(secretWord, ch, word); + updateEnteredChars(ch, correctChars); + } + else{ + updateIncorrectGuess(incorrectGuess); + updateEnteredChars(ch, incorrectChars); + } } diff --git a/AdvProg_L4-SimpleAI/simpleai.cpp b/AdvProg_L4-SimpleAI/simpleai.cpp index 7176c579f..2889e50dc 100644 --- a/AdvProg_L4-SimpleAI/simpleai.cpp +++ b/AdvProg_L4-SimpleAI/simpleai.cpp @@ -28,6 +28,11 @@ vector filterWordsByLen(int wordLen, const vector& vocabulary) { vector answer; //Write your code here + for(int i = 0; i < vocabulary.size(); i++){ + if (vocabulary[i].size() == wordLen){ + answer.push_back(vocabulary[i]); + } + } return answer; } @@ -42,6 +47,12 @@ char nextCharWhenWordIsNotInDictionary(const set& selectedChars) { char answer; //Write your code here + for(char ch = 'a'; ch <= 'z'; ch++){ + if (selectedChars.find(ch) == selectedChars.end()){ + answer = ch; + break; + } + } return answer; } @@ -56,6 +67,11 @@ map countOccurrences(const vector& candidateWords) { map answer; //Write your code here + for(int i = 0; i < candidateWords.size(); i++){ + for(int j = 0; j < candidateWords[i].size(); j++){ + answer[candidateWords[i][j]]++; + } + } return answer; } @@ -71,6 +87,15 @@ char findMostFrequentChar(const map& occurrences, const set& se { char answer; //Write your code here + int max = 0; + for(auto it = occurrences.begin(); it != occurrences.end(); it++){ + if (selectedChars.find(it->first) == selectedChars.end()){ + if(it->second > max){ + max = it->second; + answer = it->first; + } + } + } return answer; } @@ -86,6 +111,9 @@ char findBestChar(const vector& candidateWords, const set& selecte { char answer; //Write your code here + map occurrences = countOccurrences(candidateWords); + answer = findMostFrequentChar(occurrences, selectedChars); + return answer; } @@ -110,6 +138,7 @@ bool isCorrectChar(char ch, const string& mask) { bool answer; //Write your code here + answer = (find(mask.begin(), mask.end(), ch) != mask.end()); return answer; } @@ -125,6 +154,7 @@ bool isWholeWord(const string& mask) { bool answer; //Write your code here + answer = (find(mask.begin(), mask.end(), MASK_CHAR) == mask.end()); return answer; } @@ -144,6 +174,15 @@ bool wordConformToMask(const string& word, const string& mask, char ch) { bool answer; //Write your code here + answer = true; + for(int i = 0; i < word.size(); i++){ + if (mask[i] == MASK_CHAR){ + if (word[i] != ch){ + answer = false; + break; + } + } + } return answer; } @@ -163,5 +202,10 @@ vector filterWordsByMask(const vector& words, const string& mask { vector answer; //Write your code here + for(int i = 0; i < words.size(); i++){ + if (wordConformToMask(words[i], mask, ch)){ + answer.push_back(words[i]); + } + } return answer; } \ No newline at end of file From ff23ad3fbc146d74ccdaa9753157c6d7c81f807f Mon Sep 17 00:00:00 2001 From: Phan Tho Date: Wed, 27 Mar 2024 02:45:07 +0700 Subject: [PATCH 03/11] complete --- AdvProg_L0-Hello/hello.cpp | 2 +- AdvProg_L1-GuessIt/guessit.cpp | 2 +- AdvProg_L2-Calculus/calculus.cpp | 2 +- AdvProg_L3-HangMan/hangman.cpp | 2 +- AdvProg_L4-SimpleAI/simpleai.cpp | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/AdvProg_L0-Hello/hello.cpp b/AdvProg_L0-Hello/hello.cpp index 4ba90bd8f..087ac3998 100644 --- a/AdvProg_L0-Hello/hello.cpp +++ b/AdvProg_L0-Hello/hello.cpp @@ -3,4 +3,4 @@ std::string printGameOver(){ return "Game Over!"; -} +} diff --git a/AdvProg_L1-GuessIt/guessit.cpp b/AdvProg_L1-GuessIt/guessit.cpp index 539023dc4..23e73fccb 100644 --- a/AdvProg_L1-GuessIt/guessit.cpp +++ b/AdvProg_L1-GuessIt/guessit.cpp @@ -91,7 +91,7 @@ char getPlayerOpinion() { return isContinued; } - + void playGuessIt() { int randomNumber = generateRandomNumber(); diff --git a/AdvProg_L2-Calculus/calculus.cpp b/AdvProg_L2-Calculus/calculus.cpp index 11a4727e7..3006b4dc7 100644 --- a/AdvProg_L2-Calculus/calculus.cpp +++ b/AdvProg_L2-Calculus/calculus.cpp @@ -33,7 +33,7 @@ double mySin(double x) { return sin(x); } - + /*** Args: diff --git a/AdvProg_L3-HangMan/hangman.cpp b/AdvProg_L3-HangMan/hangman.cpp index e908aaec7..0d8fbdefd 100644 --- a/AdvProg_L3-HangMan/hangman.cpp +++ b/AdvProg_L3-HangMan/hangman.cpp @@ -155,7 +155,7 @@ void processData(const char ch, const string& word, else: update incorrectGuess: call updateIncorrectGuess() function update incorrectChars: call updateEnteredChars() function - ***/ + ***/ if (isCharInWord(ch, word)){ updateSecretWord(secretWord, ch, word); updateEnteredChars(ch, correctChars); diff --git a/AdvProg_L4-SimpleAI/simpleai.cpp b/AdvProg_L4-SimpleAI/simpleai.cpp index 2889e50dc..c2ce1a1b9 100644 --- a/AdvProg_L4-SimpleAI/simpleai.cpp +++ b/AdvProg_L4-SimpleAI/simpleai.cpp @@ -15,7 +15,7 @@ int readWordLen() cin >> wordLen; return wordLen; -} +} /*** Args: From 9d6c9a9a96911f9f269c8699c65eec53ababf591 Mon Sep 17 00:00:00 2001 From: Phan Tho Date: Wed, 27 Mar 2024 02:45:42 +0700 Subject: [PATCH 04/11] Delete .vscode directory --- .vscode/settings.json | 5 ----- 1 file changed, 5 deletions(-) delete mode 100644 .vscode/settings.json diff --git a/.vscode/settings.json b/.vscode/settings.json deleted file mode 100644 index 06caa9d90..000000000 --- a/.vscode/settings.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "files.associations": { - "map": "cpp" - } -} \ No newline at end of file From f63b84d335fc85b1f28a3bff2c358231da549e45 Mon Sep 17 00:00:00 2001 From: Phan Tho Date: Wed, 27 Mar 2024 02:45:56 +0700 Subject: [PATCH 05/11] Delete .DS_Store --- .DS_Store | Bin 6148 -> 0 bytes 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 .DS_Store diff --git a/.DS_Store b/.DS_Store deleted file mode 100644 index 886c4cd4805f3c084b88f6012fbb3974a703689b..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 6148 zcmeHKF-inM5Ukb<4onVA4Cey|f)5yvGY|}fdw`-VBCM<^8gJyge45qWgRtxgCMHr1 z-8IwGHOp48y$!(DZ`}#70zJdo5!`I`4SFfCpUT5~s83-3jL&;tU<$ zaW&x|V~a;T;Tb*dS#i<5-u1V`(C@xTSt%d|q<|EV0#e{t3V83OEe{eErGONW0^bVw z_o2`oYr`=yJ{=4(0uUEWhjAUV1hII6SR0Os%+M^U#H3mqF)ZoKmsVFBj)_T!wc*3s zldVlC7EkB>CCXtnQBev=fvE!fxm|hxKd1jN|4&KUNdYPFuN1JwX1iJQm0E9|y`1;j xLcgJV%_rTB>!2`1J0?au=EmFcQ50oe@iotD!!a@F%m Date: Wed, 27 Mar 2024 02:56:45 +0700 Subject: [PATCH 06/11] fix simple AI --- AdvProg_L4-SimpleAI/simpleai.cpp | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/AdvProg_L4-SimpleAI/simpleai.cpp b/AdvProg_L4-SimpleAI/simpleai.cpp index c2ce1a1b9..eb4755609 100644 --- a/AdvProg_L4-SimpleAI/simpleai.cpp +++ b/AdvProg_L4-SimpleAI/simpleai.cpp @@ -136,9 +136,14 @@ string getWordMask(char nextChar) bool isCorrectChar(char ch, const string& mask) { - bool answer; + bool answer = false; //Write your code here - answer = (find(mask.begin(), mask.end(), ch) != mask.end()); + for(auto it : mask){ + if (it == ch){ + answer = true; + break; + } + } return answer; } @@ -152,9 +157,14 @@ bool isCorrectChar(char ch, const string& mask) ***/ bool isWholeWord(const string& mask) { - bool answer; + bool answer = true; //Write your code here - answer = (find(mask.begin(), mask.end(), MASK_CHAR) == mask.end()); + for(auto it : mask){ + if (it == MASK_CHAR){ + answer = false; + break; + } + } return answer; } From 63c2bfa96a86f5e245a4d898e3a549487afd4ee1 Mon Sep 17 00:00:00 2001 From: Phan Tho Date: Wed, 27 Mar 2024 03:17:44 +0700 Subject: [PATCH 07/11] complete painter --- AdvProg_L6-Painter/painter.cpp | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/AdvProg_L6-Painter/painter.cpp b/AdvProg_L6-Painter/painter.cpp index 8f8629f75..90f4fb602 100644 --- a/AdvProg_L6-Painter/painter.cpp +++ b/AdvProg_L6-Painter/painter.cpp @@ -9,6 +9,8 @@ void Painter::setColor(SDL_Color color) { // TODO: set the color value for the Painter and set Render Draw Color + this->color = color; + SDL_SetRenderDrawColor(renderer, color.r, color.g, color.b, color.a); } @@ -21,6 +23,8 @@ void Painter::setColor(SDL_Color color) void Painter::jumpForward(int numPixel) { // TODO: jump the painter forward + x += (int) (cos(angle * M_PI / 180) * numPixel); + y -= (int) (sin(angle * M_PI / 180) * numPixel); } @@ -33,6 +37,7 @@ void Painter::jumpForward(int numPixel) void Painter::jumpBackward(int numPixel) { // TODO: jump the painter backward + jumpForward(-numPixel); } @@ -45,6 +50,9 @@ void Painter::jumpBackward(int numPixel) void Painter::turnLeft(double degree) { // TODO: rotate left the painter + angle += degree; + if (angle >= 360) angle -= 360; + if (angle < 0) angle += 360; } @@ -57,6 +65,7 @@ void Painter::turnLeft(double degree) void Painter::turnRight(double degree) { // TODO: rotate right the painter + turnLeft(-degree); } /*** @@ -67,7 +76,8 @@ void Painter::turnRight(double degree) ***/ void Painter::randomColor() { - // TODO: set random color + // TODO: set random color + SDL_Color newColor = {rand() % 256, rand() % 256, rand() % 256}; } From 815ddc9b837ffc88fb724fb8a614a1e243bfe0e6 Mon Sep 17 00:00:00 2001 From: Phan Tho Date: Wed, 27 Mar 2024 13:52:05 +0700 Subject: [PATCH 08/11] fix painter --- AdvProg_L6-Painter/painter.cpp | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/AdvProg_L6-Painter/painter.cpp b/AdvProg_L6-Painter/painter.cpp index 90f4fb602..73f88f721 100644 --- a/AdvProg_L6-Painter/painter.cpp +++ b/AdvProg_L6-Painter/painter.cpp @@ -77,7 +77,11 @@ void Painter::turnRight(double degree) void Painter::randomColor() { // TODO: set random color - SDL_Color newColor = {rand() % 256, rand() % 256, rand() % 256}; + // cast int to Uint8 + uint8_t r = static_cast(rand() % 256); + uint8_t g = static_cast(rand() % 256); + uint8_t b = static_cast(rand() % 256); + SDL_Color newColor = {r, g, b}; } From e6bb8f7a82343db2a8a4959fd8d193c9506eb29c Mon Sep 17 00:00:00 2001 From: Phan Tho Date: Wed, 27 Mar 2024 14:01:51 +0700 Subject: [PATCH 09/11] fix error init --- AdvProg_L6-Painter/utils.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/AdvProg_L6-Painter/utils.cpp b/AdvProg_L6-Painter/utils.cpp index 671be29a0..b43bbe10b 100644 --- a/AdvProg_L6-Painter/utils.cpp +++ b/AdvProg_L6-Painter/utils.cpp @@ -26,7 +26,7 @@ void initSDLsoftware(SDL_Window **window, SDL_Renderer **renderer) { } void initSDL(SDL_Window **window, SDL_Renderer **renderer) { - if (SDL_Init(SDL_INIT_EVERYTHING) != 0) { + if (SDL_Init(SDL_INIT_VIDEO) != 0) { logSDLError(std::cout, "SDL_Init"); std::cout << "The program will still continue without a video device!" << std::endl; initSDLsoftware(window, renderer); From ddf2ef5eb19d3a4094e469abdf7b18d69339234b Mon Sep 17 00:00:00 2001 From: Phan Tho Date: Tue, 4 Jun 2024 00:07:11 +0700 Subject: [PATCH 10/11] complete --- .DS_Store | Bin 0 -> 6148 bytes AdvProg_L3-HangMan/hangman.cpp | 37 +++++++------ AdvProg_L6-Painter/painter.cpp | 62 +++++++++++----------- AdvProg_L7-Snake/Game.cpp | 92 ++++++++++++++++++++------------- AdvProg_L7-Snake/Snake.cpp | 73 ++++++++++++++++---------- 5 files changed, 153 insertions(+), 111 deletions(-) create mode 100644 .DS_Store diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..4e4302ea71e5a84ec5cd0e5a9d5908be67c61bb7 GIT binary patch literal 6148 zcmeHK!EVz)5S>i}iB%y*K&2j6;+l%kmWYaro0dZ*4hSPS017q^#lrPQw$mJRF}A~Yk-zRm2sUGKBCn;{}Knx&73dPLNPGqwUWHyDqzuUX4Swt&jc zQIer^8q;$+T+5cgCMv-1?j9XeN|*G4etv&@6j4SOG^Ly-$T<6yRv!~%a^A+>8z@8C z!xS+{1=XOG$-J5-xk-@!Et%$7RSyQ=Rcot#>vpFTbhbP1qt9j@)p0$mMsfL;f4#y2 z$*LbGud~T~+`E5biaO4UNofgLIzh_2H(8OI`N+(Qw6fgD4Fo|q825G;i~XZvUmrYq zyzJ}6(f**X4-baRWzgMu@bKx&@t6FfFju@8e7*R5t=;jsg0JZO(Oxg3vdB$wj{MbJ zt2qQk0Z~8{*f<6JLDk*fxF?eb5(Pwof2{zY4;s!GdTbopqXUgC0f23Ut)b7g1aq{< z&|~8eBQWKtKu1-+#88foxb}IW$Ht+flk&xf@+&J}p(wjL=GQizROnDzQ9u; readWordListFromFile(const string& filePath) @@ -69,6 +70,11 @@ string chooseWordFromList(const vector& wordList, int index) // TODO: Return a lowercase word in the index position of the vector wordList. string answer; answer = wordList[index]; + for(int i = 0; i < answer.size(); i++){ + if(answer[i] >= 'A' && answer[i] <= 'Z'){ + answer[i] += 'a' - 'A'; + } + } return answer; } @@ -81,7 +87,7 @@ string chooseWordFromList(const vector& wordList, int index) string generateHiddenCharacters(string answerWord){ // TODO: Based on answerWord's length, generate hidden characters in form of "---" string secretWord; - for(int i = 0; i < answerWord.size(); i++){ + for(int i = 0; i < int(answerWord.length()); i++){ secretWord += '-'; } return secretWord; @@ -104,8 +110,8 @@ char getInputCharacter() { void updateSecretWord(string& secretWord, const char ch, const string& word) { // TODO: Update the secret word if the character ch is in the answer word. - for(int i = 0; i < word.size(); i++){ - if (ch == word[i]) secretWord[i] = ch; + for (int i = 0; i< secretWord.length(); i++){ + if (ch == word[i]) secretWord[i] = ch; } } @@ -119,6 +125,7 @@ void updateSecretWord(string& secretWord, const char ch, const string& word) void updateEnteredChars(const char ch, string& chars){ // TODO: append the character ch is in end of the text chars chars += ch; + chars += ' '; } /*** @@ -155,14 +162,14 @@ void processData(const char ch, const string& word, else: update incorrectGuess: call updateIncorrectGuess() function update incorrectChars: call updateEnteredChars() function - ***/ - if (isCharInWord(ch, word)){ - updateSecretWord(secretWord, ch, word); - updateEnteredChars(ch, correctChars); - } - else{ - updateIncorrectGuess(incorrectGuess); - updateEnteredChars(ch, incorrectChars); - } -} - + ***/ + if(isCharInWord(ch,word)){ + updateSecretWord(secretWord,ch,word); + updateEnteredChars(ch,correctChars); + } + else { + updateIncorrectGuess(incorrectGuess); + updateEnteredChars(ch,incorrectChars); + } + +} \ No newline at end of file diff --git a/AdvProg_L6-Painter/painter.cpp b/AdvProg_L6-Painter/painter.cpp index 73f88f721..559449740 100644 --- a/AdvProg_L6-Painter/painter.cpp +++ b/AdvProg_L6-Painter/painter.cpp @@ -1,36 +1,37 @@ #include "painter.h" /*** - Args: color (SDL_Color): color value - + Args: color (SDL_Color): color value + Returns: None ***/ -void Painter::setColor(SDL_Color color) -{ +void Painter::setColor(SDL_Color color) +{ // TODO: set the color value for the Painter and set Render Draw Color - this->color = color; - SDL_SetRenderDrawColor(renderer, color.r, color.g, color.b, color.a); + this->color = color; + SDL_SetRenderDrawColor(this->renderer, color.r, color.g, color.b, 0); } /*** Args: numPixel (int): number of pixel for jumping forward - + Returns: None ***/ void Painter::jumpForward(int numPixel) { // TODO: jump the painter forward - x += (int) (cos(angle * M_PI / 180) * numPixel); - y -= (int) (sin(angle * M_PI / 180) * numPixel); + double rad = (angle / 180) * M_PI; + this->x += cos(rad) * numPixel; + this->y -= sin(rad) * numPixel; } /*** Args: numPixel (int): number of pixel for jumping backward - + Returns: None ***/ @@ -43,45 +44,45 @@ void Painter::jumpBackward(int numPixel) /*** Args: degree (double): the value of rotation angle - + Returns: None -***/ +***/ void Painter::turnLeft(double degree) { - // TODO: rotate left the painter - angle += degree; - if (angle >= 360) angle -= 360; - if (angle < 0) angle += 360; + // TODO: rotate left the painter + this->angle += degree; + if(this->angle >= 0) this->angle -= floor(angle / 360) * 360; + else this->angle += ceil(angle / 360) * 360; } /*** Args: degree (double): the value of rotation angle - + Returns: None -***/ +***/ void Painter::turnRight(double degree) { - // TODO: rotate right the painter + // TODO: rotate right the painter turnLeft(-degree); } -/*** - Args: +/*** + Args: None Returns: None ***/ void Painter::randomColor() { - // TODO: set random color - // cast int to Uint8 - uint8_t r = static_cast(rand() % 256); - uint8_t g = static_cast(rand() % 256); - uint8_t b = static_cast(rand() % 256); - SDL_Color newColor = {r, g, b}; + // TODO: set random color + Uint8 r = rand() % 256; + Uint8 g = rand() % 256; + Uint8 b = rand() % 256; + SDL_Color color = {r, g, b}; + setColor(color); } @@ -92,7 +93,7 @@ void Painter::clearWithBgColor(SDL_Color bgColor) { SDL_Color curColor = color; setColor(bgColor); - SDL_RenderClear(renderer); + SDL_RenderClear(renderer); setColor(curColor); } @@ -154,7 +155,7 @@ void Painter::createParallelogram(int size) turnLeft(60); moveForward(size); turnLeft(120); - } + } } @@ -179,5 +180,4 @@ void Painter::moveForward(int numPixel) void Painter::moveBackward(int numPixel) { moveForward(-numPixel); -} - +} \ No newline at end of file diff --git a/AdvProg_L7-Snake/Game.cpp b/AdvProg_L7-Snake/Game.cpp index a0c6c65ed..7c0c7dc8d 100644 --- a/AdvProg_L7-Snake/Game.cpp +++ b/AdvProg_L7-Snake/Game.cpp @@ -13,7 +13,7 @@ using namespace std; // set some attributes as default value // DO NOT CHANGE THIS CONSTRUCTOR Game::Game(int _width, int _height) - : width(_width), height(_height), // play screen + : width(_width), height(_height), // play screen squares(_height, vector(_width, CELL_EMPTY)), // cell coordinates snake(*this, Position(_width/2, _height/2)), // init snake positin in middle of play screen currentDirection(Direction::RIGHT), @@ -31,23 +31,21 @@ Game::~Game() -/*** +/*** * PLEASE UPDATE THIS METHOD - * + * * When snake moves to a position, * if position belongs to BOARD or SNAKE body, status is GAME_OVER * if position is having CHERRY : * - score schoule be increased * - snake should eat cherry * - a new cherry should be randomly added - * otherwise, this position should be assigned as cell of snake + * otherwise, this position should be assigned as cell of snake * * Args: * pos (Position): position where the snake will move - * * Returns: * // none - * ***/ void Game::snakeMoveTo(Position pos) { @@ -57,85 +55,101 @@ void Game::snakeMoveTo(Position pos) { // // // END CODE HERE + if(getCellType(pos) == CELL_OFF_BOARD || getCellType(pos) == CELL_SNAKE){ + status = GAME_OVER; + } + else if(getCellType(pos) == CELL_CHERRY){ + score++; + snake.eatCherry(); + addCherry(); + } + else{ + setCellType(pos,CELL_SNAKE); + } } /*** * PLEASE UPDATE THIS METHOD - * + * * When all snake body leave a cell, set it as CELL_EMPTY * Args: * position (Position): position where snake will leave * Returns: * // none - * + * ***/ -void Game::snakeLeave(Position position) -{ +void Game::snakeLeave(Position position){ // Suggestion: use setCellType() method in Game class // START CODE HERE - // + // // // // END CODE HERE + setCellType(position, CELL_EMPTY); } // DO NOT change this method -void Game::processUserInput(Direction direction) -{ +void Game::processUserInput(Direction direction){ inputQueue.push(direction); } /*** * PLEASE REPLACE LINES MARKED WITH '// YOUR CODE HERE' - * + * * check whether the snake can move to the intended direction with the currect direction. * If current direction is UP or DOWN, the next direction should not be UP or DOWN * if current diection is LEFT or RIGHT, the next direction should not be LEFT or RIGHT - * + * * Args: * current (Direction): current direction of the snake * next (Direction): the intened direction that snake will move * Returns: * bool: whether the snake can ben changed the direction - * + * ***/ bool Game::canChange(Direction current, Direction next) const { - if (current == UP || current == DOWN) - return 0; // YOUR CODE HERE - return 0;// YOUR CODE HERE + if( (current == UP || current == DOWN) && (next == UP || next == DOWN)){ + return false; + } + else if ((current == LEFT || current == RIGHT) && (next == LEFT || next == RIGHT)){ + return false; + } + return true; } /*** * PLEASE REPLACE LINES MARKED WITH '// YOUR CODE HERE' - * - * Iterover the input queue from keyboard. + * + * Iterover the input queue from keyboard. * For each input direction, check whether snake can move or not. * If the snake can move, set currentDiection as this input direction. * Otherwise, go to the next input direction from input queue - * + * * Args: * // none * Returns: * // none - * + * ***/ void Game::nextStep() { while (!inputQueue.empty()) { // get the input direction from input queue - Direction next ; // YOUR CODE HERE + Direction next = inputQueue.front() ; // YOUR CODE HERE // remove the front of input queue + inputQueue.pop(); // YOUR CODE HERE // check if snake can move to the next direction, set current direction as next if (canChange(currentDirection, next)) { // YOUR CODE HERE + currentDirection = next; break; } } @@ -146,14 +160,14 @@ void Game::nextStep() /*** * PLEASE REPLACE LINES MARKED WITH '// YOUR CODE HERE' - * + * * When snake have already eaten a cherry, please add new cherry inside the play screen with random position - * + * * Args: * // none * Returns: * // none - * + * ***/ void Game::addCherry() @@ -162,15 +176,17 @@ void Game::addCherry() // init a random position inside the play screen (width, height) // Suggestion: use rand() function - Position randomPos; // YOUR CODE HERE - - // check if the randomPos is EMPTY + Position randomPos(rand() % width, rand() % height); // YOUR CODE HERE + + // check if the randomPos is EMPTY if (getCellType(randomPos) == CELL_EMPTY) { // assign the cherry position as randomPos, and set randomPos type as CELL_CHERRY // YOUR CODE HERE // YOUR CODE HERE + cherryPosition = randomPos; + setCellType(cherryPosition,CELL_CHERRY); break; } @@ -180,24 +196,27 @@ void Game::addCherry() /*** * PLEASE UPDATE THIS METHOD - * + * * set cell of a position as intended type. - * + * * Args: * pos (Position): a chosen position * cellType (CellType): cell type of pos * Returns: * // none - * + * ***/ -void Game::setCellType(Position pos, CellType cellType) +void Game::setCellType(Position pos, CellType cellType) { // if position is inside the play screen (width, height), set to the cellType. // Otherwise, do nothing // Suggestion: use pos.isInsideBox(...) in Position class // // START CODE HERE - // + if(pos.isInsideBox(0,0,width,height)) + { + squares[pos.y][pos.x] = cellType; + } // END CODE HERE } @@ -233,5 +252,4 @@ int Game::getHeight(){ // DO NOT change this method Snake Game::getSnake(){ return snake; -} - +} \ No newline at end of file diff --git a/AdvProg_L7-Snake/Snake.cpp b/AdvProg_L7-Snake/Snake.cpp index 73fc1fcfd..a01460212 100644 --- a/AdvProg_L7-Snake/Snake.cpp +++ b/AdvProg_L7-Snake/Snake.cpp @@ -8,7 +8,7 @@ Snake::Snake(Game& _game, Position start) : head(new SnakeNode(start)), tail(head), game(_game), cherry(0) { // Using Game.snakeMoveTo method to move Snake to start position; - game.snakeMoveTo(start); + game.snakeMoveTo(start); } // set some attributes as default value @@ -18,7 +18,7 @@ Snake::~Snake() { /* Loop: SnakeNode p = tail; p != nullptr; - + Do: SnakeNode* nextNode = p->next; // delete p; @@ -36,30 +36,33 @@ vector Snake::getPositions() const return res; } -/*** +/*** * PLEASE UPDATE THIS METHOD - * + * * When snake moves to a position, * head->next = ... * head = head->next; * Args: * pos (newPosition): head of snake grow at new position - * + * * Returns: * // none - * + * ***/ void Snake::growAtFront(Position newPosition) { // head of snake grow at new position - + /* YOUR CODE HERE */ + SnakeNode* newHead = new SnakeNode(newPosition); + newHead->next = head; + head = newHead; } -/*** +/*** * PLEASE UPDATE THIS METHOD - * + * * When snake slide to a newPosition, * if tail->next == nullptr: // snake has only one node * // tail->position is assigned by new position. @@ -73,70 +76,77 @@ void Snake::growAtFront(Position newPosition) * head->next = oldTailNode; * Args: * pos (newPosition): head of snake grow at new position - * + * * Returns: * // none - * + * ***/ void Snake::slideTo(Position newPosition) { - if (tail->next == nullptr) { + if (tail->next == nullptr) { // position is assigned by new position. /* YOUR CODE HERE */ + tail->position = newPosition; } else { SnakeNode *oldTailNode = tail; //cut the old tail off the snake /* YOUR CODE HERE */ - + tail = tail->next; + oldTailNode->next = nullptr; + // move it to the head of the snake /* YOUR CODE HERE */ + oldTailNode->position = newPosition; + head->next = oldTailNode; + head = oldTailNode; } } -/*** +/*** * PLEASE UPDATE THIS METHOD - * + * * When snake eat a Cherry, * // if snake eat cherry, number of cherries will increase one * Args: * // none - * + * * Returns: * // none - * + * ***/ void Snake::eatCherry() { /* YOUR CODE HERE */ + cherry++; } -/*** +/*** * PLEASE UPDATE THIS METHOD - * + * * When snake move in a direction, * 1. Create a newPosition and move: * Position newPosition = head->position.move(direction); * 2. Using snakeMoveTo method to update game with newPosition * game.snakeMoveTo(newPosition); - * 3. - * If gameOver, return ; + * 3. + * If gameOver, return ; * return; * elif cherry > 0: * // If cherry > 0, cherry descrease one and growAtFront() with newPosition * Note: Call to funtion growAtFront() * else: - * // SlideTo() newPosition. + * // SlideTo() newPosition. * Note: Call to function SlideTo() * * Args: * pos (newPosition): head of snake grow at new position - * + * * Returns: * // none - * + * ***/ void Snake::move(Direction direction) @@ -144,16 +154,23 @@ void Snake::move(Direction direction) Position newPosition = head->position.move(direction); /* YOUR CODE HERE */ - - // If gameOver, return ; + game.snakeMoveTo(newPosition); + + // If gameOver, return ; /* YOUR CODE HERE */ + if (game.getGameStatus() == GAME_OVER) { + return; + } // If cherry > 0, cherry descrease one and growAtFront() with newPosition if (cherry > 0) { /* YOUR CODE HERE */ + cherry--; + growAtFront(newPosition); } else { game.snakeLeave(tail->position); - /* YOUR CODE HERE */ + /* YOUR CODE HERE */ + slideTo(newPosition); } } @@ -170,4 +187,4 @@ SnakeNode* Snake::getHead(){ // DO NOT CHANGE METHOD SnakeNode* Snake::getTail(){ return tail; -} +} \ No newline at end of file From b29e205841ae616b4d6b8d3749fb9d1edd3bf845 Mon Sep 17 00:00:00 2001 From: Phan Tho Date: Tue, 4 Jun 2024 00:16:10 +0700 Subject: [PATCH 11/11] fix hangman --- AdvProg_L3-HangMan/hangman.cpp | 106 ++++++++++++++++++--------------- 1 file changed, 59 insertions(+), 47 deletions(-) diff --git a/AdvProg_L3-HangMan/hangman.cpp b/AdvProg_L3-HangMan/hangman.cpp index 2f30fc67d..8c67fadd4 100644 --- a/AdvProg_L3-HangMan/hangman.cpp +++ b/AdvProg_L3-HangMan/hangman.cpp @@ -1,11 +1,11 @@ #include #include "hangman.h" +using std::cin; +using std::domain_error; +using std::ifstream; using std::string; using std::vector; -using std::ifstream; -using std::domain_error; -using std::cin; /*** Args: @@ -17,25 +17,26 @@ using std::cin; int generateRandomNumber(const int min, const int max) { // TODO: Return a random integer number between min and max - int r = min + rand() % (max + 1 - min); - return r; + return rand() % (max - min + 1) + min; } -vector readWordListFromFile(const string& filePath) +vector readWordListFromFile(const string &filePath) { vector wordList; string word; - ifstream wordFile (filePath); - if (!wordFile.is_open()) { + ifstream wordFile(filePath); + if (!wordFile.is_open()) + { throw domain_error("Unable to open file"); } - //while ( getline (wordFile, word) ){ // Thong thuong doc tung line. - // Chuong trinh nay cung chay. - while (wordFile >> word) { // Nhung voi chuong trinh nay, doc tung word cung duoc - // Tuc ca 2 cach doc deu chay. + // while ( getline (wordFile, word) ){ // Thong thuong doc tung line. + // Chuong trinh nay cung chay. + while (wordFile >> word) + { // Nhung voi chuong trinh nay, doc tung word cung duoc + // Tuc ca 2 cach doc deu chay. wordList.push_back(word); - //cout << word << '\n'; + // cout << word << '\n'; } wordFile.close(); @@ -49,13 +50,18 @@ vector readWordListFromFile(const string& filePath) Returns: result (bool) : the character ch is in the word or not. ***/ -bool isCharInWord(const char ch, const string& word) +bool isCharInWord(const char ch, const string &word) { // TODO: return true if ch is in word else return false - for(int i = 0; i < word.size(); i++){ - if (ch == word[i]) return true; + for (auto &i : word) + { + if (i == ch) + { + return true; + } } - return true; + + return false; } /*** @@ -65,16 +71,13 @@ bool isCharInWord(const char ch, const string& word) Returns: answer (string) : the lowercase word is in the position index of wordList ***/ -string chooseWordFromList(const vector& wordList, int index) +string chooseWordFromList(const vector &wordList, int index) { // TODO: Return a lowercase word in the index position of the vector wordList. string answer; answer = wordList[index]; - for(int i = 0; i < answer.size(); i++){ - if(answer[i] >= 'A' && answer[i] <= 'Z'){ - answer[i] += 'a' - 'A'; - } - } + std::transform(answer.begin(), answer.end(), answer.begin(), [](char c) + { return tolower(c); }); return answer; } @@ -84,19 +87,19 @@ string chooseWordFromList(const vector& wordList, int index) Returns: secretWord (string): answerWord in hidden form (form of ---) ***/ -string generateHiddenCharacters(string answerWord){ +string generateHiddenCharacters(string answerWord) +{ // TODO: Based on answerWord's length, generate hidden characters in form of "---" string secretWord; - for(int i = 0; i < int(answerWord.length()); i++){ - secretWord += '-'; - } + secretWord.resize(answerWord.size(), '-'); return secretWord; } -char getInputCharacter() { +char getInputCharacter() +{ char ch; cin >> ch; - return tolower(ch); + return tolower(ch); } /*** @@ -107,11 +110,16 @@ char getInputCharacter() { Returns: void ***/ -void updateSecretWord(string& secretWord, const char ch, const string& word) +void updateSecretWord(string &secretWord, const char ch, const string &word) { // TODO: Update the secret word if the character ch is in the answer word. - for (int i = 0; i< secretWord.length(); i++){ - if (ch == word[i]) secretWord[i] = ch; + int n = word.size(); + for (int i = 0; i < n; i++) + { + if (word[i] == ch) + { + secretWord[i] = ch; + } } } @@ -122,7 +130,8 @@ void updateSecretWord(string& secretWord, const char ch, const string& word) Returns: void ***/ -void updateEnteredChars(const char ch, string& chars){ +void updateEnteredChars(const char ch, string &chars) +{ // TODO: append the character ch is in end of the text chars chars += ch; chars += ' '; @@ -134,7 +143,8 @@ void updateEnteredChars(const char ch, string& chars){ Returns: void ***/ -void updateIncorrectGuess(int& incorrectGuess){ +void updateIncorrectGuess(int &incorrectGuess) +{ // TODO: increase the value of incorrectGuess by 1 incorrectGuess++; } @@ -150,10 +160,10 @@ void updateIncorrectGuess(int& incorrectGuess){ Returns: void ***/ -void processData(const char ch, const string& word, - string& secretWord, - string& correctChars, - int& incorrectGuess, string& incorrectChars) +void processData(const char ch, const string &word, + string &secretWord, + string &correctChars, + int &incorrectGuess, string &incorrectChars) { /*** TODO If ch in word: @@ -163,13 +173,15 @@ void processData(const char ch, const string& word, update incorrectGuess: call updateIncorrectGuess() function update incorrectChars: call updateEnteredChars() function ***/ - if(isCharInWord(ch,word)){ - updateSecretWord(secretWord,ch,word); - updateEnteredChars(ch,correctChars); - } - else { - updateIncorrectGuess(incorrectGuess); - updateEnteredChars(ch,incorrectChars); - } - + + if (isCharInWord(ch, word)) + { + updateSecretWord(secretWord, ch, word); + updateEnteredChars(ch, correctChars); + } + else + { + updateIncorrectGuess(incorrectGuess); + updateEnteredChars(ch, incorrectChars); + } } \ No newline at end of file