C++ Sorry棋盘游戏:自动循环与重复骰子值问题修复求助
Hey there! Let's tackle those two issues you're facing, plus a few other bugs I spotted in your code to make it work properly.
Issue 1: Adding "Press Enter to Roll the Dice" Interaction
Right now your code rolls automatically without waiting for user input. To fix this, we'll add a prompt that waits for the player to press Enter before rolling. We need to handle leftover newline characters from previous cin inputs first with cin.ignore(), then use cin.get() to wait for the Enter key.
Issue 2: Dice Rolling Repeating the Same Value
The problem here is that you're calling srand(time(NULL)) every time you generate a random number. Since time(NULL) returns the current time in seconds, if you roll multiple times within the same second, the random seed gets reset to the same value, leading to identical numbers. We should only initialize the random seed once at the start of the program.
Bonus: Fixing Other Bugs in Your Code
I also noticed a few other issues that would break your game:
- In cases 4, 5, 6, you were modifying the
playerPospointer directly instead of the specific player's position (playerPos[j]). - Case 7's swap logic was incorrect—it was overwriting the player's position multiple times instead of swapping with the leading player once.
- Case 11 had a similar logic issue with swapping with the trailing player.
- The empty
switch(RandomNumber())at the start ofmain()was useless and has been removed. - The player count validation condition used
&&instead of||(a number can't be both less than 2 and greater than 4 at the same time!).
Fixed Full Code
#include <iostream> #include <string> #include <ctime> #include <iomanip> #include <limits> // For handling input buffer cleanup using namespace std; int RandomNumber() { // Just generate the number—seed is initialized once in main return rand() % 11 + 2; // Generates numbers 2-12 } bool CheckWinner(int pos) { return (pos == 50); } int main() { // Initialize random seed ONCE at the start of the program srand(time(NULL)); int NumOfPlayer; cout << "Enter Number of Players (2-4): "; cin >> NumOfPlayer; // Fix validation condition to use OR instead of AND while (NumOfPlayer < 2 || NumOfPlayer > 4) { cout << "Please insert a number of players between 2 and 4: "; cin >> NumOfPlayer; } int* playerPos = new int[NumOfPlayer]; for (int i = 0; i < NumOfPlayer; i++) { playerPos[i] = 0; } bool win = false; int winner; while (!win) { for (int j = 0; j < NumOfPlayer; j++) { cout << "\nPlayer " << j + 1 << "'s turn!" << endl; cout << "Press Enter to roll the dice..."; // Clean up leftover input and wait for Enter press cin.ignore(numeric_limits<streamsize>::max(), '\n'); cin.get(); int num = RandomNumber(); cout << "You rolled: " << num << endl; switch (num) { case 2: if (playerPos[j] + 2 <= 50) playerPos[j] += 2; if (CheckWinner(playerPos[j])) { win = true; winner = j + 1; } break; case 3: if (playerPos[j] + 3 <= 50) playerPos[j] += 3; if (CheckWinner(playerPos[j])) { win = true; winner = j + 1; } break; case 4: // Move back 1 space (fixed pointer access) if (playerPos[j] - 1 >= 0) playerPos[j] -= 1; if (CheckWinner(playerPos[j])) { win = true; winner = j + 1; } break; case 5: if (playerPos[j] + 5 <= 50) playerPos[j] += 5; // Fixed pointer access if (CheckWinner(playerPos[j])) { win = true; winner = j + 1; } break; case 6: if (playerPos[j] + 6 <= 50) playerPos[j] += 6; // Fixed pointer access if (CheckWinner(playerPos[j])) { win = true; winner = j + 1; } break; case 7: { // Find the leading player (highest position) int leadPlayer = j; for (int k = 0; k < NumOfPlayer; k++) { if (k != j && playerPos[k] > playerPos[leadPlayer]) { leadPlayer = k; } } // Swap positions with the lead player if (leadPlayer != j) { swap(playerPos[j], playerPos[leadPlayer]); cout << "You swapped positions with Player " << leadPlayer + 1 << " (the leader)!" << endl; } else { cout << "You're already the leader—no swap needed!" << endl; } if (CheckWinner(playerPos[j])) { win = true; winner = j + 1; } break; } case 8: if (playerPos[j] + 8 <= 50) playerPos[j] += 8; if (CheckWinner(playerPos[j])) { win = true; winner = j + 1; } break; case 9: if (playerPos[j] + 9 <= 50) playerPos[j] += 9; if (CheckWinner(playerPos[j])) { win = true; winner = j + 1; } break; case 10: if (playerPos[j] + 10 <= 50) playerPos[j] += 10; if (CheckWinner(playerPos[j])) { win = true; winner = j + 1; } break; case 11: { // Find the trailing player (lowest position) int trailPlayer = j; for (int k = 0; k < NumOfPlayer; k++) { if (k != j && playerPos[k] < playerPos[trailPlayer]) { trailPlayer = k; } } // Swap positions with the trailing player if (trailPlayer != j) { swap(playerPos[j], playerPos[trailPlayer]); cout << "You swapped positions with Player " << trailPlayer + 1 << " (the trail)!" << endl; } else { cout << "You're already trailing—no swap needed!" << endl; } if (CheckWinner(playerPos[j])) { win = true; winner = j + 1; } break; } case 12: playerPos[j] = 0; cout << "Oh no! You're sent back to the start!" << endl; if (CheckWinner(playerPos[j])) { win = true; winner = j + 1; } break; default: cout << "Invalid roll? That shouldn't happen!" << endl; break; } // Show current position after each turn for clarity cout << "Your current position: " << playerPos[j] << endl; // Exit player loop early if someone wins if (win) break; } } cout << "\nCongratulations! Winner is Player: " << winner << endl; // Clean up dynamically allocated memory to avoid leaks delete[] playerPos; return 0; }
Key Changes Explained
- Random Seed Fix: Moved
srand(time(NULL))to the start ofmain()so it's only called once, ensuring proper random number generation. - Enter Key Interaction: Added
cin.ignore()andcin.get()to pause the game until the player presses Enter to roll. - Fixed Array Access: Corrected all instances where
playerPoswas modified directly instead of targeting the specific player's index. - Improved Swap Logic: Rewrote cases 7 and 11 to properly identify the lead/trail player and swap positions only once.
- Validation Fix: Corrected the player count loop condition to use
||instead of&&. - Memory Cleanup: Added
delete[] playerPosto free dynamically allocated memory.
内容的提问来源于stack exchange,提问作者Cyson




