How to print different items depending on a random print in Python? - python

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.

Related

Finding a value in a dictionary, not a key

I need the programme to select a random value from the dictionary and ask the user what the key is. The dictionary is a glossary. I want the programme to give the user a definition first.
I propose this:
import numpy as np
dict = {"cat" : "a carnivorous mammal (Felis catus) long domesticated as a pet and for catching rats and mice.",
"dog" : "A domesticated carnivorous mammal (Canis familiaris syn. Canis lupus subsp. familiaris) occurring as a wide variety of breeds, many of which are traditionally used for hunting, herding, drawing sleds, and other tasks, and are kept as pets.",
"butterfly" : "Any of numerous insects of the order Lepidoptera, having four broad, usually colorful wings, and generally distinguished from the moths by having a slender body and knobbed antennae and being active during the day."}
length_dict = len(dict)
list_values = list(dict.values())
list_keys = list(dict.keys())
while True:
r = np.random.randint(length_dict)
print("Define: ")
print(list_values[r])
inp = input()
if inp == list_keys[r]:
print("Correct")
else:
print("Wrong")
You can't. Python doesn't support retrieving keys from a dict by their values, since there's no way to guarantee the values are distinct. However, if you flip them (definition is the key, word is the value) it's much easier to do.
From this answer to a similar question, you can use python's random library, coupled with a bit of data manipulation.
To get a list of the python dictionary's keys, you can use list(yourDict.keys() - then, you can use random.choice() from the random library to get a random key. Finally, you can use this random key as an index to d[] in order to get your result.
import random
d = {'An aquatic animal':'FISH', 'A common pet':'DOG'}
question = random.choice(list(d.keys()))
val = d[question]
print(question)
print(val)
Try it here!
Do note that for the above example, if you really want to store the word as the key, you can set val = random.choice(list(d.keys))) and question = d[val].
Here's what I came up with:
import random
d = {'Key 1':'Value 1', 'Key 2':'Value 2'}
randomKey = random.choice(list(d.keys()))
print(d[randomKey])
A random value is printed. Hope this helps.
Edit:
You copied the code wrong, it should read:
random_key = random.choice(list(glossary))
print('Define: ', glossary[random_key])
input('Press return to see the definition')
print(glossary[random_key])
Make sure you have imported random import random
One way you can approach this is to get a random key from your dictionary first and then simply retrieve the value afterwards. To do this, you can use the random library and then do the following:
import random
glossary = {
"water": "a transparent, odorless, tasteless liquid, a compound of hydrogen and oxygen",
"wind": "air in natural motion",
"fire": "a state, process, or instance of combustion in which fuel or other material is ignited and combined with oxygen"
}
correctAnswers = 0
totalQuestions = len(glossary)
while correctAnswers < totalQuestions:
# Get a random key and value from the glossary dictionary
word = random.choice(list(glossary.keys()))
definition = glossary[word]
# Present the prompt
print("The definition is:", definition)
answer = input("What word is this? ")
# Determine if answer was correct
if answer.lower() == word:
print("Correct!")
correctAnswers += 1
del glossary[word]
else:
print("Incorrect, try again.")
This will output a random definition from within the glossary and will also give the key that it is mapped by. It will then prompt the user to answer what they think the word is. If they are correct, the definition will be removed from the glossary and another question will be asked if one still exists.
Hopefully this gets you started with what you are trying to do.

How to print take something out of a list and store it elsewhere

