我写了一个剧本,让我玩剪刀石头布。我无法上课。为什么?
import random
player_choice = input("Choose rock paper or scissors")
class rock_paper_scissors:
def __init__(self, player_choice, moves, ai_choice):
self.player_choice
self.moves = ["rock", "paper", "scissors"]
ai_choice = random.choice(moves)
for player_choice in rock_paper_scissors:
if player_choice == "rock" and ai_choice == "scissors":
print("You win Rock beat's scissors")
elif ai_choice == "paper":
print("You lose! Paper beats Rock")
if player_choice == "paper" and ai_choice == "rock":
print("You win! Paper beats rock!")
elif ai_choice == "Scissors":
print("You lose! Scissors beats paper!")
if player_choice == scissors and ai_choice == paper:
print("You win")
elif ai_choice == rock:
print("You lose! Rocky beats paper!")
if player_choice == ai_choice:
print("You tied!")
if player_choice == scissors and ai_choice == paper:
print("You win")
elif ai_choice == rock:
print("You lose! Rocky beats paper!")
if player_choice == ai_choice:
print("You tied!")
错误:
NameError:名称'rock_paper_scissors'在main.py的第8行上未定义
我认为,解释需要解决的问题会更有用。
self.player_choice
未定义;ai_choice
给构造函数,然后在内部显式覆盖其值;moves
无论如何,如果要在内部定义构造函数,则无需传递给构造函数。rock_paper_scissors
因为您还没有告诉Python如何迭代一个类。elif
处使用if
,这会造成混淆;scissors
,rock
,paper
被称为变量,而不是用引号括起来,使一个字符串。这些参考文献均未定义。这是应该使用更好的样式进行修复的方法:
import random
class Game(object): # it's considered good practice to inherit from `object`
# this is a constructor where we declare all instance variables
def __init__(self):
# create a dictionary of what defeats what; accessible in all member
# functions - I deliberately chose to do this to reduce the number
# of if statements in your code and improve readability.
self.victory_map = {"rock":"scissors", "paper":"rock", "scissors":"paper"}
# a method to play only a single round
def play(self):
# Here I ask player's input, and make a random choice from only our
# victory_map's keys
player_choice = input("Type 'rock', 'paper' or 'scissors' exactly")
ai_choice = random.choice(self.victory_map.keys())
# handle case where user types in something not in self.moves
while player_choice not in self.victory_map:
print("Type one of 'rock', 'paper' or 'scissors' EXACTLY as written!")
player_choice = input("Type 'rock', 'paper' or 'scissors'")
# This block takes care of the actual victory logic
if self.victory_map[player_choice] == ai_choice:
print("You win!")
elif self.victory_map[ai_choice] == player_choice:
print("You lose")
else:
print("It's a draw.")
if __name__ == '__main__':
new_game = Game()
while True:
# infinite loop, causes you to play indefinitely
new_game.play()
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句