I have a problem with the following code:
#1/usr/bin/env python3
import random
financialPoints = 0
debatePointsT = 0
marginalCheck = random.randint(0,1)
debatePointsTO = 0
Choice = random.randint(0,2)
popularity = 0
name = input("What is your first name")
nameSur = input("What is your surname")
print("This is the political campaign simulator")
chosenParty = input("Choose a party. A - LibDem, B - Labour, C- Tory")
if chosenParty == "C":
print("You have been elected as a councillor by your fellow peers.")
marginality = input("They want you to stand as a MP in a seat. Do you want to stand in a safe or marginal seat")
if marginality == "marginal":
if marginalCheck == 0:
print("You have failed to be elected to parliament")
else:
print("You are duly elected the MP for your constituency!")
campaignT()
else:
campaignT()
def debateT():
#My Code
if marginality == "safe":
campaignT()
def campaign():
#My Code
if elected == True:
debateT()
It tells me that I have called a function before referencing it, but I need it to be there for me to run another part of the code, as you can see above. Is there a way in python for me to get to functions to go side by side, or something like that?
The function definition must come before the code that references it.
Move debateT() and campaign() to the top of the file.
Move your defined functions to the top of your file like:
#1/usr/bin/env python3
import random
financialPoints = 0
debatePointsT = 0
marginalCheck = random.randint(0,1)
debatePointsTO = 0
Choice = random.randint(0,2)
def debateT():
#My Code
if marginality == "safe":
campaignT()
def campaign():
#My Code
if elected == True:
debateT()
popularity = 0
name = input("What is your first name")
nameSur = input("What is your surname")
print("This is the political campaign simulator")
chosenParty = input("Choose a party. A - LibDem, B - Labour, C- Tory")
if chosenParty == "C":
print("You have been elected as a councillor by your fellow peers.")
marginality = input("They want you to stand as a MP in a seat. Do you want to stand in a safe or marginal seat")
if marginality == "marginal":
if marginalCheck == 0:
print("You have failed to be elected to parliament")
else:
print("You are duly elected the MP for your constituency!")
campaignT()
else:
campaignT()
Related
There is module files as well but they work perfectly, the main problem is when you enter a module and it just printing out There is 'none' in here for every module. Additionally, if I wanted to change the fuel gain from 50 to randomly chose between 20,30,40 or 50.
The rest of the code works well but when the npc in a room is outputted it should say there is a 'workers' in here instead of just none for each module.
#Telium - Game
import random
#Global Variables
num_modules = 17 #Number of modules in the space station
module = 1 #Module of space station we are in
last_module = 0 #Last module we were in
possible_moves = [] #List of possible moves we can make
alive = True #Whether player is alive or not
won = False #Whether player has won
power = 100 #Amount of power the space station has
fuel = 500 #Amount of fuel the player has in flamethrower
locked = 0 #Module that has been locked by the player
queen = 0 #Location of queen alien
vent_shafts = [] #Location of ventilation shaft entrances
info_panels = [] #Location of info panels
workers = [] #Location of worker aliens
#procedure declarations
#This loads the global module
def load_module():
global module, possible_moves
possible_moves = get_modules_from(module)
output_module()
def get_modules_from(module):
moves = []
text_file = open("Charles_Darwin\module" + str(module) + ".txt", "r")
for counter in range(0,4):
move_read = text_file.readline()
move_read = int(move_read.strip())
if move_read != 0:
moves.append(move_read)
text_file.close()
return moves
def output_module():
global module
print()
print("--------------------------------------------------------------
-----------------------")
print()
print("You are in module",module)
print()
npc = spawn_npcs()
print("There is a ", npc ,"here")
def output_moves():
global possible_moves
print()
print("From here you can move to modules: | ",end='')
for move in possible_moves:
print(move,'| ',end='')
print()
def get_action():
global module, last_module, possible_moves, power
valid_action = False
while valid_action == False:
print("What do you want to do next ? (MOVE, SCANNER)")
action = input(">")
if action == "MOVE" or action.lower() == 'move' or action.lower()
== 'm' or action.higher() == 'M':
move = int(input("Enter the module to move to: "))
if move in possible_moves:
valid_action = True
last_module = module
module = move
#power is decreased by 1 for every move
power =- 1
else:
print("The module must be connected to the current
module.")
def spawn_npcs():
global num_modules, queen, vent_shaft, greedy_info_panels, workers
module_set = []
for counter in range(2,num_modules):
module_set.append(counter)
random.shuffle(module_set)
i = 0
queen = module_set[i]
for counter in range(0,3):
i=i+1
vent_shafts.append(module_set[i])
for counter in range(0,2):
i=i+1
info_panels.append(module_set[i])
for counter in range(0,3):
i=i+1
workers.append(module_set[i])
def check_vent_shafts():
global num_modules, module, vent_shafts, fuel
if module in vent_shafts:
print("There is a bank of fuel cells here.")
print("You load one into your flamethrower.")
fuel_gained = 50
print("Fuel was",fuel,"now reading:",fuel+fuel_gained)
fuel = fuel + fuel_gained
print("The doors suddenly lock shut.")
print("What is happening to the station?")
print("Our only escape is to climb into the ventilation shaft.")
print("We have no idea where we are going.")
print("We follow the passages and find ourselves sliding down.")
last_module = module
module = random.randint(1,num_modules)
load_module()
#Main Program starts here
#Menu options
print("ENTER 1 for instructions")
print("ENTER 2 to play")
print("ENTER 3 to quit")
menu = int(input("Please enter a number corresponding to what you want to
do: "))
if menu == 1:
instructions = input("Do you want to read the instructions(Y/N): ")
if instructions == "Y":
print("You, the player are trying to navigate around a space
station named the 'Charles Darwin' which contains many modules")
print("The aim of the game is to find a and trap the queen alien
called 'Telium' who is located somewhere randomly in the station, the
queen will try to escape to connectinhg modules so beware")
print("To win - you have to lock the queen in one of the modules
so she is trapped, you can kill her with a flamethrower, there is also
objects to help on the way so keep a look out")
spawn_npcs()
#Outputs where the queen, shafts, panels and workers are located
print("Queen alien is located in module:",queen)
print("Ventilation shafts are located in modules:",vent_shafts)
print("Information panels are located in modules:",info_panels)
print("Worker aliens are located in modules:",workers)
#when the players is alive, the module will load
while alive and not won:
load_module()
if won == False and alive == True:
output_moves()
get_action()
#if power is 0 then the user will die and the game will end
if power == 0:
print("You ran out of life support, you died")
alive == False
#win message once you have trapped the queen or when you run out of life
support
if won == True:
print("The queen is trapped and you burn it to death with your
flamethrower.")
print("Game over. You win!")
if alive == False:
print("The station has run out of power. Unable to sustain life
support, you die.")
check_vent_shafts()
First the easy part. You can randomly get 20, 30, 40 or 50 by using random.randint like this:
random.randint(2, 5) * 10
The harder part:
As you discussed with #Random Davis in the comments, you want to assign the npcs to random modules and then print which one you encounter.
To append three random (possibly repeating) modules, use
for _ in range(0,3):
vent_shafts.append(random.choice(module_set))
Using global variables (and the global keyword) is generally considered bad practice as it can cause sideeffects due to other parts of the program modifying a variable you wouldn't expect it to / forgot about. Try to use them as function parameters where needed and return the results
queen, vent_shafts, info_panels, workers = spawn_npcs(5)
def spawn_npcs(num_modules):
module_set = []
for i in range(2, num_modules):
module_set.append(i)
for _ in range(0,3):
vent_shafts.append(random.choice(module_set))
for _ in range(0,2):
info_panels.append(random.choice(module_set))
for _ in range(0,3):
workers.append(random.choice(module_set))
queen_module = module_set[0]
return queen_module, vent_shafts, info_panels, workers
basically i have made 4 question list and answer list the first one works fine but the next few don't work and come up with a error sometimes the first question is displayed but not the others
this is the tool and my code https://repl.it/#alandtic/final
Traceback (most recent call last):
File "main.py", line 155, in
print(question_list2[random_int])
IndexError: list index out of range
top_index=top_index-1
after deleting a question, you should atleast decrease top index.
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 14 10:38:13 2019
#author: jainil
"""
import random
print("\033[0;37;40m\n")
print("welcome to soldier to WW1")
print(
"If you are ready to die for your country then you must learn all the parts of a WW1 soldier. but first maggot answers a few personal questions. ")
first_name = input("What is your first name? ")
middle_name = input("what is your middle name? ")
last_name = input("what is your last name? ")
full_name = (first_name + " " + middle_name + " " + last_name)
print("Is this your correct name? " + full_name)
yes_or_no = input("Y/N ")
if yes_or_no == ("N"):
print("program will give you chance to renter name in do not mess up again this is your LAST chance")
first_name = input("What is your first name? ")
middle_name = input("what is your middle name? ")
last_name = input("what is your last name? ")
full_name = (first_name + " " + middle_name + " " + last_name)
print("this is your NAME NOW " + full_name)
print("before we get to the training base do you want basic info on how it works. ")
TRAINING = input("Y/N ")
if TRAINING == ("Y"):
print(
" welcome to basic training let’s go over basic need to know info? A typical day starts with Reveille (a bugle or trumpet call to wake the soldiers and call them to duty) at 5.30 a.m. After tidying up and cleaning your quarters and having a brew, at 6.30 recruits will parade for an hour and a half to work on your fitness. After breakfast at 8, the morning was spent drilling on the parade square, learning, for instance, to march, form fours and about turn . Between 12.15 and 2 p.m. troops men took lunch before returning for more drill in the afternoon until 4.15. The unlucky image you might be working parties the rafter, but otherwise recruits are off duty, although you might have to spend time cleaning kit and shining boots. In large garrison towns like Aldershot, you can have leisure facilities in the shape of the ‘Smith-Dorrien Soldiers’ Home’, with a billiards room, a library, recreation rooms, private baths and a buffet. ")
i_am_gay = input("are you ready for the test Y/N")
if i_am_gay == ("Y"):
import random
question_list = []
question_list.append("what time do you wake up? ")
question_list.append("what do you do at 6:30? ")
question_list.append("what is at Aldershot? ")
question_list.append("what time do you have lunch? ")
question_list.append("Do you need to go to bed at a specific time? ")
answer_list = []
answer_list.append("5:30")
answer_list.append("parade")
answer_list.append("Leasure")
answer_list.append("12:15")
answer_list.append("No")
top_index = 4
correct = 0
for i in range(0, 5):
random_int = random.randint(0, top_index)
print(question_list[random_int])
user_answer = input("enter your answer: ")
if user_answer == answer_list[random_int]:
print("\033[1;32;40m good job \n")
print("\033[0;37;40m\n")
correct = correct + 1
else:
print("\033[1;31;40m incorrect \n")
print("\033[0;37;40m \n")
del question_list[random_int]
del answer_list[random_int]
top_index=top_index-1
print("you scored " + str(
correct) + " out of 5 based on this you will receive a rank all scores are collected to give you a final rank at the end of our testing. ")
import os
import time
time.sleep(10)
os.system('clear')
print(
"The next step of your training is to chose a group to learn more about and train in all with different types ways to train. first is infantry (multiple choice questions) second is planing (tactics questions) and finally is marine (fill in the blank)")
form = input("please select which one you want 1/2/3 ")
if form == ("1"):
form = input("you have selected infantry is this correct if yes enter Y1 if no then put in your teams number")
if form == ("Y1"):
print(
"first step is to train you on the role of infantry. your main mission is to be a ground troop this includes but is not limited to. building trenches, fighting off front lines and attack the enemies trenches.")
print(
"now that your training is complete time for your first quiz this will be multiple choice and will be the main for your rank. ")
question_list1 = []
question_list1.append(
"which one of these is not your job? A: build trench B: act as a spy C: fight on the front lines D: follow orders ")
question_list1.append("who is your boss? A: the furrier B: privates C: civilians D: a lieutenant ")
question_list1.append("which weaponry is better for long range A:50 cow B: mp5 C: benelli M3 D: Barret M82 ")
question_list1.append(
"which is not a rank? A: master first sergeant B: command segment major C: corporeal: D: private ")
answer_list1 = []
answer_list1.append("B")
answer_list1.append("D")
answer_list1.append("D")
answer_list1.append("A")
top_index1 = 3
correct = 0
for i in range(0, 4):
random1_int = random.randint(0, top_index1)
print(question_list1[random1_int])
user_answer1 = input("enter [A] [B] [C] [D] : ")
if user_answer == answer_list1[random1_int]:
print("\033[1;32;40m good job \n")
print("\033[0;37;40m\n")
correct = correct + 2
else:
print("\033[1;31;40m incorrect \n")
print("\033[0;37;40m \n")
del question_list1[random1_int]
del answer_list1[random1_int]
top_index1 = top_index1 - 1
if form == ("2"):
form = input("you have selected planing is this correct if yes enter Y2 if no then put in your teams number")
if form == ("Y2"):
print(
"first step is to train you on the role of a planer. you need to give tips and info to your troops based on you skills. ")
print(
"now that your training is complete time for your first quiz this will be a tactics question and will be the main determination for your rank. ")
question_list2 = []
question_list2.append(
"side X has a large compound with 12 men and side + has the element of surprise and 3 elite troops ")
question_list2.append("side X has 3 troops and the high ground side + has 13 troops but is on the low ground ")
answer_list2 = []
answer_list2.append("x")
answer_list2.append("+")
top_index2 = 1
correct = 0
for i in range(0, 2):
random_int = random.randint(0, top_index2)
print(question_list2[random_int])
user_answer2 = input("which side has the advantage x or +? ")
if user_answer2 == answer_list2[random_int]:
print("\033[1;32;40m good job \n")
print("\033[0;37;40m\n")
correct = correct + 4
else:
print("\033[1;31;40m incorrect \n")
print("\033[0;37;40m \n")
del question_list2[random_int]
del answer_list2[random_int]
top_index2 = top_index2 - 1
if form == ("3"):
form = input("you have selected marine is this correct if yes enter Y3 if no then put in your teams number")
if form == ("Y3"):
print(
"first step is to train you on the role of a marine. you need to give tips and info to your troops based on you skills. ")
print(
"now that your training is complete time for your first quiz this will be fill in the blanks and will be the main determination for your rank. ")
question_list3 = []
question_list3.append(" the marines are ___ based operatives ")
question_list3.append(" for under water travel marines use _____ ")
question_list3.append(" the average marine trains for _ weeks ")
answer_list3 = []
answer_list3.append("sea")
answer_list3.append("submarines")
answer_list3.append("13")
top_index3 = 2
correct = 0
for i in range(0, 3):
random_inte = random.randint(0, top_index3)
print(question_list3[random_inte])
user_answer3 = input("fill in the blank with the correct word ")
if user_answer3 == answer_list3[random_inte]:
print("\033[1;32;40m good job \n")
print("\033[0;37;40m\n")
correct = correct + 3
else:
print("\033[1;31;40m incorrect \n")
print("\033[0;37;40m \n")
del question_list3[random_inte]
del answer_list3[random_inte]
top_index3 = top_index3 - 1
time.sleep(10)
os.system('clear')
print(
"congratulations on your finishing of the course i will now give you a rank based on your score from e1(private) to e9(major) ")
if correct == (1):
print("e1 i would say not bad but that should be a lie")
elif correct == (2):
print("e1 i would say not bad but that should be a lie")
elif correct == (3):
print("e2 not worthless but not good")
elif correct == (4):
print("e2 not worthless but not good")
elif correct == (5):
print("e3 now i will make a man out of you")
elif correct == (6):
print("e3 now i will make a man out of you")
elif correct == (7):
print("e4 seems like front lines will be wasted on you")
elif correct == (8):
print("e5 good job mr wane")
elif correct == (9):
print("e6 no front line for you")
elif correct == (10):
print("e7 steve rogers would be proud")
elif correct == (11):
print("e8 welcome to the order")
elif correct == (12):
print("e9 no jokes you did very good my superior")
elif correct == (13):
print("you have no rank you scored 100% my bet is your cheater shame on you. ")
elif correct == (14):
print("this is a marine exclusive rank i added because i was lazy tbh. ")
you have not updated top index even,
I'm trying to create a text-based adventure game and all is going well until I encountered a problem with assigning points to attributes. I've been using this website to help with the process but realized that it might be in Python 2. Here's all that I've done so far code:
#Date started: 3/13/2018
#Description: text-based adventure game
import random
import time
def display_intro():
print('It is the end of a 100-year war between good and evil that had \n' +
'killed more than 80% of the total human population. \n')
time.sleep(3)
print('The man who will soon be your father was a brave adventurer who \n' +
'fought for the good and was made famous for his heroism. \n')
time.sleep(3)
print('One day that brave adventurer meet a beautiful woman who he later \n' +
'wed and had you. \n')
time.sleep(3)
def get_gender(gen=None):
while gen == None: # input validation
gen = input('\nYour mother had a [Boy or Girl]: ')
return gen
def get_name(name = None):
while name == None:
name = input("\nAnd they named you: ")
return name
def main():
display_intro()
gender_num = get_gender()
charater_name = get_name()
print("You entered {} {}.".format(gender_num, charater_name))
if __name__ == "__main__":
main()
character_name = get_name()
# Assignning points Main
my_character = {'name': character_name, 'strength': 0, 'wisdom': 0, 'dexterity': 0, 'points': 20}
#This is a sequence establises base stats.
def start_stat():
print("\nThis is the most important part of the intro\n")
time.sleep(3)
print("This decides your future stats and potentially future gameplay.")
time.sleep(4)
print("\nYou have 20 points to put in any of the following category:
Strength, Health, Wisdom, or Dexterity.\n")
def add_charater_points(): # This adds player points in the beginnning
attribute = input("\nWhich attribute do you want to assign it to? ")
if attribute in my_character.keys():
amount = int(input("By how much?"))
if (amount > my_character['points']) or (my_character['points'] <= 0):
print("Not enough points!!! ")
else:
my_character[attribute] += amount
my_character[attribute] -= amount
else:
print("That attribute doesn't exist!!!")
def print_character():
for attribute in my_character.keys():
print("{} : {}".format(attribute, my_character[attribute]))
playContinue = "no"
while playContinue == "no":
Continue = input("Are you sure you want to continue?\n")
if Continue == "yes" or "Yes" or "y":
playContinue = "yes"
start_stat()
add_charater_points()
else:
display_intro()
gender_num = get_gender()
charater_name = get_name()
running = True
while running:
print("\nYou have {} points left\n".format(my_character['points']))
print("1. Add points\n2. Remove points. \n3. See current attributes. \n4. Exit\n")
choice = input("Choice: ")
if choice == "1":
add_charater_points()
elif choice == "2":
pass
elif choice == "3":
print_character()
elif choice == "4":
running = False
else:
pass
And here's what happens when I run it:
It is the end of a 100-year war between good and evil that had
killed more than 80% of the total human population.
The man who will soon be your father was a brave adventurer who fought for
the good and was made famous for his heroism.
One day that brave adventurer meet a beautiful woman who he later wed and
had you.
Your mother had a [Boy or Girl]: boy
And they named you: Name
You entered boy Name.
And they named you: Name
Are you sure you want to continue?
yes
This is the most important part of the intro
This decides your future stats and potentially future gameplay.
You have 20 points to put in any of the following category: Strength,
Health, Wisdom, or Dexterity.
Which attribute do you want to assign it to? strength
By how much? 20
You have 20 points left
1. Add points
2. Remove points.
3. See current attributes.
4. Exit
Choice: 3
name : Name
strength : 0
wisdom : 0
dexterity : 0
points : 20
You have 20 points left
1. Add points
2. Remove points.
3. See current attributes.
4. Exit
Choice:
Oh, and prompt for the name of the play goes again twice for some reason. Also, what does the my_character.keys() under def add_charater_points() mean? Since I just started to learn to code python, if there are any other tips you guys can give me it would be greatly appreciated.
The last two lines of this snippet
if (amount > my_character['points']) or (my_character['points'] <= 0):
print("Not enough points!!! ")
else:
my_character[attribute] += amount
my_character[attribute] -= amount
add the character points to the attribute, and immediately subtract them again. I think you might mean
my_character['points'] -= amount
Your repeated prompt is probably because you have a whole lot of code that logically seems to belong in function main() but is coded to run after main() finishes.
I have had problems with the shell saying local variable referenced before assignment and don't feel any previous answers have helped. Can I have some specific advice to this code:
import random
marginalCheck = random.randint(0,1)
print("This is the political campaign simulator")
global popularity
popularity = 50
def unpopularT():
if popularity <= 30 and popularity < 0:
print("You are decreasing in popularity.")
popularityRecover = input("Do you wish to carry on or resign. If this carries on, you are likely to lose to a landslide by your Labour opposition")
if popularityRecover == "resign":
print("You have become an infamous, unpopular politician. You are remembered as a horrible, unkind person")
else:
print("You are hanging by a thread")
elif popularity > 70:
print("You are seriously doing well among your supporters and gaining new ones every day")
else:
print("You are doing fine so far in the campaign")
def campaignT():
leadershipT = input("You are chosen as a candidate by your colleagues in the Tory leadership contest. Do you wish to take an A - Far Right, B - Right, C - Centre, D - Left or E - Far Left stance on the political spectrum")
if leadershipT == "A" or leadershipT == "B":
print("You have been elected as leader of the Tories and leader of the opposition. Now the election campaign starts")
ClassicToryAusterity = input("What do you wish to do about the poor funding in the NHS by the Labour government. A - Do you wish to keep the current program, B - Do you wish to increase funding dramatically and increase taxes, C - Do you propose minor increases with small raises on tax, D - Do you support austere implementations on the Health Service")
if ClassicToryAusterity == "A":
popularity += -5
elif ClassicToryAusterity == "B":
popularity += 5
elif ClassicToryAusterity == "C":
popularity += 2
elif ClassicToryAusterity == "D":
popularity += -10
BedroomTax = input("What do you propose to do about the bedroom tax. A - increase it, B - freeze it, C - Decrease it, D - Scrap it")
if BedroomTax == "A":
popularity += -10
elif BedroomTax == "B":
popularity += -5
elif BedroomTax == "C":
popularity += -1
else:
popularity += 10
unpopularT()
else:
print("The Tory whip dislikes your stance and you have not been voted as leader")
chosenParty = input("Choose a party. A - LibDem, B - Labour, C- Tory")
if chosenParty == "C":
print("You have been elected as a councillor by your fellow peers.")
marginality = input("They want you to stand as a MP in a seat. Do you want to stand in a safe or marginal seat")
if marginality == "marginal":
if marginalCheck == 0:
print("You have failed to be elected to parliament")
else:
print("You are duly elected the MP for your constituency!")
campaignT()
else:
campaignT()
What I don't understand is that I have referenced popularity as a global variable, but according to the shell, it is local.
If you want to use access global variables inside functions you don't need to declare anything, but if you need to re-assign the variable by any means, you need to declare it inside the function. For example:
test = 'hello'
def print_test():
print test
def set_test():
global test
test = 'new value'
in your case, you didn't declare the global variable popularity inside your function and you were trying to re-assign it.
So in your case:
def unpopularT():
global popularity
# your code
def campaignT():
global popularity
# your code
I'm new in Python but bear with me.
In my code, I am trying to make variable room to 2, via west() function.
Code:
EDIT: I have isolated most of the non-essential code.
room = 1
cmds = 'west'.lower()
def isValidCMD(cmd):
if cmd in cmds:
return True
else:
print("Unknown command. For help type /help, for available options type /options")
cmd = input(">> ")
if isValidCMD(cmd):
runCMD(cmd)
return False
def runCMD(cmd):
if cmd == '/help':
help()
elif cmd == '/exit':
exit()
elif cmd == '/about':
about()
elif cmd == '/stats':
stats()
elif cmd == '/options':
options()
elif cmd == 'north':
north()
elif cmd == 'south':
south()
elif cmd == 'east':
east()
elif cmd == 'west':
west()
elif cmd == '/lookaround':
look_around()
def west():
if room == 1:
print("You head on over to the lab, to get some advice from Professor Andrew.")
return 2 #LINE 40 < -------
elif room == 7:
print("You head back to Auderban Square feeling primed for battle.")
else:
print("You cannot go west.")
cmd = input(">> ")
if isValidCMD(cmd):
runCMD(cmd)
def main():
while True:
# Town
if room == 1:
print("\nYou are at the centre of town, Auderban Square.".upper())
print("\nYou look at the signpost and see 4 signs.")
print("\t- North - Twinleaf Forest")
print("\t- South - Store of Celestia")
print("\t- East - Deskemon Training Ground")
print("\t- West - Auderban's Deskemon centre")
# Lab
elif room == 2:
print("You are at Auderban's Deskemon Centre")
AndrewConv()
print("\nYou see the exit at the door.")
print("\t- East - Auderban Square")
cmd = input(">> ")
if isValidCMD(cmd):
runCMD(cmd)
main()
Output:
But room keeps its value, 1.
Please give some advice for the future so I won't make the same mistake twice.
Replace west() function with this:
def west():
global room
...
Global variables are widely considered bad programming practice because it is extremely difficult to determine where and when they might be modified in a large program. They also make thread-safe and reentrant code almost impossible to write.
A simple approach would be to have each function accept the room as a parameter and return the “new room.” You can then always update the room in your main function every time you invoke a command.
You will probably end up keeping track of more than the room, though. Consider using a mutable data structure like a dictionary or a class to store the game state, and then passing it into your command functions. That way, it is just as simple to keep up with many state variables as one, and you still do not need global variables.
def main():
state = {'room': 1}
while True:
[...]
if isValidCMD(cmd, state):
runCMD(cmd, state)
def west(state):
thisroom = state['room']
if thisroom == 1:
print("You head on over to the lab, to get some advice from Professor Andrew.")
state.update(room=2)
elif thisroom == 7:
print("You head back to Auderban Square feeling primed for battle.")
else:
print("You cannot go west.")
cmd = input(">> ")
if isValidCMD(cmd):
runCMD(cmd)
There are some additional issues with this code. For example, you duplicate the command prompt code in each command prompt, which is brittle and error prone, and unnecessary since you will be returning to main() anyway.
Edited: Here is a minimal, runnable example:
def main():
state = {'room': 1}
for i in range(20):
oldroom = state['room']
nextroom(state)
print("Went from room {} to room {}.".format(oldroom, state['room']))
def nextroom(state):
state['room'] += 2