Using classes in a python program and incrementing points

I need to create a final project for a Beginning Python class and I decided to create a riddle program and want to simplify the following code, but am unsure how to do it. I would like to use a class to do this, but I'm having trouble figuring out how to change my main program to use the information from Class The program runs fine without using Class, but I have to use it for the final project. I am unsure how to do this, I've tried a few things like doing a points system (5 points increment for each win) and thought it would be nice to make the riddles/answers etc. into a class. The problem I'm having is how to code the self instances in the program itself. I know to import the class, but I'm struggling with how/what to change in the program without screwing everything up.. I've looked all over Stack Overflow and a variety of other internet resources, and believe I have a decent understanding of classes, importing and inheritance, but I can't seem to find any examples similar to what I'm trying to do.. Any help is greatly appreciated.

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

UPDATE Thank you all for your help and questions. Even the questions got me thinking more about my project. I still haven't completed the program yet, but I know it could work. I just need to practice more. I've been studying nonstop, but for some reason I'm struggling to learn this language no matter how many tutorials I search.

-------------Problems Reply------------

I'm assuming you understand what a class is, right? So your question really is, "how should I use classes in this program?"

Usually the best way to figure out what classes (and objects) you need in a program is to sit down and write out a description of what your program is trying to do, and then pick out words from that. For example:

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.

OK, so this is still pretty straightforward. I've highlighted some of the words that occur more than once. Each of these words represents an idea that might be usefully made into a class: the game itself, each question, the user's guess.

Some of these things don't need to be their own objects, but can be properties of other objects. For example, notice how we kept referring to "the user's points". Clearly the points number is an attribute of the user object. And the correct answer to a question should be an attribute of that question.

OK, so now we have some "things" we're going to use in our program, and some idea of what we want to know about each of them:

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

OK, these are starting to look like classes! We can translate these into classes pretty directly:

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

Now we have some objects, but we can't do anything useful with them. Now we need to decide what methods to add. There's more than one right way to do this (and a lot of subtle tradeoffs, depending on which things you care more or less about).

Let's start, though, by identifying things we want to be able to do:

  • ask a Question, that is, print out its question_text
  • read in a Guess from the user
  • determine whether a Guess matches a Question's correct_answer text
  • add points to a User
  • find the next Question in a Game, or determine when there are no more questions

Each of these things we want to do should be a method! Now you're breaking down your program into smaller and smaller pieces. Keep doing it until it becomes obvious what each piece should do -- and then translate each piece into code. That's it!

Some of these things could potentially live in multiple places. Some things to think about:

  • Should reading in a Guess from the user be a method on Guess or on User? Either one is OK. Or it could even be a separate function (not a method of a class).
  • Where should the function that determines whether a Guess is correct or not live? Right now I have it as an attribute of the Guess class, but maybe it should be a method on Guess like is_correct_answer_to(question) that takes the question and returns True or False.
  • Where should we keep track of the number of guesses so far for a particular question? It could either be on the Question object, or on the User object. Or it could just be a local variable in a function like ask_question(question) which could live either on Question or maybe on Game, or maybe not as a member of a class.

These are the decisions you need to make. But hopefully this will help you get started!

I think there are two possible places to put a class into your code. One is urgently needed, the other not so much (but it could come in handy if you want to add new features to the program).

The obvious place to use a class is to encapsulate all the data and logic related to a single riddle. Each instance of the class would have attributes for the question, the answer, and perhaps other things that would be modified as the player tries to solve the riddle (the masked solution shown to the player and a list of the guesses so far, perhaps).

Something like this:

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("-")

The other place you might use a class is to encapsulate the game logic (e.g. how many guesses the user gets to make, how they score points) and state (e.g. the player's score and the list of Riddles to ask). This would let you adapt your program in various ways, like letting the player play again after they complete the first run.

However, I don't think that using a class for this is nearly as important as it was for the riddles. Most of the benefits would simply come from gathering the game logic into functions, rather than repeating it over and over. Make an ask_riddle function to handle a single riddle and return the score the player earned and your code will get a whole lot cleaner. If you want to make it a method of the Game class, and update the instance with the score instead, that works too. Python doesn't require you to write object oriented code (though it does make it easy to do so), so you don't need to wedge classes in where they're not needed.

Category:python Views:0 Time:2018-03-12

Related post

Copyright (C) dskims.com, All Rights Reserved.

processed in 0.197 (s). 11 q(s)