How can I get this text variable to work? - python

This program is not working right. It seems to be unable to print the cars after "You have the following cars:"
How could I get the variables to change in the def game() section?
Here is a pastebin: http://pastebin.com/pjsuWRYs
import random
car1 = ("car1")
car2 = ("car2")
car3 = ("car3")
car4 = ("car4")
car5= ("car5")
car6 = ("car6")
car7= ("car7")
car8 = ("car8")
car9 = ("car9")
def game():
print ("You have the following cars:")
print (car1)
print (car2)
print (car3)
print (car4)
print (car5)
print (car6)
print (car7)
print (car8)
print (car9)
print ("You selected Grand Thief Auto")
gta = input ("To commit GTA type GTA")
if gta in ("gta", "Gta", "GTA", "a"):
chance = random.randint(0,100)
if chance <= 1:
print ("You stole a Bugatti Veryron")
car1 = ("Bugatti Veryron")
elif chance <= 5:
print ("You stole a Ferrari Spider")
car2 = ("Ferrari Spider")
elif chance <= 10:
print ("You stole a Audi Q7")
car3 = ("Audi Q7")
elif chance <= 15:
print ("You stole a BMW X6")
car4 = ("BMW X6")
elif chance <= 20:
print ("You stole a Jaguar X Type")
car5 = ("Jaguar X Type")
elif chance <= 25:
print ("You stole a Ford Mondeo")
car6 = ("Ford Mondeo")
elif chance <= 30:
print ("You stole a Audi A3")
car7 = ("Audi A3")
elif chance <= 35:
print ("You stole a Ford Fiesta")
car8 = ("Ford Fiesta")
elif chance <= 40:
print ("You stole a Skoda Octavia")
car9 = ("Skoda Octavia")
elif chance <= 100:
print ("You got caught!")
game()
game()

