简体   繁体   中英

How to dynamically choose a line from a csv file in python

For my final project in a python class, I need to make a "make you're own adventure" type game, or more of a game engine, using python... The csv file is the story;

Should I add a database to my app?,Use MS Access,No way - databases suck,2,3
You are buried in relational diagrams,Get through them and get to the fun stuff,Let's add in a few more relationships,4,5
Shall we stick with some fun Javascript?,Yes,No,7,5
Onto the coding!,Which language?,Let's use several!,3,6
I miss programming Python - Game Over!,,,,
Brain burn out - Game Over!,,,,
Good choice - take a break - Game Over!,,,,

and I need to print the first cell from a line, use the following x cells as prompts, and then the same amount of x cells are the lines that that answer will bring me to. (For example, if I say Use MS Access on the first question, I jump to line 2, and if I say No way - databases suck, I jump to line 3)

My question is, how do I make a line of code that will read out the prompt, show the unspecified amount of options, and then take the answer from that option and jump to the corresponding line?

This is what I have right now:

print(story[0][0])
print("1 -", story[0][1])
print("2 -", story[0][2])
print("3 - Save game")

And that shows up like:

Should I add a database to my app?
1 - Use MS Access
2 - No way - databases suck
3 - Save game

Which is what I want, but it's not dynamic, which is a requirement I need, but I was never thought how to do that.

To gather inputs from the user, you want the builtin input(prompt) function (nb: in Python2.x you want raw_input(prompt) instead). Beware, this function always returns a string so you'll have to turn it into an integer.

Then you have to get the current row's value matching the user's input (in your above example if the user types "1" ("Use MS Access"), you want to retrieve the associated value "2", and if types "2" ("No way, ....") you want to retrieve the value "3".

Once you have the value matching the user's input (and have turned it into an int - if you didn't already did so when loadin the cvs file in story ), you just have to retrieve the matching row from story , ie if the user typed "2" ("No way, ...."), you want to read the story 's third row (just beware, lists indexes are zero-based, so the third line is actually at index 2).

Then put all this in a loop (starting with 0 as current story index) and you're done.

NB : It would actually have been almost faster to answer with a full code example - this is actually simpler to code than to explain xD - but you wouldn't learn anything then ;-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM