Since you are relatively new to programming, I'd like to give you an informative example of the game to clarify some concepts.
- String
str
is implemented as sequence in Python (you can think that a string is an array of chars). So it supports indexing s = 'abc'; print(s[1]);
shows b
.
- The standard library
random
includes a bench of functions to carry out randomized operations. As mentioned in the other answers that the function random.choice
randomly pick an element from a sequence. So it can be used to randomly pick a character from a string.
- You mentioned loops and you seem to be able to master them. So I hereby use another approach called recursion to continue the game until the desired answer is found.
- The game is written in an Object-Oriented manner. If you gonna be a developer latter in your career, it's good practice to see this.
Here is the Code:
import random
class Game:
def __init__(self, string):
self.string = string
def start_game(self):
self.answer = random.choice(string)
self.ask_player()
def ask_player(self):
char = input("Just enter your guess: ")
self.cheat(char)
if char == self.answer:
print("Bingo!")
return None
else:
print("You missed, try again! (Or press Ctrl+C to goddamn exit!)")
self.ask_player()
def show_answer(self):
print('The answer iiiis: %s \n' % self.answer)
def cheat(self, user_input):
if user_input == 'GG':
self.show_answer()
if __name__ == '__main__':
string = "This is the string from which the letters are ramdomly chosen!"
gg = Game(string)
gg.start_game()
Some test runs:
Just enter your guess: 2
You missed, try again! (Or press Ctrl+C to goddamn exit!)
Just enter your guess: T
You missed, try again! (Or press Ctrl+C to goddamn exit!)
Just enter your guess: GG (Haha, I left a cheat code in order to get the right anwser!)
The answer iiiis: o
You missed, try again! (Or press Ctrl+C to goddamn exit!)
Just enter your guess: o
Bingo!