HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

A game modeled after Adventure

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
aftergameadventuremodeled

Problem

Here is a little game modeled after adventure that I have been working on. The code initializes a set of lists. It sets a current location randomly generated. The user is tasked with either incrementing the index or de-incrementing the index (moving up and down the avenue). At each location there is a store which they can enter into. If they choose to, they can buy something if they have enough money. If they buy something, their need is met and they receive pleasure. The goal of the game is to meet all your needs and receive the most pleasure before the time runs out. At this point you have 30 turns to do so, or 30 iterations of the while loop in main().

I'm worried about bugs. Basically, the way I am tracking the decisions of the user to buy stuff is by index. Meaning, if a user is at index 3, then they can enter into the store which is also at index 3, and meet their need which is at index 3. I am tracking streets, stores, and needs in separate lists. But once a person meets their need, lets say they 'eat pizza', I pop the need off the list.

But what happens when I do that? The need which is 'next in line' to the index 3, for instance, goes to index 3. So someone would be able to meet the need of index 4 while going to the location at index 3. So the question in sum is:

What is the proper way to structure the data so that the 'need' of index 3 stays in index 3, even if the need at index 2 is popped off? Can the code be changed, or does the data structure need to be changed?

I'd also like any feedback regarding content.

```
import sys
from travels import *
import random
import collections

print("Welcome to Cavernous J. You have stumbled upon a quaint commercial strip, and have a couple of hours to satisfy all yours needs before it closes up.")
start()

#the function which initializes the game - the initial arrays, variables
def start():
#initialize lists and variables
# global Streets, Need, Locations, money, pleasure, Time, check, street_index, curr

Solution

Input sanitizing and validation

As it stands, whenever you try to get input from the user, and check it against and if statement, it looks something like this:

user_input = raw_input( ... )

if user_input == ...:
    ...


This is a really bad way to get user input. Not only are you not sanitizing input, or lowering it, but you're also not doing error handling when you deal with integer input.

In order to properly "sanitize" input, I'd recommend that you use the following techniques:

-
Strip any leading and trailing whitespace. For example:

blah foo bar blah   
^^^^                 ^^^


-
Remove unnecessary, non alphanumeric characters. For example:

@$!$blah% foo^& bar-- bl*ah
^^^^    ^    ^^    ^^  ^


-
Convert all the characters in user input to lowercase characters.

In the case of integer input, you want to setup a try-except block, that will check to make sure that the user enters only valid integers. Here's what that might look like:

try:
    user_input_int = int(raw_input( ... ))
    ...
except ValueError:
    print "Invalid input!"
    ...


Dictionary lookups

Rather than chaining a bunch of if-elif statements, like this:

if blah == 1:
    ...

elif blah == 2:
    ...

...


You can use a dictionary to create a lookup table for user input. For example:

possible_inputs = {
    "input1": some_function,
    ...
}


Then, to check user input, all you have to do is something simple like this:

user_input = raw_input( ... )
if user_input in possible_inputs:
    possible_inputs[user_input]()
else:
    print "Invalid input!"
    ...


Do note, you will still want to validate, and sanitize your input with this method.

Style

Python has on official style guide, and you're violating many of these guidelines. According to this online checker, you have about 50 violations. Since there are too many issues to list here, here's a small list of some of the more important violations.

  • Variable names should be in snake_case, and constant variables should be in UPPER_SNAKE_CASE.



  • Function names should also be in snake_case.



  • Classes should be in PascalCase.



  • You should have spaces between binary, mathematical, comparison, and assignment operators. This adds additional clarity.



  • There should be two blank lines between top-level code block, functions, and classes.



  • Comments above function declarations should be converted into docstrings.



  • Wildcard imports, like from blah import *, should be avoided.



-
Commented lines of code, like these ones here:

# Streets, Need, Locations, money, pleasure, Time, check, street_index, current_street
#   print("User Input = " + user_input)
#    print("Numeric Value of User Input = " + str(user_answer))
#   print("Number of streets = " + str(len(Streets)))
#   print("Current Street = " + str(current_street))


Are a bit of a code smell. I'd highly recommend that you remove them, as it makes your code more readable, and easier to understand.

I'd highly recommend that you read PEP8, Python's official style guide.

Code Snippets

user_input = raw_input( ... )

if user_input == ...:
    ...
blah foo bar blah   
^^^^                 ^^^
@$!$blah% foo^& bar-- bl*ah
^^^^    ^    ^^    ^^  ^
try:
    user_input_int = int(raw_input( ... ))
    ...
except ValueError:
    print "Invalid input!"
    ...
if blah == 1:
    ...

elif blah == 2:
    ...

...

Context

StackExchange Code Review Q#104369, answer score: 5

Revisions (0)

No revisions yet.