C++实现:
下面是一个简单的C++程序,模拟了取火柴游戏的基本逻辑。这个程序假设只有两堆火柴,并且玩家交替输入他们想拿走的火柴数量。
#include <iostream>
using namespace std;
int main() {
int matches1, matches2;
cout << "Enter the number of matches in pile 1: ";
cin >> matches1;
cout << "Enter the number of matches in pile 2: ";
cin >> matches2;
int currentPlayer = 1; // Player 1 starts first
while (matches1 > 0 || matches2 > 0) {
int pile, numMatches;
cout << "Player " << currentPlayer << "'s turn." << endl;
cout << "Choose a pile (1 or 2): ";
cin >> pile;
if (pile == 1 && matches1 > 0) {
cout << "Enter the number of matches to take (1-3): ";
cin >> numMatches;
if (numMatches >= 1 && numMatches <= 3 && numMatches <= matches1) {
matches1 -= numMatches;
} else {
cout << "Invalid move. Try again." << endl;
continue;
}
} else if (pile == 2 && matches2 > 0) {
cout << "Enter the number of matches to take (1-3): ";
cin >> numMatches;
if (numMatches >= 1 && numMatches <= 3 && numMatches <= matches2) {
matches2 -= numMatches;
} else {
cout << "Invalid move. Try again." << endl;
continue;
}
} else {
cout << "Invalid pile or not enough matches. Try again." << endl;
continue;
}
// Check for win condition
if (matches1 == 0 && matches2 == 0) {
cout << "Player " << currentPlayer << " takes the last match and loses!" << endl;
break;
}
Python实现:
下面是一个简单的Python程序,模拟了取火柴游戏的基本逻辑。这个程序假设只有两堆火柴,并且玩家交替输入他们想拿走的火柴数量。
def main():
matches1 = int(input("Enter the number of matches in pile 1: "))
matches2 = int(input("Enter the number of matches in pile 2: "))
current_player = 1 # Player 1 starts first
while matches1 > 0 or matches2 > 0:
print(f"Player {current_player}'s turn.")
pile = int(input("Choose a pile (1 or 2): "))
num_matches = int(input("Enter the number of matches to take (1-3): "))
if pile == 1 and num_matches >= 1 and num_matches <= 3 and num_matches <= matches1:
matches1 -= num_matches
elif pile == 2 and num_matches >= 1 and num_matches <= 3 and num_matches <= matches2:
matches2 -= num_matches
else:
print("Invalid move. Try again.")
continue
# Check for win condition
if matches1 == 0 and matches2 == 0:
print(f"Player {current_player} takes the last match and loses!")
break
# Switch player
current_player = 2 if current_player == 1 else 1