I am new to python and want to write a simple text adventure game. The player enters a tavern and interacts with the guests. The game takes place in a fantasy setting, where there are multiple races. I want to randomly generate each guest and then interact with them in the tavern. Here is my simplified code:
import random
class guest:
def __init__(self,race,name,fav_food):
self.race = race
self.name = name
self.fav_food = fav_food
guest1 = guest('human','Tom','chicken')
print('The first guest you meet is a '+guest1.race+ ' named '+guest1.name+ '. He really likes '+guest.fav_food+ '.')
So far so good. But here i get stuck: I want the set of data for guest1 to be randomly selected from other guests that i create beforehand.
guest1 = guest('human','Tom','chicken')
guest1 = guest('dwarf','Bjorn','potatoes')
guest1 = guest('orc','Orok','pork')
guest1 = guest('elf',,'Eli','Salad')
How do i do that? Sure, i could name them guest2,guest3 etc., but then it wouldnยดt be random anymore.
When i run the code, i want to randomly encounter Tom,Bjorn,Orok or Eli
I would really appreciate any help on this matter.
Sorry for my bad english :)
You can put all of your guests into an array and use random.choice to set random guest to a variable called random_guest.
guests = [guest('human', 'Tom', 'chicken'),
guest('dwarf', 'Bjorn', 'potatoes'),
guest('orc', 'Orok', 'pork'),
guest('elf', 'Eli', 'Salad')]
random_guest = random.choice(guests)
print('The first guest you meet is a '+ random_guest.race + ' named '+ random_guest.name + '. He really likes '+ random_guest.fav_food + '.')
It's perfectly fine to use random.choice to select one character from a list of characters but sometimes random.choice is not what you want.
I mean, no problem if your game is conversational: you meet George, move on to Rita and next it's George again...
But, if your game implies that you KILL George (or George kills you... Game Over) then you KILL Rita, well it would be strange (unless your game is titled Zombie34 โ the Tavern Massacre) if George comes back to harass you.
If your use case is the second one, I'd suggest using a combination of random.shuffle
characters = [...]
random.shuffle(characters)
and the .pop method of a list
# whenever you need a new character
try:
a_character = characters.pop()
except IndexError:
# if you are here, you have exausted your list of characters,
# you could consider generating a new list and possibly starting a new level
Related
I want to create a game where a person is drawn out randomly.
Can some1 check the code if everything is setup correctly.
I have tested the code numerous times and its ok in my eyes.
But when I send the code to a review, to an online class I only get 50% score.
import random
# ๐จ Don't change the code below ๐
test_seed = int(input("Create a seed number: "))
random.seed(test_seed)
# Split string method
names_string = input("Give me everybody's names, separated by a comma. ")
names = names_string.split(", ")
# ๐จ Don't change the code above ๐
#Write your code below this line ๐
print(names)
names_count = len(names)
random_name_number = random.randint(0, names_count)
print(f"{names[random_name_number]} is going to buy the meal today!")
The problem here is almost certainly with randint. Unlike most Python conventions, the parameters to randint are inclusive. That means, if you supply (0,10), you are going to get numbers from 0 to 10. In your case, if they supply 10 names, using index 10 is going to cause an exception.
You want random.randrange, not random.randint. randrange(0,10) will supply numbers from 0 to 9.
I am doing a project in school which is asking me to make a music quiz in python that reads a file, displays the first letters of each word of the song and the artist (e.g Dave F F). In my file I have a list of 10 song names where python fetches a random line and does the displaying. It must be from a file (mine is notepad) The user must have 2 chances to guess the name of the song, and if they don't then the game ends. The problem that I have is I cannot get my code to ask another question, and store the last one asked so that it doesn't ask it again (e.g if the first question is Dave and F F, I want it to not come again). I would also appreciate it if I was shown how to get python to display a leaderboard. Could answers please be the full code with improvements as i'm not good with indents and putting code In the right place.
I have already gave the user 2 chances to get the song right, and If they dont then the program ends, but doesn't loop to the start.
import random
with open("songlist.txt", "r") as songs_file:
with open("artistlist.txt", "r") as artists_file:
songs_and_artists = [(song.rstrip('\n'), artist.rstrip('\n'))
for (song, artist) in zip(songs_file, artists_file)]
random_song, random_artist = random.choice(songs_and_artists)
songs_intials = "".join(item[0].upper() for item in random_song.split())
print("The songs' initials are", songs_intials, "and the name of the artist is", random_artist)
nb_tries_left = 3
guess = input("Guess the name of the song! ")
nb_tries_left -= 1
finished = False
while not finished:
answer_found = (guess == random_song)
if not answer_found:
guess = input("Nope! Try again! ")
nb_tries_left -= 1
elif answer_found:
print("The songs' initials are", songs_intials, "and the name of the artist is", random_artist)
finished = (answer_found or nb_tries_left <= 0)
if answer_found:
The songs' initials are LT and the name of the artist is Fredo
Guess the name of the song! Like That
The songs' initials are LT and the name of the artist is Fredo
Well done!
Python then doesn't ask another question, and I don't know If it will be that one again.
getting it wrong on purpose outputs this:
The songs' initials are CS and the name of the artist is 50 Cent
Guess the name of the song! candysong
Nope! Try again! carpetshop
Nope! Try again! coolsong
Sorry, you've had two chances. Come back soon!
>>>
First You want to get 2 unique songs. To do that you could use random.sample. For your use case, It is
indexes = random.sample(range(len(songs_and_artists)), 2) # 2 random songs (sampling without replacement)
# song 1
random_song, random_artist = songs_and_artists[indexes[0]]
# song 2
random_song, random_artist = songs_and_artists[indexes[1]]
Additionally, I recommend you to put your code to the function and use it with each selected song.
In order to ask more than one question every game you have to do something like this:
with open("songlist.txt", "r") as songs_file:
with open("artistlist.txt", "r") as artists_file:
songs_and_artists = [(song.rstrip('\n'), artist.rstrip('\n'))
for (song, artist) in zip(songs_file, artists_file)]
def getSongAndArtist():
randomIndex = random.randrange(0, len(songs_and_artists))
return songs_and_artists.pop(randomIndex)
while(len(songs_and_artists) > 0):
random_song, random_artist = getSongAndArtist()
#play game with the song
You save the list of songs in a python list and pop a random one out each round as long as you have more songs to play with.
For the leaderboard you have to ask for a user name before you start the game and save a list of usernames and their score and then pick the top ones. you should also figure out how to score the users
I've been trying to make a basic text game in Python, and I'm using dictionaries to contain the player's information. I want to make it so that when a player's health reaches 0, the code will stop running. I've had trouble making that happen. My dictionary, which is at the beginning of my code, looks like this:
playerAtt = {}
playerAtt["Weapon"] = "Baseball bat"
playerAtt["Party"] = "Empty"
playerAtt["Health"] = 15
playerAtt["Cash"] = "$100"
print(playerAtt)
if playerAtt['Health'] <= 0:
exit()
The bottom section is what I wrote to try and make the code stop running when the player's health reached zero, but it doesn't seem to work. In one path of my game, your health gets set to zero and the game is supposed to end, but the program continues to run:
townChoice = raw_input("You met a traveler in the town. 'Yo. I'm Bob. Let's be friends.' Will you invite him to your party? Y/N\n")
if townChoice == 'y' or townChoice == 'Y':
print("That kind traveler was not such a kind traveler. He stabbed you with a machete. RIP " + Name + '.')
playerAtt['Health'] == 0
When you reach this part of the game, all it does is print the message, and moves on to the next decision. In this situation, I could just manually end the program by doing exit() under the print command, but there are circumstances where the player only loses a fraction of their health, and they would eventually reach zero. Sorry if this is a stupid question, I've only been working on Python for a few days.
You have two "=" when you set the player's health to 0
I had put 2 == instead of 1 = when defining
playerAtt["Health"].
Also, I needed to make sure it was constantly checking if the player's health was zero, so I used a while loop. I used
while playerAtt["Health"] = 0:
deathmsg()
exit()
to fix it. deathMsg was a function I made to display a random death message, for more information.
How to print different items depending on a random print in Python? Here is part of my script.
Mage = "Mage"
Warrior = "Warrior"
Thief = "Thief"
skilltree = (Mage, Warrior, Thief)
print random.choice (skilltree)
Now say it randomly chose Warrior. In my next script it would print 7 skills. But if it were to randomly choose Thief or Mage they would of been 7 completely different skills. So I want the 7 skills you get to depend on the randomly chosen skill tree.
You have done the hard part. Now you just need to map the skills to each category. For instance, using a dictionary:
skills = {'Mage': range(7), 'Warrior': range(7,14), 'Thief': range(14,21)}
choice = random.choice(skilltree)
print skills[choice]
This will print the list of skills you associated with the chosen skilltree. I used range just to illustrate, you could have a list of strings with the skills.
I will just illustrate a little bit further with Paulo's example in case you are not familiar with using a dictionary (and like he said using a dictionary is probably the best choice for a mapping).
MageSkills = ["Mskill1", "Mskill2"]
ThiefSkills = ["Tskill1", "Tskill2"]
WarriorSkills = ["Wskill1", "Wskill2"]
skills = {'Warrior': WarriorSkills, 'Mage': MageSkills, 'Thief': ThiefSkills}
choice = 'Warrior'
print(skills[choice])
The general concept of a solution has been outlined by others, but I think they're missing the key misunderstanding behind your question, which is how to persist something that you randomly chose and printed. As far as that goes, and for understanding this is what I would do:
import random
classes = ("Mage", "Warrior", "Thief")
skill_dictionary = {"Mage": ["Fireball", "Ice Blast"...], "Warrior": [...]} # etc
random_class = random.choice(classes) # Keep a version around for yourself
print random_class # print the version you just saved so you still have a copy
print skill_dictionary[random_class] #Then use the saved version to get the skill list
An important thought distinction to have here is separating getting the data from displaying it. First you randomly choose the data, and only after you already have it do you decide to show it to the user with your print statement.
The dictionary is just a key/value store (something that maps keys(your classes) to values (your skills)). It happens to fit this problem well, but you could implement this in other ways.
Hi I'm just starting to learn Python, I'm using the book "learn python the hard way" and one of the exercises is to build a simple game. I wanted to give options to the user from a list.
For example I would make a list called animals which would include 3 animals, lion tiger and fish. is is possible to offer selected elements from a list. I'm pretty sure it is but I just don't know how.
I was thinking something like this (obviously wrong but I think it helps to understand what I mean)
animals = ['Lion', 'Tiger', 'Fish']
print "which of these animals is your favourite?"
favourite = raw_input(animals[0] or animals[2])
if favourite = "Lion':
print "Nice choice"
else:
print "Bad choice"
Again I can't stress enough I know the above is really crap but essentially I want to offer certain items of a list as an option for the raw_input. In the above case the 0 item and the 2 item.
Thanks in advance for the help.
favourite = raw_input(' or '.join(animals))
This will take all the strings from the list animals and join them together with or in between, so you'll end up with
Lion or Tiger or Fish
if you want to add a question mark and space to the end, you can do
favourite = raw_input(' or '.join(animals) + '? ')
Also, on the line
if favourite = "Lion':
Your quotes don't match -- make sure to use either double or single quotes, not one of each. You also need to use == to compare two things; = is for assigning a value, not comparing.
I would probably do it like
animal_string = ' or '.join(animals)
favourite = raw_input("Which of these animals is your favourite:\n{}? ".format(animal_string))
Which first makes the animal string, then formats the choices into the question on a new line (because of the \n), and puts ? after.
How about this?
favourite = raw_input("which of these animals is your favourite? "+",".join([str(a)+":"+b for a,b in enumerate(animals)])+">")
fav = animals[int(favourite)]
print fav+" is a nice choice indeed!. The big bear will kill you anyway. Good bye."