If you want to make the "car"s accessible in the functions, you must set them as global variables.
Try putting
global car1, car2, car3, car4, car5, car6, car7, car8, car9
before the print ("You have the following cars:") and after define game():
I would also suggest using lists or dictionaries instead of defining each variable by itself.
You could have:
cars = ["car1", "car2", "etc"]
# To change a value for "car2" for example, do this:
# List values (indexes) in Python are starting from 0
cars[1] = "Bugatti"
# To print the car name do:
print (cars[0])
print (cars[1])
# Etc.
or:
cars = { "car1" : "Bugatti", "car2" : "Ferarri", "car number" : "car name"}
# To change a value for "car2" for example, do this:
cars["car2"] = "Bugatti"
# And to print the car names:
print (cars["car1"])
print (cars["car2"])
If you chose to use lists or dictionaries, you will have to set the cars variable global as well
To make things look nicer, I would suggest changing input ("To commit GTA type GTA") to (input ("To commit GTA type GTA: ").lower() which will add an extra space for "beauty" and make the input case-insensitive
I would also add newlines (\n) or empty print () statements to make the output prettier and easier to understand. This will just add an empty line wherever you want it to be.

Related

Error with a player turn ending loop in the Zombie Dice game

I'm trying to develop a code for the zombie dice game.
My problem is when the first player replies that he doesn't want to continue playing.
The game ends and I can't get the second player to play. Can someone help me?
import random
print("========== ZOMBIE DICE (PROTÓTIPO SEMANA 4) ==========")
print("========= WELCOME TO THE ZOMBIE DICE GAME! ========")
numeroJogadores = 0
while numeroJogadores < 2:
numeroJogadores = int(input("Enter the number of players: "))
print(numeroJogadores)
if numeroJogadores < 2:
print("NOTICE: You must have at least 2 players to continue!")
listaJogadores = []
for i in range(numeroJogadores):
nome = str(input("\nEnter player name: " + str(i+1) + ": "))
listaJogadores.append(nome)
print(listaJogadores)
dadoVerde = ("brain", "steps", "brain", "shot", "steps", "brain")
dadoAmarelo = ("shot", "steps", "brain", "shot", "steps", "brain")
dadoVermelho = ("shot", "steps", "shot", "brain", "steps", "shot")
listaDados = [dadoVerde, dadoVerde, dadoVerde, dadoVerde, dadoVerde, dadoVerde,
dadoAmarelo, dadoAmarelo, dadoAmarelo, dadoAmarelo,
dadoVerde, dadoVermelho, dadoVermelho]
print("\nSTARTING THE GAME...")
jogadorAtual = 0
dadosSorteados = []
tiros = 0
cerebros = 0
passos = 0
while True:
print("PLAYER TURN: ", listaJogadores[jogadorAtual])
for i in range (3):
numeroSorteado = random.randint(0, 12)
dadoSorteado = listaDados[numeroSorteado]
if (dadoSorteado == dadoVerde):
corDado = "Green"
elif (dadoSorteado == dadoAmarelo):
corDado = "Yellow"
else:
corDado = "Red"
print("Dice Drawn: ", corDado)
dadosSorteados.append(dadoSorteado)
print("\nThe faces drawn were: ")
for dadoSorteado in dadosSorteados:
numeroFaceDado = random.randint(0,5)
if dadoSorteado[numeroFaceDado] == "brain":
print("- brain (you ate a brain)")
cerebros = cerebros + 1
elif dadoSorteado[numeroFaceDado] == "tiro":
print("- shot (you got shot)")
tiros = tiros + 1
else:
print("- steps (a victim escaped)")
passos = passos + 1
print("\nCURRENT SCORE: ")
print("brins: ", cerebros)
print("shots: ", tiros)
if cerebros >= 13:
print("Congratulations, you've won the game!")
break
elif tiros >= 3:
print("You lost the game!")
break
else:
continuarTurno = str(input("\nNOTICE: Do you want to continue playing dice? (y=yes / n=no)")).lower()
if continuarTurno == "n":
jogadorAtual = jogadorAtual + 1
dadossorteados = 0
tiros = 0
cerebros = 0
passos = 0
if jogadorAtual > numeroJogadores:
print("Finalizing the game prototype")
else:
print("Starting another round of the current turn")
dadossorteados = []
print("======================================================")
print("===================== END OF THE GAME ====================")
print("======================================================")
Does anyone know what I'm doing wrong?
I'm new as a programmer. If anyone knows how to help me with this problem, I would be grateful.
EDIT: Well now the code just works. I can switch players just fine, but if you go through all the characters it crashes again since jogadorAtual gets too big for listaJogadores. I don't quite understand the game, but assuming you want to start back with the first player, an elegant way you can accomplish that is by doing modulus with the % operator, which divides two numbers but returns the remainder. If you divide the number of players by the size of listaJogadores, you'll always get a number inside listaJogadores's range.
# Change this...
print("PLAYER TURN: ", listaJogadores[jogadorAtual])
# ...to this
print("PLAYER TURN: ", listaJogadores[jogadorAtual % len(listaJogadores)])
If that's not what you need for your game, let me know.
Original answer: Is the game ending or is it crashing? When I run the game, it always crashes with:
File "C:\Users\me\Desktop\Untitled-1.py", line 56, in <module>
diceDrawns.append(diceDrawn)
AttributeError: 'int' object has no attribute 'append'
This is because after looping, you try to do diceDrawns.append(), but you've already replaced the diceDrawns list with an integer on line 87. I'm not sure if you meant to replace diceDrawn instead, but that's definitely the source of the problem.
An unrelated note: You can do += as a shorthand way to increment a variable by a certain amount, so you can replace a lot of instances of things like currentPlayer = currentPlayer + 1 with currentPlayer += 1, and the same can be done with any operator, so you could also do things like -= or *=

Having Trouble With: Tuple and Int?

So I am making a camel game and I get a weird error that says
"TypeError: '>' not supported between instances of 'tuple' and 'int'"
and I am not sure what this means, I have posted before and I will state this again I am a beginner coder. Thank you to whoever helps here is the code and I will put a comment where the error is that you!
import random
done = False
milesTraveled = 0
thirst = 0
camelTired = 0
nativesDis = -20
canteens = 5
print('''
Welcome to Camel!
You have stolen a camel to make your way across the great Mobi desert.
The natives want their camel back and are chasing you down! Survive your
desert trek and outrun the natives. ''')
while not done:
oasis = (1,21)
if oasis == 4:
print("You found an oasis!")
canteens = 5
thrist = 0
if thirst > 6:
print("You died of thrist!")
spc = input("")
done = True
if thirst > 4:
print("You are thirsty")
#under here
if camelTired > 8:
print("Your camel DIED!")
spc = input("")
done = True
if camelTired > 5:
print("Your camel is getting tired")
if nativesDis == milesTraveled + 20:
print('The natives caught up with you!')
spc=input("")
done = True
if milesTraveled == 200:
print('You Win!')
spc = input("")
done = True
print('''
A. Drink from your canteen.
B. Ahead full speed.
C. Stop and rest.
D. Status check.
Q. Quit ''')
user_choice = input("")
if user_choice.upper() == 'Q':
done = True
elif user_choice.upper() == 'D':
print('''
Miles Traveled: 0
Drinks In Canteen:''',canteens,'''
Thirstyness:''',thirst,'''
The Natives Are 20 Miles Behind You''')
elif user_choice.upper() == 'C':
camelTired = 0
nativesDis = random.randint(7,15)
elif user_choice.upper() == 'B':
milesTraveled = random.randint(10,22)
print("You traveled",milesTraveled,"miles!")
thirst + 1
camelTired = (1,3)
nativesDis = (7,14)
elif user_choice.upper() == 'A':
if canteens > 0:
canteens = canteens - 1
thirst
= 0
You need to take the number out of the tuple and into a variable that is also an integer.
There are multiple integers in your tuple.
You can access them in the following way:
some_tuple_of_integers = (12, 432, 345)
index_zero_integer = some_tuple_of_integers[0]
index_one_integer = some_tuple_of_integers[1]
index_two_integer = some_tuple_of_integers[2]
print(index_zero_integer)
print(index_one_integer)
print(index_two_integer)
Or just straight from the tuple itself without creating a new variable (This can sometimes get unreadable when working with lots of indexes and tuples).
print(some_tuple_of_integers[0])
print(some_tuple_of_integers[1])
print(some_tuple_of_integers[2])
You can then easily compare between other values.
If, for example you have a string from the tuple that you need to compare with another integer, you can change it by doing:
index_two_integer = int(index_two_integer)

Python 2.7.3 Code Loops Without a While Loop

I am relatively new to programming, so don't be surprised if there are some minor hiccups in the code, but the problem that is happening is that this code seems to loop itself, the whole thing and I don't understand why. I looked at the actual code that runs this function but it seemed fine. So I cannot find any error in this code that makes it loop itself. (If the problem isn't in this code then the looping code it beneath it)
def thebeast(yourhp):
foe = "Thisisirrelevant"
enemy = int(random.randint(1,4))
if enemy == 1:
foe = "skeleton"
elif enemy == 2:
foe = "man with crazy eyes"
else:
foe = "dog, a big and scary dog"
monsteract = 1
dmg = 0
print "-=~-=~-=~-=~-=~-=~-=~-=~-=~-=~-=~-=~"
time.sleep(0.1)
print " C O M B A T"
time.sleep(0.1)
print "-=~-=~-=~-=~-=~-=~-=~-=~-=~-=~-=~-=~"
time.sleep(0.1)
print "You encounter a " + foe
time.sleep(0.5)
while monsteract == 1:
comb = str(input("What do you do to the " + foe + "?" + " Do you feel like jabbing it or stabbing it?"))
if comb in ["s", "S", "Stab", "STAB", "stab"]:
if spear == 1:
dmg = int(random.randint(1,4))
elif sword == 1:
dmg = int(random.randint(1,3))
else:
dmg = int(random.randint(1,5))
elif comb in ["j", "J", "Jab", "JAB", "jab"]:
if spear == 1:
dmg = int(random.randint(1,3))
elif sword == 1:
dmg = int(random.randint(1,4))
else:
dmg = int(random.randint(1,5))
if dmg == 1:
print "You slay the " + foe + " with graceful ease"
time.sleep(0.5)
monsteract = 0
else:
enemydmg = int(random.randint(1,3))
print "The " + foe + " strikes you for " + str(enemydmg) + " damage"
time.sleep(0.3)
print "That didn't work out as planned, but you pull yourself together and prepare to strike the " + foe
time.sleep(0.3)
yourhp = yourhp - enemydmg
if yourhp < 0:
yourhp = 0
print "You have " + str(yourhp) + " health left"
time.sleep(0.3)
if yourhp < 1:
print "The " + foe + " has slain you, well done, you're dead, on the bright side the innocent "
print foe + " is still alive! Every life counts, even that of a " + foe + "."
monsteract = 0
return thebeast(yourhp)
Looping code:
def randomevents(yourhp):
turn = 10
while turn > 0:
time.sleep(0.1)
happening = int(random.randint(1,6))
time.sleep(0.1)
if yourhp < 1:
turn = 0
print "You managed to escape the dungeon, by dying that is"
elif happening == 1:
turn = turn - 1
thebeast(yourhp)
elif happening == 2:
item(sword, spear)
turn = turn - 1
elif happening in [3, 4, 5]:
friend()
turn = turn - 1
print "Well done! You escaped the dungeon! (Either by running out of it, or by having your soul sent to another world)"
useless = str(input("Are you satsified with yourself?: "))
Thank you!
Look at your return statement at the end of thebeast. At the end of the function, you call the function again! Since this happens every time you call it, you will never stop calling it (until you hit the maximum recursion depth). Considering that you don't capture the return value of thebeast in randomevents, you should consider it not returning anything.

Local variable referenced before assignment (don't want to use global)

I'm learning Python using "Learn Python the hard way" and am currently making a simple game
Following the book's guidelines, each "room" is to be it's own function and herein lies my problem, I have some variables that need to be accessed by all functions. e.g. Current_health, armor, strength stat.
I have looked at the previous questions on here (that I actually understood) and the only solution seems to be to declare it as a global variable within the function, but as I'm going to have 20+ rooms (functions) it seems a bit silly to declare them all every time
The other option is to pass the variable when calling the function, but as I need to put through 8 variables each time that also seems impractical. Any help would be greatly appreciated. I'll paste the code below in case it helps (the game is far from finished so some may not make sense)
Right now the start() works because of my global variables but I'll run into the error as soon as it tries to run shadow_figure() because of the wep_dam reference
from sys import exit
str = 0
wep_dam = 0
dam = str + wep_dam
cha = 0
sne = 0
arm = 0
max_life = 10
points_remaining = 0
def shadow_figure():
print "\n\nYou approach the figure, who remains silent."
print "As you get closer you realise he has bag at his feet."
print "Mysterious figure: \"You may choose only one.\""
print "You look into the bag, and see a shiny sword on top of a large steel shield."
ans = raw_input("Do you: \n1. Take the sword \n2. Take the shield \n3. Take the whole bag and run \n4. Walk away without taking anything\n> ")
if ans == "1":
print "The sword gives you an extra 3 damage"
wep_dam += 3
exit_beach()
elif ans == "2":
print "The shield gives you 3 armor, but it's so heavy it reduces your sneak by 1"
arm += 3
sne -= 1
def beach():
print "\n\nYou wake up on a beach with no idea how you got there. \nYou see a shadowy figure close to the water."
ans = raw_input("Do you: \n1. Approach him \n2. Go the other way\n> ")
if ans == "1":
shadow_figure()
elif ans == "2":
exit_beach()
else:
print "Please enter either 1 or 2"
def reset_stats():
str = 0
wep_dam = 0
dam = str + wep_dam
cha = 0
sne = 0
arm = 0
max_life = 10
points_remaining = 10
print "\n\n\n\nGame Reset\n\n\n\n"
def start():
global str
global wep_dam
global dam
global cha
global sne
global arm
str = 0
wep_dam = 0
dam = str + wep_dam
cha = 0
sne = 0
arm = 0
max_life = 10
points_remaining = 0
print "You are an adventurer, your stats are currently:"
print "Strength: %d \nCharisma: %d \n Sneak: %d" % ( str, cha, sne)
print "Strength determines your damage, charisma determines your chance of pursuasion, \nand sneak determines whether or not you can go get past enemies without being detected"
print "you have 10 points available to spend, to spend a point, simply type the number which corresponds\nwith the skill and hit enter"
print "\n\n1. Strength \t2. Charisma \t3. Sneak\n"
points_remaining = 10
while points_remaining > 0:
ans = raw_input("Choose a skill: ")
if ans == "1":
str += 1
points_remaining -= 1
print "Strength is now %d" % ( str)
print "%d points remaining\n" % ( points_remaining)
elif ans == "2":
cha += 1
points_remaining -= 1
print "Charisma is now %d" % ( cha)
print "%d points remaining\n" % ( points_remaining)
elif ans == "3":
sne += 1
points_remaining -= 1
print "Sneak is now %d" % ( sne)
print "%d points remaining\n" % (points_remaining)
else:
print "Error, please enter a number from 1 to 3\n"
print "Your stats are now: "
print "Strength: %d \nCharisma: %d \n Sneak: %d\n\n" % ( str, cha, sne)
print "Is this OK? Or would you like to restart?\n"
ans = raw_input("1. Continue \n2. Restart\n> ")
if ans == "1":
print "Game will now begin...."
beach()
elif ans == "2":
ans = raw_input("Are you sure? Yes/No\n> ")
ans = ans.lower()
if ans == "yes":
reset_stats()
start()
else:
beach()
else:
print "Error, please enter 1 or 2"
start()
You may wrap your globals in class:
class Player:
str = 0
wep_dam = 0
dam = str + wep_dam
cha = 0
sne = 0
arm = 0
max_life = 10
points_remaining = 0
and access its fields in rooms like this: Player.arm += 3

Repeating a block of "If" statement

I'm trying to make a text based game, and to make my fighting mechanics I have to repeat an if statement until you or the monster dies.
Here it is --
Ph would stand for Player health, str is player strength, mdam is monster damage, mstr is monster strength, monsterh is monsterhealth, the random.random() is the attack bonus you receive (Adding onto this, is there any way to round the number to one or no decimal places?) Thank you! :D
if fight == "A" and ph > 0:
damage = (str) + (random.random())
monsterh = 6
mstr = 0.9
monsterh = (monsterh) - (damage)
print(damage)
print(damage - str)
print('You attack the monster. You deal %s damage.' % damage )
time.sleep(3)
if monsterh > 0:
mstr = 0.9
mdam = (mstr) + (random.random())
print('The monster attacks you!')
ph = ph - mstr
print("You get hit %s" % mdam )
else:
xpgain = damage + 5
print("You won! You've gained %s XP!" % xpgain)
I would wrap your combat seen in a while loop. For example:
while (ph > 0 or monsterh > 0)
# combat rules
# Check who died and move on from there
if (ph > 0)
# next thing the player does
else
# print "You died"
In regards to rounding, there are multiple options depending on exactly what you want to do: python: getting only 1 decimal place
To round the value you get from
random.random()
you can do
round(random.random(),1)
to round to 1 decimal place, or if you want to get rid of decimals, replace
random.random()
with
int(random.random())
As for repeating the if statement, you can put it into a loop which will break when a condition is met
while true:
if fight == "A" and ph > 0:
damage = (str) + (int(random.random()))
monsterh = 6
mstr = 0.9
monsterh = (monsterh) - (damage)
print(damage)
print(damage - str)
print('You attack the monster. You deal %s damage.' % damage )
time.sleep(3)
elif ph<=0 or fight!="A":
print("You lose!")
break
if monsterh > 0:
mstr = 0.9
mdam = (mstr) + (int(random.random()))
print('The monster attacks you!')
ph = ph - mstr
print("You get hit %s" % mdam )
else:
xpgain = damage + 5
print("You won! You've gained %s XP!" % xpgain)
break
Although you wouldn't need the fight!="A" since I don't think you change the value of fight at all.
Also you don't have to do
mdam = (mstr) + (int(random.random()))
You can just do
mdam = mstr+int(random.random())
This above ^ applies to other places in your code as well. If you have any questions please feel free to ask.

Categories

Resources