I'm trying to make a very simple blackjack game in python and it works well. The problem is that I want to restart it when it finishes, but doesn't restart. Any ideas?
Piece of code
import random
class BlackjackGame():
def __init__(self):
self.randomNumberMachine = random.randint(4,24)
self.randomNumberUser = random.randint(4,24)
self.conditionalBoolean = False
def blackjackMain(self):
self.numberInput = int(input("Introduzca la apuesta "))
while not self.conditionalBoolean:
if self.randomNumberUser > 21:
print("Desgraciadamente has perdido\nPuntos de la maquina: " + str(self.randomNumberMachine) + "\nPuntos tuyos: " + str(self.randomNumberUser))
self.numberInput = self.numberInput / 2
if self.numberInput <= 0:
print("Tienes solo 0 euros")
else:
print("Tienes " + str(self.numberInput) + " euros")
self.conditionalBoolean = True
else:
userChoice = int(input(("Tienes " + str(self.randomNumberUser) + "puntos, deseas:\n1)Retirarte\n2)Aumentar\n")))
if userChoice == 1:
if self.randomNumberUser > self.randomNumberMachine or self.randomNumberMachine > 21:
print("Enhorabuena, has ganado\nPuntos de la maquina: " + str(self.randomNumberMachine) + "\nPuntos tuyos: " + str(self.randomNumberUser))
self.numberInput = self.numberInput * 2
print("Ahora tienes " + str(self.numberInput) + " euros")
elif self.randomNumberMachine == self.randomNumberUser:
print("Empate\nPuntos de la maquina: " + str(self.randomNumberMachine) + "\nPuntos tuyos: " + str(self.randomNumberUser))
else:
print("Desgraciadamente has perdido\nPuntos de la maquina: " + str(self.randomNumberMachine) + "\nPuntos tuyos: " + str(self.randomNumberUser))
self.numberInput = self.numberInput / 2
if self.numberInput <= 0:
print("Tienes solo 0 euros")
else:
print("Tienes " + str(self.numberInput) + " euros")
self.conditionalBoolean = True
elif userChoice == 2:
self.aumentPoints = random.randint(2,10)
self.randomNumberUser = self.randomNumberUser + self.aumentPoints
self.blackjackMain()
jugador1 = BlackjackGame()
jugador1.blackjackMain()
The self.numerInput input it keeps asking the same thing and doesn't restart the program.
Inside blackjackMain(self), the variable self.conditionalBoolean is only set to True. When this happens, you while condition is always False and the code inside is not executed anymore.
If you want to enter the while block, you need to set the variable somewhere outside of this block.
Related
So I'm trying to make a calculator but when i do plus (also with other things but for example) it does work but after the outcome comes it asks for number 2 again, I just want the code to start again.
this is the plus piece of the code:
q = input(str("Wil je de bewerkingsteken legende zien? (j/n): "))
if q == "J" or q == "j" :
print ("\nplus = + ")
print ("min = -")
print ("maal = X")
print ("delen door = :")
print ("quadrateren = Q")
print ("tot de kracht van = P")
print ("Worteltrekken = W")
print ("Procent = %")
num1 = float(input("\n Nummer 1: "))
bew = input("\n Bewerkingsteken: ")
num1_word = (str(num1))
if bew == "+" :
plus_num2 = input(float("\nNummer 2: "))
plus_num2_con = (str(plus_num2))
plus_out = (num1 + plus_num2)
plus_out1 = (str(plus_out))
print ("\n" + num1_con +" + " + num2_con + " = " + plus_out1)
First, you write the input wrong for plus_num2. Try this;
plus_num2 = float(input("\nNummer 2: "))
Second, you define the number's name different from last print function. Try This;
print ("\n" + num1_word +" + " + plus_num2_con + " = " + plus_out1)
Third, if you want to start the code again you can add while True on first line.
So I have been working on a quizzing application for some time now (about 4 days). I managed to make all the logical part of the code (the quiz taking, the quiz question handling, score outputting, etc.) I know that this code is neither the best nor the most efficient as it can be but I'm just a beginner. Anyways, the get() function for the entry function for tkinter does not return anything. I am aware that there is a way to fix it however I'm not sure how to implement the solution with an external loop. Please help me. Here is my code:
import random
from time import sleep
import tkinter as tk
from tkinter import *
import threading
class App(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.start()
def callback(self):
self.root.quit()
def run(self):
self.root = tk.Tk()
self.root.protocol("WM_DELETE_WINDOW", self.callback)
#label = tk.Label(self.root, text="Hello World")
#label.pack()
#Button(self.root, text = "Choose", command=btnPressed).pack()
tk.Label(self.root, text="Answer: ").grid(row=0,column=0)
#answerField_get = StringVar()
answerField = tk.Entry(self.root)
answerField.grid(row=0, column=1)
#Button(self.root, text='Show').grid(row=3, column=1, sticky=tk.W, pady=4)
print(str(answerField.get()))
Button(self.root, text='Show', command = lambda arg1=answerField.get():btnPressed("<"+str(arg1)+">")).grid(row=3, column=1, sticky=tk.W, pady=4)
self.root.mainloop()
def sendTMP(self, sendStr):
btnPressed(sendStr)
SCORE_SET = []
qasTmp = {}
qas = {}
qasSequenced = {}
incorrectResponses = []
incorrectResponses_replies = []
quiztaker_name = ""
attachAnsCode = "%% Fun fact: rgb computer parts lovers are somewhat weird hehe %%********^^&&^^&&^^&&"
qasQsSequenced = False
qasQsL = 0
qasQsL_divisionFactor = 2
qasINDEX = 0
err_noCode = "<!>NO_CODE<!>"
codes_answerCorrect = "A_C"
codes_answerIncorrect = "A_I"
answerCode = err_noCode
score = 0
randQs = False
# File
# the metadata will corrupt the reading from the file, a separate file, created in the targeted system, must be used to properly read the data.
# comment out the file name that is not being used.
filename_windows = "qas-windows"
filename_rpi = "qas-rpi"
filename = filename_windows
fileformat = "txt"
file_name_format = filename + "." + fileformat
spaceIndicator = "|"
char_commentLine_qasFile = "*"
char_newline = "`"
print("Information about modes: ")
print(" *Easy: No point deductions for an incorrect response")
print(" *Hard: One point deducted for every incorrect response")
modes_err = "0"
modes_ez = "1"
modes_hard = "2"
gameOn = False
selectedMode = modes_err
askReplay = True
data_prev = []
with open("SCORES.txt", 'r') as scores_prev:
data_prev = scores_prev.readlines()
scores_prev.close()
for i in range(0, len(data_prev)):
SCORE_SET.append(data_prev[i])
def btnPressInform():
print("A button has been pressed!")
def importAndClean():
# import questions from qas-windows.txt
with open(file_name_format, 'r') as document:
for line in document:
if line.strip():
key, value = line.split(None, 1)
if key[0] != char_commentLine_qasFile: # Custom comments for the txt file
qasTmp[key] = value.split()
# Clean up dictionary input from the txt file
for i in range(0, len(qasTmp)): # FIVE FOR LOOPS!!!! (FOUR IN THIS ONE)
for ii in qasTmp:
output = ""
output_ans = ""
for iii in range(0, len(ii)):
if ii[iii] != spaceIndicator:
output += ii[iii]
else:
output += " "
for iiii in range(0, len(qasTmp[ii])):
TEMP = str(qasTmp[ii])
for iiiii in range(2, len(TEMP) - 2): # IGNORE [' and ']
# print(TEMP[iiiii])
if TEMP[iiiii] != spaceIndicator:
output_ans += TEMP[iiiii]
else:
output_ans += " "
# print(output + " : " + output_ans) #Output question: answer
qas[output] = output_ans
importAndClean()
def getL():
qasQsL = len(qas) / qasQsL_divisionFactor # only ask 1/qasQsL_divisionFactor the questions
qasQsL = int(qasQsL) # round to an integer as odd numbers will end in .5 after division
if qasQsL < 1:
qasQsL = 1 # Have atleast ONE question
return qasQsL
def debug1(keys, vals, index, i):
print(str(index) + "/" + str((len(keys) - 1)))
print(keys)
print(vals)
print()
print(keys[index] + " : " + vals[index] + "\n")
print("Sorting original index " + str(i) + " at random index " + str(index))
def debug2(keys, vals, index):
print(keys)
print(vals)
print("\n")
def debugFinal():
print("Temp (OG reading): ")
print(qasTmp)
print("\nQAS (Non-sequenced, cleaned): ")
print(qas)
print("\nQAS Sequenced (Randomly sequenced, cleaned): ")
print(qasSequenced)
def randomize(qasQsL_tmp):
qas_keys = list(qas.keys())
qas_vals = list(qas.values())
if randQs == False:
qasQsL_tmp = len(qas_keys) # all questions
print("You will be asked all " + str(qasQsL_tmp) + " questions")
else:
qasQsL_tmp = getL() # random question
print("You will be asked " + str(qasQsL_tmp) + " questions out of " + str(len(qas)) + " possible questions!")
print("\n\nRandomly sequencing questions...")
for i in range(0, qasQsL_tmp):
INDEX = random.randint(0, qasQsL_tmp - 1)
# debug1(qas_keys, qas_vals, INDEX, i)
qasSequenced[qas_keys[INDEX]] = qas_vals[INDEX]
qas_keys.pop(INDEX)
qas_vals.pop(INDEX)
qasQsL_tmp -= 1
# debug2(qas_keys, qas_vals, INDEX)
sleep(0.05)
# debugFinal()
print("Done sequencing! Starting quiz now! \n\n")
return "0"
def quizController(index):
qas_keys = list(qasSequenced.keys())
qas_vals = list(qasSequenced.values())
# print(qas_keys)
# print(qas_vals)
lines = []
lines_index = 0
tmp = ""
# Splitter
for i in range(0, len(qas_keys[index])):
if lines_index < len(qas_keys[index]) - 1:
if qas_keys[index][i] != char_newline:
tmp += qas_keys[index][i]
else:
lines.append(tmp)
tmp = ""
lines.append(tmp)
# Multiple choice
mChoiceQ = False
mChoice_startBrackets = 0
mChoice_endBrackets = 0
mChoice_options = []
mChoice_numOptions = 0
mChoice_seperatorsAt = []
for i in range(0, len(qas_keys[index])):
if qas_keys[index][i] == "[":
mChoice_startBrackets = i
mChoiceQ = True
elif qas_keys[index][i] == "]":
mChoice_endBrackets = i
elif qas_keys[index][i] == "/":
mChoice_seperatorsAt.append(i)
if mChoiceQ == True:
TEMP = ""
for i in range(mChoice_startBrackets, mChoice_endBrackets + 1):
if qas_keys[index][i] != "[":
if qas_keys[index][i] != "/" and qas_keys[index][i] != "]":
TEMP += qas_keys[index][i]
else:
mChoice_options.append(TEMP)
TEMP = ""
mChoice_numOptions = len(mChoice_seperatorsAt) + 1
# Default options (yes, no) full names
for i in range(0, len(mChoice_options)):
if mChoice_options[i].lower() == "y":
mChoice_options.append("yes")
elif mChoice_options[i].lower() == "n":
mChoice_options.append("no")
# if mChoiceQ == True:
# print("It is a multiple choice question! There are " + str(mChoice_numOptions) + " options. They are: ")
# print(mChoice_options)
print("\nQuestion " + str(index + 1) + "/" + str(qasQsL) + ":")
for i in range(0, len(lines)):
print(lines[i])
# answer = ""
answer = input(">")
# answer = input(qas_keys[index]+ ": ")
if mChoiceQ == False:
if len(answer) > 0:
if answer.lower() == str(qas_vals[index]).lower():
return codes_answerCorrect
else:
incorrectResponses.append(qas_keys[index])
incorrectResponses_replies.append(answer)
# print("DEBUG: Incorrect response! Expected '" + str(qas_vals[index]).lower() + "', received " + answer.lower())
return codes_answerIncorrect
else:
print("Please insert an answer!")
else:
allowedResponse = False
for i in range(0, len(mChoice_options)):
if answer.lower() == mChoice_options[i].lower():
allowedResponse = True
if allowedResponse == True:
ans = qas_vals[index].lower()
yn = False
ans_yesno = ""
if ans.lower() == "y" or ans.lower() == "n":
yn = True
else:
yn = False
if yn == True:
if ans == "y":
ans_yesno = "yes"
elif ans == "n":
ans_yesno = "no"
if len(answer) > 0:
if yn == True:
if answer.lower() == ans.lower() or answer.lower() == ans_yesno.lower():
return codes_answerCorrect
else:
return codes_answerIncorrect
incorrectResponses.append(qas_keys[index])
incorrectResponses_replies.append(answer)
else:
if answer.lower() == ans.lower():
return codes_answerCorrect
else:
return codes_answerIncorrect
incorrectResponses.append(qas_keys[index])
incorrectResponses_replies.append(answer)
else:
print("Please insert an answer!")
else:
print("Invalid response! You may only enter the following: " + str(mChoice_options))
def saveScore():
# Clear file!
score_file_CLEAR = open("SCORES.txt", "wt")
score_file_CLEAR.close()
# Save contents
score_file = open("SCORES.txt", "wt")
for i in range(0, len(SCORE_SET)):
score_file.write(SCORE_SET[i])
print("Done saving!")
def btnPressed(tmp):
print(tmp)
app = App()
while True:
qasQsL = len(qasSequenced)
if gameOn == True and selectedMode != modes_err:
if qasQsSequenced == True:
if qasINDEX < qasQsL:
answerCode = quizController(qasINDEX)
else:
output = randomize(qasQsL)
if output == "0":
qasQsSequenced = True
if qasINDEX < qasQsL:
if answerCode == codes_answerCorrect:
score += 1
qasINDEX += 1
# print("DEBUG: Correct! Score set to: " + str(score))
elif answerCode == codes_answerIncorrect:
if selectedMode == modes_hard:
score -= 1
qasINDEX += 1
# print("Score set to: " + str(score))
else:
print("")
if qasQsL != 0:
score_per = score / qasQsL
if score_per < 0:
score_per = 0
if score < 0:
score = 0
print("You score was lower than 0, therefore it was set to 0")
# print("Your score: " + str(score) + "/" + str(len(qasSequenced)) + " (" + str(int(score_per*100)) + "%)")
# if score != qasQsL:
# print("You responded to the following questions incorrectly:")
# print(incorrectResponses)
if score / qasQsL == 1:
SCORE_SET.append(quiztaker_name + " scored " + str(score) + " out of " + str(qasQsL) + "(" + str(
int(score / qasQsL) * 100) + "%). PART OF Qs: " + str(
int(randQs)) + " at division factor 1/" + str(qasQsL_divisionFactor) + ", MODE: " + str(
int(selectedMode)) + "\n")
if score / qasQsL != 1:
SCORE_SET.append(quiztaker_name + " scored " + str(score) + " out of " + str(qasQsL) + " (" + str(
int(score / qasQsL) * 100) + "%). PART OF Qs: " + str(
int(randQs)) + " at division factor 1/" + str(qasQsL_divisionFactor) + ", MODE: " + str(
int(selectedMode)) + " They got the following questions wrong: \n")
for i in range(0, len(incorrectResponses)):
SCORE_SET.append(" " + str(i + 1) + ") " + incorrectResponses[i] + " --RESPONSE-- " +
incorrectResponses_replies[i] + "\n")
SCORE_SET.append("\n")
saveScore()
qasQsSequenced = False
gameOn = False
print("\nGame over!")
askReplay = True
else:
continue
elif askReplay == False:
TEMP = input("What mode would you like? (E = Easy, H = Hard): ")
if len(str(TEMP)) > 0:
if str(TEMP).lower() == "e":
selectedMode = modes_ez
gameOn = True
print("Set mode to: NO POINT DEDUCTIONS")
elif str(TEMP).lower() == "h":
selectedMode = modes_hard
gameOn = True
print("Set mode to: POINT DEDUCTIONS ALLOWED")
else:
print("Error: Undefined response. Please try again!")
elif askReplay == True:
TEMP = input("Would you like to (re)do the quiz? (Y/N): ")
if len(str(TEMP)) > 0:
if str(TEMP).lower() == "y":
askReplay = False
qasQsSequenced = False
qasQsL = 0
qas.clear()
qasSequenced.clear()
qasTmp.clear()
qasINDEX = 0
incorrectResponses.clear()
answerCode = err_noCode
score = 0
selectedMode = modes_err
importAndClean()
randQs = False
USER_TEMP = input("Please enter your name >")
if len(USER_TEMP) > 0:
quiztaker_name = str(USER_TEMP)
print("Welcome " + quiztaker_name + "!")
USER_TEMP = input("Would you like all questions (a) or a part of the questions(p)? (A/P) > ")
if len(USER_TEMP) > 0:
if USER_TEMP.lower() == "a":
print("Set to all questions!")
randQs = False
elif USER_TEMP.lower() == "p":
print("Set to 1/" + str(qasQsL_divisionFactor) + " questions (pre-set variable)")
randQs = True
else:
print("Undefined response! Setting to default value (ALL)")
randQs = False
gameOn = False
askReplay = False
elif str(TEMP).lower() == "n":
selectedMode = modes_hard
gameOn = False
print("Exiting now!")
saveScore()
sleep(2)
exit(0)
else:
print("Error: Undefined response. Please try again!")
Entry() doesn't work like input(). It doesn't wait for your data but it only informs tkitner that you want to display Entry widget (and mainloop() will display it) and Python goes to next lines of code and it runs print(str(answerField.get())) before it even displays window - so you try to get from empty Entry.
You should get it in function assigned to Button which you will press after you put some text in Entry.
The same problem is with
lambda arg1=self.answerField.get():print(arg1)
it assigns to args value from Entry only once when lambda is defined at start - so it get empty string. You should use it inside function
command=lambda:print(self.answerField.get())
or create normal function and assign to button.
Minimal working code
import tkinter as tk
import threading
class App(threading.Thread):
def run(self):
self.root = tk.Tk()
#self.root.protocol("WM_DELETE_WINDOW", self.on_close)
self.answerField = tk.Entry(self.root)
self.answerField.grid(row=0, column=1)
#b = tk.Button(self.root, text='Show', command=lambda:print(self.answerField.get()))
b = tk.Button(self.root, text='Show', command=self.on_click)
b.grid(row=1, column=1)
self.root.mainloop()
def on_click(self):
print(self.answerField.get())
#def on_close(self):
# self.root.destroy()
App().start()
#App().run()
I'm new to python and about a month into learning. I came across an issue where when I run this code it's supposed to print out the numbers in red. The second example shows what it really prints out and I'm stuck. Please help.
It's supposed to print ('Enemy HP:', 1150/1200)
but it actually prints ('Enemy HP:', '\x1b[91m1150/1200\x1b[0m\n')
import random
class bcolors:
HEADER = '\033[95m'
OKBLUE = "\x1b[94m"
OKGREEN = "\x1b[92m"
WARNING = '\033[93m'
FAIL = '\x1b[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
class Person:
def __init__(self, hp, mp, atk, df, magic):
self.maxhp = hp
self.hp = hp
self.maxmp = mp
self.mp = mp
self.atkl = atk - 10
self.atkh = atk + 10
self.df = df
self.magic = magic
self.actions = ["Attack", "Magic"]
def generate_damage(self):
return random.randrange(self.atkl, self.atkh)
def generate_spell_damage(self, i):
mgl = self.magic[i]["dmg"] - 5
mgh = self.magic[i]["dmg"] + 5
return random.randrange(mgl, mgh)
def take_damage(self, dmg):
self.hp -= dmg
if self.hp < 0:
self.hp = 0
return self.hp
def get_hp(self):
return self.hp
def get_max_hp(self):
return self.maxhp
def get_mp(self):
return self.mp
def get_max_mp(self):
return self.maxmp
def reduce_mp(self, cost):
self.mp -= cost
def get_spell_name(self, i):
return self.magic[i]["name"]
def get_spell_mp_cost(self, i):
return self.magic[i]["cost"]
def choose_action(self):
i = 1
print(bcolors.OKBLUE + bcolors.BOLD + "Actions" + bcolors.ENDC)
for item in self.actions:
print(str(i) + ":", item)
i += 1
def choose_magic(self):
i = 1
print(bcolors.OKBLUE + bcolors.BOLD + "Magic" + bcolors.ENDC)
for spell in self.magic:
print(str(i) + ":", spell["name"], "(cost:", str(spell["cost"]) + ")")
i = 1
from classes.game import Person, bcolors
magic = [{"name": "Fire", "cost": 10, "dmg": 100},
{"name": "Thunder", "cost": 10, "dmg": 124},
{"name": "Blizzard", "cost": 10, "dmg": 100}]
player = Person(460, 65, 60, 34, magic)
enemy = Person(1200, 65, 45, 25, magic)
running = True
i = 0
print(bcolors.FAIL + bcolors.BOLD + "AN ENEMY ATTACKS!" + bcolors.ENDC)
while running:
print("======================")
player.choose_action()
choice = input("Choose action:")
index = int(choice) - 1
if index == 0:
dmg = player.generate_damage()
enemy.take_damage(dmg)
print("You attacked for", dmg, "points of damage.")
elif index == 1:
player.choose_magic()
magic_choice = int(input("Choose magic:")) - 1
magic_dmg = player.generate_spell_damage(magic_choice)
spell = player.get_spell_name(magic_choice)
cost = player.get_spell_mp_cost(magic_choice)
current_mp = player.get_mp()
if cost > current_mp:
print(bcolors.FAIL + "\nNot enough MP\n" + bcolors.ENDC)
continue
player.reduce_mp(cost)
enemy.take_damage(magic_dmg)
print(bcolors.OKBLUE + "\n" + spell + " deals", str(magic_dmg), "points of damage" + bcolors.ENDC)
enemy_choice = 1
enemy_dmg = enemy.generate_damage()
player.take_damage(enemy_dmg)
print("Enemy attacks for", enemy_dmg)
print("----------------------------")
print("Enemy HP:", bcolors.FAIL + str(enemy.get_hp()) + "/" + str(enemy.get_max_hp()) + bcolors.ENDC + "\n")
print("Your HP:", bcolors.OKGREEN + str(player.get_hp()) + "/" + str(player.get_max_hp()) + bcolors.ENDC)
print("Your MP:", bcolors.OKBLUE + str(player.get_mp()) + "/" + str(player.get_max_mp()) + bcolors.ENDC + "\n")
if enemy.get_hp() == 0:
print(bcolors.OKGREEN + "You Win!", + bcolors.ENDC)
running = False
elif player.get_hp() == 0:
print(bcolors.FAIL + "Your enemy has defeated you!" + bcolors.ENDC)
running = False
Your code would work well in Python 3, where print is a function:
>>> print("x", "y")
x y
It means "print the first argument, then the separator (which defaults to a space), then the second argument.
In Python 2, though:
>>> print("x", "y")
('x', 'y')
prints a representation of the tuple containing your strings.
So, you can either use Python 3, which has many advantages, or change your code like this:
print("Enemy HP:" + bcolors.FAIL + str(enemy.get_hp()) + "/" +
str(enemy.get_max_hp()) + bcolors.ENDC + "\n")
# note the + instead of ,
in order to print a single string.
does it work for your others print ?
You have a double quote "" instead off simple '' on OKGREEN in class bcolors maybe it comes from here
My problem is that if you look at 'support' variable. (In the variable list) it doesn't apply to the Current Consumption. For EX. If I press 'S' and enter to start the game then press 'M' to display missions then press 'S' to choose the Survivors mission. And I recieve 2 survivors. That count won't add to the support for some reason and display "You are consuming 0.5 blah blah blah" not "You are consuming 0.7 blah blah blah" as it should be adding 0.1 per human? Sorry if this is hard to understand, I'm only 11 trying to program!
import random
from PIL import Image
print('\x1b[6;30;42m' + 'Zombie Survival Simulator' + '\x1b[0m')
print "Press [S] to start!"
resp = raw_input()
if 's' in resp or 'S' in resp:
foodmission = ['Convience Store','Grocery Store','Restraunt','Food Storage Area']
watermission = ['Convience Store', 'Old Gas Station', 'Water Tower','Toppled Coca-Cola truck.']
survivormission = ['Abandoned Refugee Camp','Bus','Army Camp','Train Station']
"FOOD"
#Pick Area
def pickfoodMission():
foodmis = random.choice(foodmission)
return foodmis
#Chance to get food
def chanceFood():
foodcha = random.randint(1,20)
return foodcha
#How much food you gain a mission
def foodPickup():
foodpick = random.randint(1,2)
return foodpick
"WATER"
#Pick the area
def pickwaterMission():
watermis = random.choice(watermission)
return watermis
#Chance for getting water
def chancewater():
watercha = random.randint(1,20)
return watercha
#Number of water you gain a mission
def waterPickup():
waterpick = random.randint(1,2)
return waterpick
"SURVIVORS"
#Pick the area
def picksurvivorMission():
survivormis = random.choice(survivormission)
return survivormis
#Chance for getting water
def chancehuman():
humancha = random.randint(1,20)
return humancha
#Number of water you gain a mission
def humanPickup():
humanpick = random.randint(1,2)
return humanpick
food = 3
water = 3
human = 5
healthy = 0
con = 0.1
level = 1
game = 1
new = 1
foodcon = 0
watercon = 0
support = 0.1 * human
newhuman = (human + (1 + (human / 5)) + healthy)
newwater = (water + (1 + (human / 5)) + healthy)
newfood = (water + (1 + (human / 5)) + healthy)
while game == 1:
if food <= 0 or water <= 0:
print('\x1b[7;30;41m' + 'You and your friends are dead.' + '\33[3m')
break
if food >= 3 or water >= 3:
healthy = healthy + 1
if food <= 2 or water <= 2:
healthy = healthy - 1
print "Current Resources: Food: " +str(food) + " Day(s) Water: " + str(water) + " Day(s)"
print "Current Survivors " + str(human)
if healthy <= -3 and healthy >= -1:
print "Current Survivors are " + ('\x1b[7;30;41m' + 'Nearly Dead' + '\33[3m')
if healthy == 0:
print "Current survivors " + ('\x1b[7;30;41m' + 'Are not healthy' + '\33[3m')
if healthy >= 1 and healthy <= 3:
print "Current Survivors are " + ('\x1b[7;32;43m' + 'Ok' + '\x1b[0m')
if healthy >= 3 and healthy <= 5:
print "Current Survivors are " + ('\x1b[7;32;43m' + 'Great' + '\x1b[0m')
if healthy >= 5 and healthy <= 7:
print "Current Survivors are " + ('\x1b[7;32;43m' + 'Excellent' + '\x1b[0m')
foodcon = support
watercon = support
food = food - support
water = water - support
print human
print support
print "You are consuming " + str(support) + " food and " + str(support) + " water per day"
if food - support <= 0 or water - support <= 0:
print('\x1b[7;30;41m' + 'You will not survive the next day.' + '\33[3m')
print "[M]issions [B]uilding [H]oard [E]nd Day"
resp = raw_input()
if 'M' in resp or 'm' in resp:
print "[F]ood [W]ater [S]urvivor"
resp = raw_input()
if 'F' in resp or 'f' in resp:
foodmis = pickfoodMission()
print "You go to a " + foodmis
foodcha = chanceFood()
if foodcha >= 14:
foodpick = foodPickup()
food = newfood
img = Image.open('food.png')
img.show()
print('\x1b[7;32;43m' + 'You are now at ' + str(newfood) + ' day(s) of food' + '\x1b[0m')
elif foodcha < 14:
print('\x1b[7;30;41m' + 'You come back empty handed.' + '\x1b[0m')
elif 'w' in resp or 'W' in resp:
watermis = pickwaterMission()
print "You go to a " + watermis
watercha = chancewater()
if watercha >= 14:
waterpick = waterPickup()
water = newwater
img = Image.open('water.png')
img.show()
print('\x1b[7;32;43m' + 'You are now at ' + str(newwater) + ' day(s) of water' + '\x1b[0m')
elif watercha <= 14:
print('\x1b[7;30;41m' + 'You come back empty handed.' + '\x1b[0m')
elif 's' in resp or 'S' in resp:
humanmis = picksurvivorMission()
print "You go to a " + humanmis
humancha = chancehuman()
if humancha >= 14:
humanpick = humanPickup()
human = newhuman
print('\x1b[7;32;43m' + 'You are now at ' + str(human) + ' survivor(s)' + '\x1b[0m')
img = Image.open('cats.jpg')
img.show()
elif humancha <= 14:
print('\x1b[7;30;41m' + 'You come back with no one else new.' + '\x1b[0m')
if 'B' in resp or 'b' in resp:
print "[F]ood"
You're never updating your support variable after you set it the first time so each time you print it out it's the same. Since support is dependent on human, you should either recalculate support every time human is updated or have a function like calculate_support() which calculates it when you need it.
As far as I can see at a quick glance you are only assigning value to the 'support' variable once in the code:
support = 0.1 * human
and I don't think this code gets to run again. Once support gets a value through this assignment statement it is not going to update even if you update the value of the 'human' variable.
def main():
print("You haved activated Weather Pro 3.0")
rain_inputs()
rain_calc()
def rain_inputs():
global rain
rain = []
for x in range(1, 13):
try:
rain_meter = float(input("What is the rainfall? "))
rain.append(rain_meter)
if x == 4:
print("8 more months to go!")
elif x == 7:
print("5 more months to go!")
elif x == 9:
print("2 more to go! Smash those keys!")
elif x == 13:
return
except Exception as err:
err = ("You should be putting in numbers!")
print(err)
rain_calc is supposed to calculate the total of all listed inputs.
def rain_calc():
rain_math =(rain[0] + rain[1] + rain[2] + rain[3])
rain_math2 =(rain[5] + rain[6] + rain[7] + rain[8])
rain_math3 =(rain[9] + rain[10] + rain[11] + rain[12])
rain_total =(rain_math + rain_math2 + rain_math3)
print(rain_total)
main()
The error occurs in rain-math3:
Programming/RainFall.py", line 30, in rain_calc rain_math3 =(rain[9] + rain[10] + rain[11] + rain[12])
IndexError: list index out of range
rain[12] is out of range because rain only has 12 elements in it. You missed rain[4], so you probably wanted this:
def rain_calc():
rain_math =(rain[0] + rain[1] + rain[2] + rain[3])
rain_math2 =(rain[4] + rain[5] + rain[6] + rain[7])
rain_math3 =(rain[8] + rain[9] + rain[10] + rain[11])
rain_total =(rain_math + rain_math2 + rain_math3)
print(rain_total)