I am making a music key theory test.
In order to achieve something else that I won't explain right now here (maybe I will later though if this doesn't work), I need to take the root chord out of the list, store it somewhere else, and call back upon it for the user input when they are asked what key the chords come from.
I don't know how to do this, but I am pretty sure it is possible. I would love it if someone could help me. After I have this problem sorted out I will be much further.
Before, I was trying to find someway to have the actual variable represent the variable, while representing what the variable contains. So then after printing the randomized chords from the variable, the user can input the key from which the chords come from, which I have as the variable. But I don't think that will work.
import random
print('Key Theory Werkout')
Dmajor = {'D','E-','F⌗-','G','A','B-','C⌗dim'}
Gmajor = {'G','A-','B-','C','D','E-','F⌗dim'}
Cmajor = {'C','D-','E-','F','G','A-','Bdim'}
Fmajor = {'F','G-','A-','Bb','C','D-','Edim'}
Bbmajor = {'Bb','C-','D-','Eb','F','G-','Adim'}
Ebmajor = {'Eb','F-','G-','Ab','Bb','C-','Ddim'}
Abmajor = {'Ab','Bb-','C-','Db','Eb','F-','Gdim'}
Dbmajor = {'Db','Eb-','F-','Gb','Ab','Bb-','Cdim'}
Cxmajor = {'C⌗','D⌗-','E⌗-','F⌗','G⌗','A⌗-','B⌗dim'}
Gbmajor = {'Gb','Ab-','Bb-','Cb','Db','Eb-','Fdim'}
Fxmajor = {'F⌗','G⌗-','A⌗-','B','C⌗','D⌗-','E⌗dim'}
Bmajor = {'B','C⌗-','D⌗','E','F⌗','G⌗','A⌗dim'}
Cbmajor = {'Cb','Db-','Eb-','Fb','Gb','Ab-','B-dim'}
Emajor = {'E','F⌗-','G⌗-','A','B','C⌗-','D⌗dim'}
Amajor = {'A','B-','C⌗-','D','E','F⌗-','G⌗dim'}
questions = [Dmajor, Gmajor, Cmajor, Fmajor, Bbmajor, Ebmajor,
Abmajor, Dbmajor, Cxmajor, Gbmajor, Fxmajor, Bmajor, Cbmajor,
Emajor, Amajor]
print('Difficulty:Easy, Hard')
begin = input("Choose Difficulty:")
if begin == 'easy':
while begin == "easy":
q = random.choice(questions)
qq = random.sample(list(q), 7)
print(qq)
answer = input('Please Provide the key:')
if answer == q
'''HERE IS THE PROBLEM. Lets say the code outputs F, A-, Bb, C, D-
for Dmajor. How can I have the user type in Dmajor and have it
print correct, or incorrect? I am thinking I will have to put .
entire blocks for each question, and then have the easy choose
random out of all of those questions and that will be how I have to
do it. But maybe there is an easier way.
'''
print("correct")
I would like it to tell the user if they are correct or wrong, while keeping the randomness of questions, and chords it spits out exactly the way it is.
What do I need to do?
Maybe you can try using a dictionary to represent your questions, like this:
questions = {
'Dmajor': {'D','E-','F⌗-','G','A','B-','C⌗dim'},
'Gmajor': {'G','A-','B-','C','D','E-','F⌗dim'},
'Cmajor': {'C','D-','E-','F','G','A-','Bdim'},
'Fmajor': {'F','G-','A-','Bb','C','D-','Edim'},
'Bbmajor': {'Bb','C-','D-','Eb','F','G-','Adim'},
'Ebmajor': {'Eb','F-','G-','Ab','Bb','C-','Ddim'},
'Abmajor': {'Ab','Bb-','C-','Db','Eb','F-','Gdim'},
'Dbmajor': {'Db','Eb-','F-','Gb','Ab','Bb-','Cdim'},
'Cxmajor': {'C⌗','D⌗-','E⌗-','F⌗','G⌗','A⌗-','B⌗dim'},
'Gbmajor': {'Gb','Ab-','Bb-','Cb','Db','Eb-','Fdim'},
'Fxmajor': {'F⌗','G⌗-','A⌗-','B','C⌗','D⌗-','E⌗dim'},
'Bmajor': {'B','C⌗-','D⌗','E','F⌗','G⌗','A⌗dim'},
'Cbmajor': {'Cb','Db-','Eb-','Fb','Gb','Ab-','B-dim'},
'Emajor': {'E','F⌗-','G⌗-','A','B','C⌗-','D⌗dim'},
'Amajor': {'A','B-','C⌗-','D','E','F⌗-','G⌗dim'},
}
Then, you select a random question like this:
key = random.choice(list(questions))
set = questions[key]
sample = random.sample(set, 7)
Now, you only have to check if answer is equal to key.

Using a random instance of a class in a text

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

Python Data Structure Selection

