用面向对象的方法设计一个电脑与人玩石头,剪刀,布的游戏,要求将数据成员设计为私有访问属性,同时需要提供构造函数来初始化成员;
时间: 2024-02-19 08:57:31 浏览: 79
好的,我可以为您提供代码示例,如下所示:
```python
import random
class Game:
def __init__(self):
self.__options = ["rock", "scissors", "paper"]
self.__player_score = 0
self.__computer_score = 0
def print_options(self):
print("Please choose one of the following: ")
print("1. Rock")
print("2. Scissors")
print("3. Paper")
def get_player_choice(self):
choice = int(input("Enter your choice (1-3): "))
return self.__options[choice-1]
def get_computer_choice(self):
choice = random.randint(1, 3)
return self.__options[choice-1]
def determine_winner(self, player_choice, computer_choice):
if player_choice == computer_choice:
print("It's a tie!")
elif player_choice == "rock" and computer_choice == "scissors":
print("You win!")
self.__player_score += 1
elif player_choice == "scissors" and computer_choice == "paper":
print("You win!")
self.__player_score += 1
elif player_choice == "paper" and computer_choice == "rock":
print("You win!")
self.__player_score += 1
else:
print("Computer wins!")
self.__computer_score += 1
def print_scores(self):
print("Player score: ", self.__player_score)
print("Computer score: ", self.__computer_score)
def play_game(self):
print("Welcome to the game!")
while True:
self.print_options()
player_choice = self.get_player_choice()
computer_choice = self.get_computer_choice()
print("You chose: ", player_choice)
print("Computer chose: ", computer_choice)
self.determine_winner(player_choice, computer_choice)
self.print_scores()
play_again = input("Do you want to play again? (Y/N) ")
if play_again.lower() != "y":
break
print("Thanks for playing!")
```
这段代码定义了一个名为Game的类,其中包含了私有访问属性options、player_score和computer_score,以及构造函数__init__()。类还定义了打印选项、获取玩家选择、获取计算机选择、确定获胜者、打印得分和玩游戏等方法。通过调用play_game()方法,用户可以开始玩石头,剪刀,布游戏。
阅读全文
相关推荐














