在 python 程序中使用 类 并递增点数
Using classes in a python program and incrementing points
我需要为 Beginning 创建一个期末项目 Python class 我决定创建一个谜语程序并想简化以下代码,但我不确定如何去做。我想使用 class 来执行此操作,但我无法弄清楚如何更改我的主程序以使用来自 Class 的信息该程序在不使用 Class 的情况下运行良好,但我必须将它用于最终项目。我不确定该怎么做,我尝试了一些事情,比如做一个积分系统(每次获胜增加 5 分)并且认为将 riddles/answers 等变成 [=25= 会很好].我遇到的问题是如何在程序本身中对 self 实例进行编码。我知道要导入 class,但我正在努力 how/what 来更改程序而不搞砸一切。我已经查看了 Stack Overflow 和各种其他互联网资源,并且相信我对 classes、导入和继承有很好的理解,但我似乎找不到任何与我正在尝试做的类似的例子。非常感谢任何帮助。
import riddle_class
banner = "~Riddle Me This~"
print(banner)
print('')
print('Instructions: You have 10 chances to answer each of the following 5 riddles.\
You will receive 5 points for each riddle you answer – up to 25 points.')
points = {'win': 0}
riddle_one = 'What\'s round, but not always around. It is light sometimes and is dark sometimes. Everyone wants to walk all over me. What am I?'
riddle_two = 'What has roots as nobody sees, Is taller than trees, Up, up it goes, And yet never grows?'
riddle_three = 'Voiceless it cries, Wingless flutters, Toothless bites, Mouthless mutters. What am I?'
riddle_four = 'Tear one off and scratch my head; what was once red is black instead.'
riddle_five = 'We\'re five little items of an everyday sort; you\'ll find us all in a tennis court'
riddle_one_answer = 'moon'
riddle_two_answer = 'mountain'
riddle_three_answer = 'wind'
riddle_four_answer = 'match'
riddle_five_answer = 'vowels'
hidden_one = '-' * len(riddle_one_answer)
hidden_two = '-' * len(riddle_two_answer)
hidden_three = '-' * len(riddle_three_answer)
hidden_four = '-' * len(riddle_four_answer)
hidden_five = '-' * len(riddle_five_answer)
guess_one = 0
guess_two = 0
guess_three = 0
guess_four = 0
guess_five = 0
points = 0
score = {'win':0}
print('')
#Riddle One
print('~Riddle Number One!~')
print(riddle_one)
print('')
while guess_one < 11:
print(hidden_one)
user_input = input('Enter one letter at a time (guess #%d): ' % guess_one)
if len(user_input) != 1:
continue
# Count the number of times the character occurs in the word
num_occurrences = riddle_one_answer.count(user_input)
# Replace the appropriate position(s) in hidden_word with the actual character.
position = -1
for occurrence in range(num_occurrences):
position = riddle_one_answer.find(user_input, position+1) # Find the position of the next occurrence
hidden_one = hidden_one[:position] + user_input + hidden_one[position+1:] # Rebuild the hidden word string
if not '-' in hidden_one:
print('')
print('Nice Job!', end=' ')
results = 'win'
break
guess_one += 1
else:
print('Loser!', end=' ')
print('The word was %s' % riddle_one_answer,'\.')
print('______________________________________')
print('')
#Riddle Two
print('')
print('~Riddle Number Two!~')
print(riddle_two)
print('')
while guess_two < 11:
print(hidden_two)
user_input = input('Enter one letter at a time (guess #%d): ' % guess_two)
if len(user_input) != 1:
continue
# Count the number of times the character occurs in the word
num_occurrences = riddle_two_answer.count(user_input)
# Replace the hidden_word with the character.
position = -1
for occurrence in range(num_occurrences):
position = riddle_two_answer.find(user_input, position+1) # Find the position of the next occurrence
hidden_two = hidden_two[:position] + user_input + hidden_two[position+1:] # Rebuild the hidden word string
if not '-' in hidden_two:
print('')
print('WINNER!', end=' ')
results = 'win'
break
guess_two += 1
else:
print('Loser!', end=' ')
print('The word was: %s' % riddle_two_answer,'\.')
print('______________________________________')
print('')
#Riddle Three
print('')
print('~Riddle Number Three!~')
print(riddle_three)
print('')
while guess_three < 11:
print(hidden_three)
user_input = input('Enter one letter at a time (guess #%d): ' % guess_three)
if len(user_input) != 1:
continue
# Count the number of times the character occurs in the word
num_occurrences = riddle_three_answer.count(user_input)
# Replace the appropriate position(s) in hidden_word with the actual character.
position = -1
for occurrence in range(num_occurrences):
position = riddle_three_answer.find(user_input, position+1) # Find the position of the next occurrence
hidden_three = hidden_three[:position] + user_input + hidden_three[position+1:] # Rebuild the hidden word string
if not '-' in hidden_three:
print('')
print('WINNER!', end=' ')
results = 'win'
break
guess_three += 1
else:
print('Loser!', end=' ')
print('The word was %s' % riddle_three_answer,'/.')
print('______________________________________')
print('')
#Riddle Four
print('')
print('~Riddle Number Four!~')
print(riddle_four)
print('')
while guess_four < 11:
print(hidden_four)
user_input = input('Enter one letter at a time (guess #%d): ' % guess_four)
if len(user_input) != 1:
continue
# Count the number of times the character occurs in the word
num_occurrences = riddle_four_answer.count(user_input)
# Replace the appropriate position(s) in hidden_word with the actual character.
position = -1
for occurrence in range(num_occurrences):
position = riddle_four_answer.find(user_input, position+1) # Find the position of the next occurrence
hidden_four = hidden_four[:position] + user_input + hidden_four[position+1:] # Rebuild the hidden word string
if not '-' in hidden_four:
print('')
print('WINNER!', end=' ')
results = 'win'
break
guess_four += 1
else:
print('Loser!', end=' ')
print('The word was %s' % riddle_four_answer,'/.')
print('______________________________________')
print('')
#Riddle Five
print('')
print('~Riddle Number Five!~')
print(riddle_five)
print('')
while guess_five < 11:
print(hidden_five)
user_input = input('Enter one letter at a time (guess #%d): ' % guess_five)
if len(user_input) != 1:
continue
# Count the number of times the character occurs in the word
num_occurrences = riddle_five_answer.count(user_input)
# Replace the appropriate position(s) in hidden_word with the actual character.
position = -1
for occurrence in range(num_occurrences):
position = riddle_five_answer.find(user_input, position+1) # Find the position of the next occurrence
hidden_five = hidden_five[:position] + user_input + hidden_five[position+1:] # Rebuild the hidden word string
if not '-' in hidden_five:
print('')
print('WINNER!', end=' ')
results = 'win'
break
guess_five += 1
else:
print('Loser!', end=' ')
print('The word was %s' % riddle_five_answer,'/.')
print('______________________________________')
print('')
if results == 'win':
score['win'] += 1
total_wins = (score['win'])
points += 5 * total_wins
print('Total points: %d' % points) *#This is only recognizing 1 'win'*
Class
class riddle_me:
def __init__(self, turns, guess):
self.turns = 5
guess = 0
score = {'wins': 0}
def __init__(self):
guess_one = 0
guess_two = 0
guess_three = 0
guess_four = 0
guess_five = 0
更新
谢谢大家的帮助和提问。即使是这些问题也让我更多地思考我的项目。我还没有完成该程序,但我知道它可以工作。我只需要多练习。我一直在不停地学习,但出于某种原因,无论我搜索了多少教程,我都在努力学习这门语言。
我假设您了解 class 是什么,对吧?所以你的问题确实是,"how should I use classes in this program?"
通常,弄清楚程序中需要什么 classes(和对象)的最好方法是坐下来写下您的程序试图做什么的描述,然后挑选出来从那句话。例如:
This riddle game will ask the user a series of questions, and each time compare the user's guess with the correct answer. When the user guesses correctly, the user's points will increase. If the user does not guess correctly after 10 guesses, we will move to the next question. After all the questions have been asked, the game will display the user's points.
好的,所以这仍然很简单。我已经突出显示了一些出现不止一次的词。这些词中的每一个都代表了一个可以有用地制作成class的想法:游戏本身,每个问题,用户的猜猜.
其中一些东西不需要是它们自己的对象,可以是其他对象的属性。例如,请注意我们如何一直引用 "the user's points"。显然 points 数字是 user 对象的一个属性。问题的正确答案应该是该问题的属性。
好的,现在我们有了一些要在我们的程序中使用的 "things",以及我们想了解的关于它们的一些想法:
User:
has points (a number)
Question:
has question text (a string)
has correct answer (a string)
Guess:
has the text of the guess, what the user entered (a string)
is either right or wrong (a boolean)
Game:
has 5 questions
好的,这些开始看起来像 classes 了!我们可以直接将它们翻译成 classes:
class User:
def __init__(self):
self.points = 0 # user starts out with zero points
class Question:
def __init__(self, question_text, correct_answer):
self.question_text = question_text
self.correct_answer = correct_answer
class Guess:
def __init__(self, text, is_correct):
self.text = text
self.is_correct = is_correct
class Game:
def __init__(self, questions):
self.questions = questions
现在我们有了一些对象,但是我们不能对它们做任何有用的事情。现在我们需要决定要添加哪些方法。有不止一种正确的方法可以做到这一点(还有很多微妙的权衡,取决于你或多或少关心哪些事情)。
不过,让我们先确定 我们希望能够做的事情:
- 问一个
Question
,即打印出它的question_text
- 从用户
读入 Guess
- 确定
Guess
是否匹配 Question
的 correct_answer
文本
- 将
points
添加到 User
- 在
Game
中找到下一个Question
,或确定何时没有更多问题
这些我们想做的事情中的每一个都应该是一个方法!现在您正在将您的程序分解成越来越小的部分。继续这样做,直到每个部分应该做什么变得显而易见——然后将每个部分翻译成代码。就是这样!
其中一些东西可能存在于多个地方。需要考虑的一些事情:
- 从用户那里读取
Guess
应该是 Guess
上的方法还是 User
上的方法?任何一个都可以。或者它甚至可以是一个单独的函数(不是 class 的方法)。
- 判断一个
Guess
是否正确的函数应该放在哪里?现在我把它作为 Guess
class 的一个属性,但也许它应该是 Guess
上的一个方法,比如 is_correct_answer_to(question)
接受问题和 returns True
或 False
.
- 我们应该在哪里记录到目前为止对特定问题的猜测次数?它可以在
Question
对象上,也可以在 User
对象上。或者它可能只是像 ask_question(question)
这样的函数中的局部变量,它可以存在于 Question
或 Game
上,或者可能不作为 class 的成员。
这些是您需要做出的决定。但希望这能帮助您入门!
我认为有两个可能的地方可以将 class 放入您的代码中。一个是急需的,另一个不是很需要(但如果你想给程序添加新功能,它可能会派上用场)。
使用 class 的明显地方是封装与单个谜语相关的所有数据和逻辑。 class 的每个实例都将具有问题、答案以及可能会在玩家尝试解决谜语时修改的其他内容的属性(向玩家显示的蒙面解决方案和猜测列表很远,也许)。
像这样:
class Riddle(object):
def __init__(self, question, answer):
self.question = question
self.answer = answer
self.guesses = []
self.update_mask()
def update_mask(self):
self.masked_answer = "".join(c if c in self.guesses else "-"
for c in self.answer)
def guess(self, letter):
# perhaps do some sanity checking here, for invalid or duplicated letters
self.guesses.append(letter)
self.update_mask()
# return number of letters just matched, number yet to be guessed
return self.answer.count(letter), self.masked_answer.count("-")
您可能会使用 class 的另一个地方是封装游戏逻辑(例如,用户进行了多少次猜测,他们如何得分)和状态(例如,玩家的得分和列表Riddle
s 问)。这会让您以各种方式调整您的程序,例如让玩家在完成第一个 运行.
后再次玩
但是,我不认为为此使用 class 几乎和谜语一样重要。大部分好处只是来自将游戏逻辑收集到函数中,而不是一遍又一遍地重复它。创建一个 ask_riddle
函数来处理一个谜语和 return 玩家获得的分数,您的代码将变得更加清晰。如果你想让它成为 Game
class 的方法,并用分数更新实例,那也可以。 Python 不要求您编写面向对象的代码(尽管这样做确实很容易),因此您不需要将 classes 插入不需要的地方。
我需要为 Beginning 创建一个期末项目 Python class 我决定创建一个谜语程序并想简化以下代码,但我不确定如何去做。我想使用 class 来执行此操作,但我无法弄清楚如何更改我的主程序以使用来自 Class 的信息该程序在不使用 Class 的情况下运行良好,但我必须将它用于最终项目。我不确定该怎么做,我尝试了一些事情,比如做一个积分系统(每次获胜增加 5 分)并且认为将 riddles/answers 等变成 [=25= 会很好].我遇到的问题是如何在程序本身中对 self 实例进行编码。我知道要导入 class,但我正在努力 how/what 来更改程序而不搞砸一切。我已经查看了 Stack Overflow 和各种其他互联网资源,并且相信我对 classes、导入和继承有很好的理解,但我似乎找不到任何与我正在尝试做的类似的例子。非常感谢任何帮助。
import riddle_class
banner = "~Riddle Me This~"
print(banner)
print('')
print('Instructions: You have 10 chances to answer each of the following 5 riddles.\
You will receive 5 points for each riddle you answer – up to 25 points.')
points = {'win': 0}
riddle_one = 'What\'s round, but not always around. It is light sometimes and is dark sometimes. Everyone wants to walk all over me. What am I?'
riddle_two = 'What has roots as nobody sees, Is taller than trees, Up, up it goes, And yet never grows?'
riddle_three = 'Voiceless it cries, Wingless flutters, Toothless bites, Mouthless mutters. What am I?'
riddle_four = 'Tear one off and scratch my head; what was once red is black instead.'
riddle_five = 'We\'re five little items of an everyday sort; you\'ll find us all in a tennis court'
riddle_one_answer = 'moon'
riddle_two_answer = 'mountain'
riddle_three_answer = 'wind'
riddle_four_answer = 'match'
riddle_five_answer = 'vowels'
hidden_one = '-' * len(riddle_one_answer)
hidden_two = '-' * len(riddle_two_answer)
hidden_three = '-' * len(riddle_three_answer)
hidden_four = '-' * len(riddle_four_answer)
hidden_five = '-' * len(riddle_five_answer)
guess_one = 0
guess_two = 0
guess_three = 0
guess_four = 0
guess_five = 0
points = 0
score = {'win':0}
print('')
#Riddle One
print('~Riddle Number One!~')
print(riddle_one)
print('')
while guess_one < 11:
print(hidden_one)
user_input = input('Enter one letter at a time (guess #%d): ' % guess_one)
if len(user_input) != 1:
continue
# Count the number of times the character occurs in the word
num_occurrences = riddle_one_answer.count(user_input)
# Replace the appropriate position(s) in hidden_word with the actual character.
position = -1
for occurrence in range(num_occurrences):
position = riddle_one_answer.find(user_input, position+1) # Find the position of the next occurrence
hidden_one = hidden_one[:position] + user_input + hidden_one[position+1:] # Rebuild the hidden word string
if not '-' in hidden_one:
print('')
print('Nice Job!', end=' ')
results = 'win'
break
guess_one += 1
else:
print('Loser!', end=' ')
print('The word was %s' % riddle_one_answer,'\.')
print('______________________________________')
print('')
#Riddle Two
print('')
print('~Riddle Number Two!~')
print(riddle_two)
print('')
while guess_two < 11:
print(hidden_two)
user_input = input('Enter one letter at a time (guess #%d): ' % guess_two)
if len(user_input) != 1:
continue
# Count the number of times the character occurs in the word
num_occurrences = riddle_two_answer.count(user_input)
# Replace the hidden_word with the character.
position = -1
for occurrence in range(num_occurrences):
position = riddle_two_answer.find(user_input, position+1) # Find the position of the next occurrence
hidden_two = hidden_two[:position] + user_input + hidden_two[position+1:] # Rebuild the hidden word string
if not '-' in hidden_two:
print('')
print('WINNER!', end=' ')
results = 'win'
break
guess_two += 1
else:
print('Loser!', end=' ')
print('The word was: %s' % riddle_two_answer,'\.')
print('______________________________________')
print('')
#Riddle Three
print('')
print('~Riddle Number Three!~')
print(riddle_three)
print('')
while guess_three < 11:
print(hidden_three)
user_input = input('Enter one letter at a time (guess #%d): ' % guess_three)
if len(user_input) != 1:
continue
# Count the number of times the character occurs in the word
num_occurrences = riddle_three_answer.count(user_input)
# Replace the appropriate position(s) in hidden_word with the actual character.
position = -1
for occurrence in range(num_occurrences):
position = riddle_three_answer.find(user_input, position+1) # Find the position of the next occurrence
hidden_three = hidden_three[:position] + user_input + hidden_three[position+1:] # Rebuild the hidden word string
if not '-' in hidden_three:
print('')
print('WINNER!', end=' ')
results = 'win'
break
guess_three += 1
else:
print('Loser!', end=' ')
print('The word was %s' % riddle_three_answer,'/.')
print('______________________________________')
print('')
#Riddle Four
print('')
print('~Riddle Number Four!~')
print(riddle_four)
print('')
while guess_four < 11:
print(hidden_four)
user_input = input('Enter one letter at a time (guess #%d): ' % guess_four)
if len(user_input) != 1:
continue
# Count the number of times the character occurs in the word
num_occurrences = riddle_four_answer.count(user_input)
# Replace the appropriate position(s) in hidden_word with the actual character.
position = -1
for occurrence in range(num_occurrences):
position = riddle_four_answer.find(user_input, position+1) # Find the position of the next occurrence
hidden_four = hidden_four[:position] + user_input + hidden_four[position+1:] # Rebuild the hidden word string
if not '-' in hidden_four:
print('')
print('WINNER!', end=' ')
results = 'win'
break
guess_four += 1
else:
print('Loser!', end=' ')
print('The word was %s' % riddle_four_answer,'/.')
print('______________________________________')
print('')
#Riddle Five
print('')
print('~Riddle Number Five!~')
print(riddle_five)
print('')
while guess_five < 11:
print(hidden_five)
user_input = input('Enter one letter at a time (guess #%d): ' % guess_five)
if len(user_input) != 1:
continue
# Count the number of times the character occurs in the word
num_occurrences = riddle_five_answer.count(user_input)
# Replace the appropriate position(s) in hidden_word with the actual character.
position = -1
for occurrence in range(num_occurrences):
position = riddle_five_answer.find(user_input, position+1) # Find the position of the next occurrence
hidden_five = hidden_five[:position] + user_input + hidden_five[position+1:] # Rebuild the hidden word string
if not '-' in hidden_five:
print('')
print('WINNER!', end=' ')
results = 'win'
break
guess_five += 1
else:
print('Loser!', end=' ')
print('The word was %s' % riddle_five_answer,'/.')
print('______________________________________')
print('')
if results == 'win':
score['win'] += 1
total_wins = (score['win'])
points += 5 * total_wins
print('Total points: %d' % points) *#This is only recognizing 1 'win'*
Class
class riddle_me:
def __init__(self, turns, guess):
self.turns = 5
guess = 0
score = {'wins': 0}
def __init__(self):
guess_one = 0
guess_two = 0
guess_three = 0
guess_four = 0
guess_five = 0
更新 谢谢大家的帮助和提问。即使是这些问题也让我更多地思考我的项目。我还没有完成该程序,但我知道它可以工作。我只需要多练习。我一直在不停地学习,但出于某种原因,无论我搜索了多少教程,我都在努力学习这门语言。
我假设您了解 class 是什么,对吧?所以你的问题确实是,"how should I use classes in this program?"
通常,弄清楚程序中需要什么 classes(和对象)的最好方法是坐下来写下您的程序试图做什么的描述,然后挑选出来从那句话。例如:
This riddle game will ask the user a series of questions, and each time compare the user's guess with the correct answer. When the user guesses correctly, the user's points will increase. If the user does not guess correctly after 10 guesses, we will move to the next question. After all the questions have been asked, the game will display the user's points.
好的,所以这仍然很简单。我已经突出显示了一些出现不止一次的词。这些词中的每一个都代表了一个可以有用地制作成class的想法:游戏本身,每个问题,用户的猜猜.
其中一些东西不需要是它们自己的对象,可以是其他对象的属性。例如,请注意我们如何一直引用 "the user's points"。显然 points 数字是 user 对象的一个属性。问题的正确答案应该是该问题的属性。
好的,现在我们有了一些要在我们的程序中使用的 "things",以及我们想了解的关于它们的一些想法:
User:
has points (a number)
Question:
has question text (a string)
has correct answer (a string)
Guess:
has the text of the guess, what the user entered (a string)
is either right or wrong (a boolean)
Game:
has 5 questions
好的,这些开始看起来像 classes 了!我们可以直接将它们翻译成 classes:
class User:
def __init__(self):
self.points = 0 # user starts out with zero points
class Question:
def __init__(self, question_text, correct_answer):
self.question_text = question_text
self.correct_answer = correct_answer
class Guess:
def __init__(self, text, is_correct):
self.text = text
self.is_correct = is_correct
class Game:
def __init__(self, questions):
self.questions = questions
现在我们有了一些对象,但是我们不能对它们做任何有用的事情。现在我们需要决定要添加哪些方法。有不止一种正确的方法可以做到这一点(还有很多微妙的权衡,取决于你或多或少关心哪些事情)。
不过,让我们先确定 我们希望能够做的事情:
- 问一个
Question
,即打印出它的question_text
- 从用户 读入
- 确定
Guess
是否匹配Question
的correct_answer
文本 - 将
points
添加到User
- 在
Game
中找到下一个Question
,或确定何时没有更多问题
Guess
这些我们想做的事情中的每一个都应该是一个方法!现在您正在将您的程序分解成越来越小的部分。继续这样做,直到每个部分应该做什么变得显而易见——然后将每个部分翻译成代码。就是这样!
其中一些东西可能存在于多个地方。需要考虑的一些事情:
- 从用户那里读取
Guess
应该是Guess
上的方法还是User
上的方法?任何一个都可以。或者它甚至可以是一个单独的函数(不是 class 的方法)。 - 判断一个
Guess
是否正确的函数应该放在哪里?现在我把它作为Guess
class 的一个属性,但也许它应该是Guess
上的一个方法,比如is_correct_answer_to(question)
接受问题和 returnsTrue
或False
. - 我们应该在哪里记录到目前为止对特定问题的猜测次数?它可以在
Question
对象上,也可以在User
对象上。或者它可能只是像ask_question(question)
这样的函数中的局部变量,它可以存在于Question
或Game
上,或者可能不作为 class 的成员。
这些是您需要做出的决定。但希望这能帮助您入门!
我认为有两个可能的地方可以将 class 放入您的代码中。一个是急需的,另一个不是很需要(但如果你想给程序添加新功能,它可能会派上用场)。
使用 class 的明显地方是封装与单个谜语相关的所有数据和逻辑。 class 的每个实例都将具有问题、答案以及可能会在玩家尝试解决谜语时修改的其他内容的属性(向玩家显示的蒙面解决方案和猜测列表很远,也许)。
像这样:
class Riddle(object):
def __init__(self, question, answer):
self.question = question
self.answer = answer
self.guesses = []
self.update_mask()
def update_mask(self):
self.masked_answer = "".join(c if c in self.guesses else "-"
for c in self.answer)
def guess(self, letter):
# perhaps do some sanity checking here, for invalid or duplicated letters
self.guesses.append(letter)
self.update_mask()
# return number of letters just matched, number yet to be guessed
return self.answer.count(letter), self.masked_answer.count("-")
您可能会使用 class 的另一个地方是封装游戏逻辑(例如,用户进行了多少次猜测,他们如何得分)和状态(例如,玩家的得分和列表Riddle
s 问)。这会让您以各种方式调整您的程序,例如让玩家在完成第一个 运行.
但是,我不认为为此使用 class 几乎和谜语一样重要。大部分好处只是来自将游戏逻辑收集到函数中,而不是一遍又一遍地重复它。创建一个 ask_riddle
函数来处理一个谜语和 return 玩家获得的分数,您的代码将变得更加清晰。如果你想让它成为 Game
class 的方法,并用分数更新实例,那也可以。 Python 不要求您编写面向对象的代码(尽管这样做确实很容易),因此您不需要将 classes 插入不需要的地方。