Let's say I have a list of soccer players. For now, I only have four players. [Messi, Iniesta, Xavi, Neymar]. More players will be added later on. I want to keep track of the number of times these soccer players pass to each other during the course of a game. To keep track of the passes, I believe I'll need a data structure similar to this
Messi = {Iniesta: 4, Xavi: 5 , Neymar: 8}
Iniesta = {Messi: 4, Xavi: 10 , Neymar: 5}
Xavi = {Messi: 5, Iniesta: 10 , Neymar: 6}
Neymar = {Messi: 8, Iniesta: 5 , Xavi: 6}
Am I right to use a dictionary? If not, what data structure would be better suited? If yes, how do I approach this using a dictionary though? How do I address the issue of new players being included from time to time, and creating a dictionary for them as well.
As an example, If I get the first element in the list, List(i) in the first iteration is Messi, how do i use the value stored in it to create a dictionary with the name Messi. That is how do i get the line below.
Messi = [Iniesta: 4, Xavi: 5 , Neymar: 8]
It was suggested I try something like this
my_dynamic_vars = dict()
string = 'someString'
my_dynamic_vars.update({string: dict()})
Python and programming newbie here. Learning with experience as I go along. Thanks in advance for any help.
This is a fun question, and perhaps a good situation where something like a graph might be useful. You could implement a graph in python by simply using a dictionary whose keys are the names of the players and whose values are lists players that have been passed the ball.
passes = {
'Messi' : ['Iniesta', 'Xavi','Neymar', 'Xavi', 'Xavi'],
'Iniesta' : ['Messi','Xavi', 'Neymar','Messi', 'Xavi'],
'Xavi' : ['Messi','Neymar','Messi','Neymar'],
'Neymar' : ['Iniesta', 'Xavi','Iniesta', 'Xavi'],
}
To get the number of passes by any one player:
len(passes['Messi'])
To add a new pass to a particular player:
passes['Messi'].append('Xavi')
To count the number of times Messi passed to Xavi
passes['Messi'].count('Xavi')
To add a new player, just add him the first time he makes a pass
passes['Pele'] = ['Messi']
Now, he's also ready to have more passes 'appended' to him
passes['Pele'].append['Xavi']
What's great about this graph-like data structure is that not only do you have the number of passes preserved, but you also have information about each pass preserved (from Messi to Iniesta)
And here is a super bare-bones implementation of some functions which capture this behavior (I think a beginner should be able to grasp this stuff, let me know if anything below is a bit too confusing)
passes = {}
def new_pass(player1, player2):
# if p1 has no passes, create a new entry in the dict, else append to existing
if player1 not in passes:
passes[player1] = [player2]
else:
passes[player1].append(player2)
def total_passes(player1):
# if p1 has any passes, return the total number; otherewise return 0
total = len(passes[player1]) if player1 in passes else 0
return total
def total_passes_from_p1_to_p2(player1, player2):
# if p1 has any passes, count number of passes to player 2; otherwise return 0
total = passes[player1].count(player2) if player1 in passes else 0
return total
Ideally, you would be saving passes in some database that you could continuously update, but even without a database, you can add the following code and run it to get the idea:
# add some new passes!
new_pass('Messi', 'Xavi')
new_pass('Xavi', 'Iniesta')
new_pass('Iniesta', 'Messi')
new_pass('Messi', 'Iniesta')
new_pass('Iniesta', 'Messi')
# let's see where we currently stand
print total_passes('Messi')
print total_passes('Iniesta')
print total_passes_from_p1_to_p2('Messi', 'Xavi')
Hopefully you find this helpful; here's some more on python implementation of graphs from the python docs (this was a fun answer to write up, thanks!)
I suggest you construct a two dimensional square array. The array should have dimensions N x N. Each index represents a player. So the value at passes[i][j] is the number of times the player i passed to player j. The value passes[i][i] is always zero because a player can't pass to themselves
Here is an example.
players = ['Charles','Meow','Rebecca']
players = dict( zip(players,range(len(players)) ) )
rplayers = dict(zip(range(len(players)),players.keys()))
passes = []
for i in range(len(players)):
passes.append([ 0 for i in range(len(players))])
def pass_to(f,t):
passes[players[f]][players[t]] += 1
pass_to('Charles','Rebecca')
pass_to('Rebecca','Meow')
pass_to('Charles','Rebecca')
def showPasses():
for i in range(len(players)):
for j in range(len(players)):
print("%s passed to %s %d times" % ( rplayers[i],rplayers[j],passes[i][j],))
showPasses()

Pulling raw_input options form a list

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."

Categories

Resources