Repeating sections of code multiple times in my text-based game - python

I'm making a text-based game, which is based largely in if-, elif- and else-statements. However, I also use while loops for different "areas" within the game. (Play_loop, Main_loop, Shop_loop, Fish_loop, etc.).
Lately I've implemented admin commands which I use in-game to change things on the go, and I want these to be available in every loop. I also have some general commands which I want to be available (help, leave, quit, logout, go to another area, check inventory, etc.).
The issue I'm facing is knowing that duplicated code should be avoided, but i'm wondering if this is necessary in this situation. I've already made many functions to make each command code pretty short, about 2-15 lines in general.
Should I add the code blocks into functions that do the same thing, and then just repeat the function, or should I just keep it as is? Or maybe I should do something else that I havent even thought about?
Example code:
elif command == '/user info':
if user.admin:
print(f'User-list: {users}')
who = input('Name of user: ').strip()
who_user = admin_load_user(who, users)
if who_user:
print(who_user.info())
print(who_user.display_inv())
else:
print(DNEError)
else:
print(PError)
elif command == '/add coins':
who = input('Who gets coins? ').strip()
amount = int(input('How much? ').strip())
admin_add_coins(who, amount, users)
save_users(users)

Code that is repeated should typically be put into functions, so that you have better overview and control over what they are doing. There you can also easily give them default arguments and expand on the code without bloating the main function of your program.
Here is a concise argument for using functions. It's written for C but applies to python as well.
Then, as Jason Chia pointed out, you should consider thinking about building your game into classes, as they solve some of the problems you mentioned and generally are an important control instrument for bigger programs where you need to coordinate different states (e.g. changing something in a room based on the player's actions).
This tutorial could help with that.
Does that about answer your question?

You should use decorator style to do it nice to read and write.
get inspiration here:
def requires_admin(f):
def wrapper(f):
#wraps(f)
def wrapped(*args, **kwargs):
#if not admin:
#return render_template('error.html')
return f(*args, **kwargs)
return wrapped
return wrapper
#app.route('/admin/action')
#requires_admin
def AdminAction():
whatyouwant()

Related

i have challenges implementing OOP in python

I am facing challenges implementing OOP in python to enable me to call the functions whenever i want , so far i have no syntax errors which makes quite challenging for me . The first part of the code runs ehich is to accept data but the function part does not run.
I have tried different ways of calling the function by creating an instance of it.
print (list)
def tempcheck(self,newList):
temp=newList[0]
if temp==27:
print ("Bedroom has ideal temperature ")
elif temp>=28 or temp<=26:
print ("Bedroom Temperature is not ideal ,either too low or too cold. ")
print ("Please to adjust the temperature to the optimum temperature which is 27 degree Celsuis")
# now to initialize args
def __init__(self,temp,puri1,bedwashroom,newList):
self.temp=temp
self.puri1=puri1
self.bedwashroom=bedwashroom
tempcheck(newList)
# now calling the functions
newvalue=tempcheck(list)
# where list contains the values from the input function.
I expected the function to to check the specific value at the location in the list provided which is called list and also for the function to return a string based on the if statements.
i got it right ,i figured out an alternative to my bug thanks for the critique however any further addition is welcome,
the main goal was to create a function that takes input and passes it to list to be used later i guess this code is less cumbersome
the link to the full code is pasted below

Are there alternatives to OptionMenu that can store other data than just strings?

I'm currently working on a project and i need the user to choose an option which will trigger something. The problem is that I have to check all the cases and i have quite a lot of options.
Here is what the code would look like:
def check(variable):
if (variable.get() == "GroupA"):
GroupA.doSomething()
elif (variable.get() == "GroupB"):
GroupB.doSomething()
...
elif (variable.get() == "GroupZ"):
GroupZ.doSomething()
Is there a more elegant way to code this other than just to hard code it? Or is there another drop down tool i can use in tkinter(It would be perfect if i could store another object which could be accessed along with the string)?

Repeating a function with another function

for an assignment we needed to make a function that flipped a coin and another to flip it 100 times. I was able to make a function that flipped a coin, but got stuck when trying to call it a 100 times with another function. This is what I have right now:
import random
def TC():
face = random.randint(0,1)
if face == 1:
return "head"
else:
return "tail"
print TC()
def ply(flips):
for i in range(flips):
return TC()
print ply(100)
When I run it it just says 'none.' Please tell me where I am going wrong. Thank You!
Just to start, your method naming is very bad. I doubt this is how your professor is teaching you to name methods and variables. It's ugly, against Python standards and hard to read I suggest you take some time and read PEP 8 it's how python was intended to be written.
So instead of TC you should use something like flip_coin and instead of ply use something like play_coin_flip or even simply play.
Next I don't know if I'm stepping outside of what you have learned but instead of using randon.randint you can use randon.choice.
And finally, as others have said, when you return you quit any other execution in a function and return whatever variable you retrun in that statement thus nullifying any other iterations of the loop you're performing. I suggest something like the below as a better program with corrections applied to make it function as intended.
from random import choice
faces = ['head', 'tail']
def flip_coin():
face = choice(faces)
return face
def play_coin_flip(flips = 1):
for i in range(flips):
print(flip_coin)
if __name__ == "__main__":
play_coin_flip(100)

railway booking program in python

I'm working on this project in python where I'm trying to code a system that allows the user to book, cancel, print train tickets and also save everything they've done to a separate file that the program reads every time it opens and the re-saves it with the new information when it is closed. I'm stuck because I don't know what to do next, I've defined a class for reservations and also some methods within the class. I'll eventually attempt to code a GUI, where the user just clicks on the button with the seat number they want to order to book it and so on. Here's what I've done so far, I'm a new programmer so please be kind, I need suggestions on what I should do next, I'm I on the right track or do I need to code in another way? Here's what I've done so far:
class Reservation:
def __init__ (self, seatCol, seatRow, department, destination, departure, price):
self.__seatCol = seatCol
self.__seatRow = seatRow
self.__departement = departement
self.__destination = destination
self.__departure = departure
self.__price = price
def selectDeparture(departure):
#Asks the user to pick a departure
def selectDestination(destination):
#Asks the user to pick a destination
def selectSeat(seatCol, seatRow, department):
#Asks the user to pick a seat and checks if it's already booked
def ticketPrice (price):
def printBookedTicket:
If you are dead set on using classes for this project, make sure to follow a good tutorial on Python OOP programming.
However, I recommend learning some Python fundamentals before tackling OOP stuff.
If I was going to make this program, I would put all my data in a dictionary and make functions that could do all my editing of the data. Once you get this, if you feel like wrapping a class around it, you could.
Start with a simple command line interface to manipulating your data, something like:
ticket_booker.py add John Smith
>> Departure : ?
>> Destination: ?
>> (etc).

Python Global Variable Not Working

I have an extremely long program for a Canasta game that I am writing, in it there is a variable that ends the turn of the player if it equals a certain value. However, the turn repeats itself.
I have read many different articles and posts on forums like this one, but none of these seem to work. I even have a debug system to print the value of the variable before the if statement, and the variable is the right value, but the if statement doesn't see the same value.
I can't give the entire code, as it is extremely long, but I can give the sections that use this variable. I am using Python 2.7.2 and cannot make files separate from the main file to import.
The first line of the program is:
endTurn=1
The following function is called when conditions to win the game are met, but I have not been able to test that this works because of the bug.
def winGame(player):
global endTurn
gameWinner=player
gameWinner["score"]+=100
endTurn=0
The following function is called when a move is made. The variable decide is a raw_input() variable.
def move(player,decide):
global endTurn
theMove=decide.lower()
#if player says to end turn
if theMove=="end":
#until player discards something
discarded=0
while not discarded:
displayHand(player)
#ask player for discard
discard=int(raw_input(" Enter the list number of the card you wish to discard:"))-1
#if discard ID is in player's hand length
if not discard<0 and not discard>len(player["hand"])-1:
#add card to discard pile and remove from hand
discardPile.append(player["hand"][discard])
del(player["hand"][discard])
discarded=1
debug("Before changing, endTurn is %s"%str(endTurn))
endTurn = 0
debug("After changing, endTurn is %s"%str(endTurn))
if theMove=="new book":
newBook(player)
if theMove=="add to book":
addBook(player)
Here is where the turn should be ended. turn(thePlayer) repeats the function. The debug statement shows the correct value, 0, but the if still reads a 1. The function this is in also has the global endTurn at the top.
debug("If ending turn, endTurn of %s should be 0."%str(endTurn))
if endTurn==1:
turn(thePlayer)
Any help is greatly appreciated!
EDIT: The code is available at http://labs.codecademy.com/CV9z#:workspace. I ask that anyone viewing the code does not modify it, so that other people can see the true code.
I fixed the bug. I removed the endTurn variable and instead made the function that ends the turn just do the turn of the next player. It also simplified my code a bit.
I am wondering though, is using this method of running a function inside of itself over and over and over again (without leaving) rather messy or maybe slowing down my program?
EDIT: I now realize that this answer does not exactly help with anyone else who is stuck with global variables...
The previous answer I posted was just wrong, as it was based on a misinterpretation of the namespace docs as I had read them (Thanks to TheifMaster for pointing out my error), so this is a SEVERELY EDITED ANSWER:
The problem is in the while loop that I was able to read when the link to the entire code was posted after the erroneous answer I gave earlier.
while gameWinner==0:
endTurn=1
turn(player1)
if not gameWinner==0:
endTurn=1
turn(player2)
The game can never get to player two in this loop until gameWinner!=0.
I added the entire code to my sandbox and changed it to:
while gameWinner==0:
endTurn=1
turn(player1)
if gameWinner==0: #if player1 did not win yet
endTurn=1
turn(player2)
However, the game is still buggy... No one can win! gameWinner is not changed globally by the winGame() function until you add it to the global statement as I have shown here.
def winGame(player):
global endTurn, gameWinner
gameWinner=player
gameWinner["score"]+=100
debug("gameWinner == " + str(gameWinner))
endTurn=0

Categories

Resources