Well here's the problem my game() function wont go to my firstlevel() function and just keeps says process exited with exit code 0 And I have no clue why I even tried changing the function name And still no luck I truly have no clue what to do I am just a beginner...
code:
import winsound
import random as ran
import pickle
profile = {}
def fightsound():
winsound.PlaySound('fight2.wav', winsound.SND_FILENAME | winsound.SND_ASYNC)
def ranking():
if profile['xp'] >= 20:
profile['level'] += 1
if profile['xp'] >= 50:
profile['level'] += 1
if profile['xp'] >= 100:
profile['level'] += 1
game()
else:
game()
else:
game()
else:
game()
def play_bgmusic():
winsound.PlaySound('mk.wav', winsound.SND_FILENAME | winsound.SND_ASYNC)
def load_game():
global profile
profile = pickle.load(open("save.txt", "rb"))
game()
def fatality():
winsound.PlaySound('fatal2.wav', winsound.SND_FILENAME | winsound.SND_ASYNC)
def game():
global profile
print("Player: " + profile['player'])
print("XP: ", profile['xp'])
print("Level: ", profile['level'])
print("win: ", profile['win'])
print("loss: ", profile['loss'])
if profile['level'] >= 1:
print("1.) The ogre king...")
if profile['level'] >= 2:
print("2.) The realm of the witch!")
y = input("Select an option -> ")
if y == 1:
firstlevel()
def firstlevel():
global profile
fightsound()
enemyhp = 50
hp = 100
while enemyhp > 0:
print("Your hp: ", hp, " Enemy hp: ", enemyhp)
input("Press enter to attack...")
damage = ran.randint(0, 25)
enemyhp -= damage
damage = ran.randint(0, 25)
hp -= damage
if hp <= 0:
profile['xp'] += 5
profile['loss'] += 1
pickle.dump(profile, open("save.txt", "wb"))
print("You died, press enter to continue...")
game()
fatality()
profile['xp'] += 10
profile['win'] += 1
pickle.dump(profile, open("save.txt", "wb"))
input("You win! Press enter to continue...")
ranking()
def new_game():
global profile
player = input("Enter a player name -> ")
profile['player'] = player
profile['xp'] = 0
profile['level'] = 1
profile['win'] = 0
profile['loss'] = 0
pickle.dump(profile, open("save.txt", "wb"))
game()
def main():
play_bgmusic()
print(20 * "-")
print("| |")
print("| 1.) New Game |")
print("| 2.) Load Game |")
print("| 3.) Credits |")
print("| |")
print(20 * "-")
x = int(input("Select an option -> "))
if x == 1:
new_game()
if x == 2:
load_game()
if x == 3:
pass
main()
The problem is these three lines:
y = input("Select an option -> ")
if y == 1:
firstlevel()
When you get input, it will come back as a string. You are comparing the string "1" to the integer 1. The two are not equal, so firstlevel() is never called.
You should convert the string to an integer, or change the integer to a string, so that you are comparing two objects of the same type.
Gonna bet it's cause y isn't what you think it is. Try printing it out or putting a breakpoint on it to make sure it is an integer with value 1.
The problem is here:
y = input("Select an option -> ")
if y == 1:
input() returns a string, so it will never be equal to the integer 1. Simply use int() on y before your comparison and you'll be good to go.
Related
I have been trying to make a black jack game, and have come to a point where three players roll the dice to decide who goes first. I need to check if player_a rolled higher than both player_b & player_c. I tried: if a_roll > b_roll & c_roll:, but that just adds the b and c rolls. I feel like there is an easy way to do this but i cannot figure it out.
here is my full program so far:
import random
print("Welcome to Max's BlackJack v1.0")
print(" _____")
print(" |A . | _____")
print(" | /.\ ||A ^ | _____")
print(" |(_._)|| / \ ||A _ | _____")
print(" | | || \ / || ( ) ||A_ _ |")
print(" |____V|| . ||(_'_)||( v )|")
print(" |____V|| | || \ / |")
print(" |____V|| . |")
print(" |____V|")
print("")
print("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-")
ready = input("To start type ready: ")
if ready == "ready":
print("")
print("")
mode = input("Single Player(1) or Multiplayer(2)... ")
if mode == "1":
print("Hello their Sir, Welcome to Back Jack. ")
print("")
print("These are your competitors... ")
player_a = random.randint(1,3)
player_b = random.randint(1,3)
player_c = random.randint(1,3)
#first dude
if player_a == 1:
player_a = ("Tessa")
if player_a == 2:
player_a = ("Britney")
if player_a == 3:
player_a = ("zack")
#seccond dude
if player_b == 1:
player_b = ("Donald")
if player_b == 2:
player_b = ("Bruce")
if player_b == 3:
player_b = ("Colin")
#third dude
if player_c == 1:
player_c = ("leven")
if player_c == 2:
player_c = ("Joe")
if player_c == 3:
player_c = ("Brady")
print("")
print(player_a + "," + player_b + "," + player_c)
print("")
#game code starts here
start2 = input("Press ENTER ")
print("DEALER: Lets begin. ")
print("DEALER: To decide who goes first we each roll the dice, whomever gets the highest number goes first")
print("")
a_roll = random.randint(1,12)
b_roll = random.randint(1,12)
c_roll = random.randint(1,12)
print(player_a + " rolled a " + str(a_roll))
print(player_b + " rolled a " + str(b_roll))
print(player_c + " rolled a " + str(c_roll))
#filter results
if a_roll > b_roll & c_roll:
print("bruh")
if b_roll > a_roll & c_roll:
print("test")
print(a_roll + b_roll)
I might use if b < a > c: (if I had three variables instead of a list or so and wanted to write separate code for each case, which I almost certainly wouldn't).
The & operatior is a "bitwise and" operator which does a logical AND operation on the bits of the numbers. The operator you actually need is "and". The correct way to do this is to first check is a is higher than b and then check if a is higher than c like this:
if a > b and a > c:
Hi all programming masters! Im working on a python guessing game and want to change the format of my print to file from "name: win 0: loss 0: guess 0", to "Name | Win or loss (not both) | number of guesses". Im not sure how to make it print the win OR loss, do i need another if statement to print to the txt file?
import random
print("Number guessing game")
name = input("Hello, please input your name: ")
win = 0
loss = 0
guesses = 0
diceRoll = random.randint(1, 6)
if diceRoll == 1:
print("You have 1 guess.")
if diceRoll == 2:
print("You have 2 guesses.")
if diceRoll == 3:
print("You have 3 guesses.")
if diceRoll == 4:
print("You have 4 guesses.")
if diceRoll == 5:
print("You have 5 guesses.")
if diceRoll == 6:
print("You have 6 guesses.")
elif diceRoll != 1 and diceRoll != 2 and diceRoll != 3 and diceRoll != 4 and diceRoll != 5 and
diceRoll != 6:
print("Invalid input!")
number = random.randint(1, 3)
chances = 0
print("Guess a number between 1 and 100:")
while chances < diceRoll:
guess = int(input())
if guess == number:
print("Congratulation YOU WON!!!")
win += 1
guesses = guesses + 1
break
elif guess < number:
print("Your guess was too low")
guesses = guesses + 1
else:
print("Your guess was too high")
guesses = guesses + 1
chances += 1
else:
print("YOU LOSE!!! The number is", number)
loss += 1
print(name)
print("win: "+str(win))
print("loss: "+str(loss))
stat = open("Statistics.txt", "a")
stat.write(name + ":" + " win: "+str(win) + " loss: " +str(loss) +" guesses: "+str(guesses)),
stat.close()
You can solve the critical part using the ternary statement, an "if-then-else" expression, like this:
result = "Win" if win == 1 else "Loss"
stat.write((name + ":" + result + " guesses: "+str(guesses))
Beyond this, I strongly recommend that you look up "Python output format", so you can improve your range of expression. You won't have to keep doing string construction for your output statements.
Hi i am unsure on how to add a second player for this number guessing game whereby after player 1 makes a guess, then player 2 makes a guess. like between every guess. I am only able to make it so that the player 2 guesses after player 1 guesses finish all of his choices(code below) if anyone is able to tell me if what i am looking for is possible or if there is any advice, it would be greatly appreciated. thanks in advance.
def main():
import random
n = random.randint(1, 99)
chances = 5
guess = int(input("Player 1 please enter an integer from 1 to 99, you have 5 chances: "))
while n != "guess":
chances -=1
if chances ==0:
print("out of chances")
break
if guess < n:
print("guess is low")
guess = int(input("Enter an integer from 1 to 99: "))
elif guess > n:
print ("guess is high")
guess = int(input("Enter an integer from 1 to 99: "))
else:
print("you guessed it")
break
import random
n1 = random.randint(1, 99)
chances1 = 0
guess1 = int(input("Player 2 please enter an integer from 1 to 99, you have 5 chances "))
while n1 != "guess":
chances1 +=1
if chances1 ==5:
print("out of chances")
break
if guess1 < n1:
print("guess is low")
guess1 = int(input("Enter an integer from 1 to 99: "))
elif guess > n1:
print ("guess is high")
guess1 = int(input("Enter an integer from 1 to 99: "))
else:
print("you guessed it")
break
retry=input("would you like to play again? (please choose either 'yes' or 'no')")
if retry == "yes":
main()
else:
print("Okay. have a nice day! :D ")
main()
to achieve this I would use a while loop and a variable to detect which players turn it is. Like this:
import random
random_number = random.randint(1, 99)
player_chances = 5
current_player = 1
while player_chances > 0:
if current_player == 1:
guess = int(input("Player 1 please enter an integer from 1 to 99, {} chances left. ".format(player_chances)))
player_chances -= 1
current_player = 2
if guess < random_number:
print("->guess is too low")
elif guess > random_number:
print("->guess is too high")
else:
print("CONGRATULATIONS! You guessed it! Player 1 wins!")
break
else:
guess = int(input("Player 2 please enter an integer from 1 to 99, {} chances left. ".format(player_chances)))
player_chances -= 1
current_player = 1
if guess < random_number:
print("->guess is too low")
elif guess > random_number:
print("->guess is too high")
else:
print("CONGRATULATIONS! You guessed it! Player 1 wins!")
break
print("####")
print("Out of chances! The number was {}.".format(random_number))
print("####")
To make this possible in an efficient way I would have created a player class as such:
class Player:
def __init__(self,name):
self.name = name
self.getNumberOfTrys = 0
self.guess = 0
def getNumberOfTrys(self):
return self.getNumberOfTrys
def getPlayerName(self):
return self.name
def play(self):
try:
self.guess = int(input("Enter an integer from 1 to 99: "))
self.getNumberOfTrys+=1
return self.guess
except Exception as error:
print(error)
return None
this class is responsible to create the player with the number of tries,his guess and his name.
the logic will be going through the list of players (you can add as much as you want) and perform the game logic as follows:
import random
p1 = Player("Player 1")
p2 = Player("Player 2")
players = []
players.append(p1)
players.append(p2)
n1 = random.randint(1, 99)
NUMBER_OF_TRIES = 5
print(n1)
while players:
for player in players:
print(player.getPlayerName() + " turn, you have " + str(NUMBER_OF_TRIES - player.getNumberOfTries) + " turns left")
guess = player.play()
if guess < n1:
print("guess is low")
elif guess > n1:
print ("guess is high")
else:
print(player.getPlayerName()," you guessed it")
players.clear()
break
if player.getNumberOfTries == NUMBER_OF_TRIES:
print(player.getPlayerName(), " out of chances")
players.remove(player)
Basically, create a list of players then go through each one and apply the game logic (getting input, comparing and checking number of tries)
after a player loses, we should remove him from the list and if a player wins we can clear the list and thus exiting the game.
Here is the full code:
class Player:
def __init__(self,name):
self.name = name
self.getNumberOfTries = 0
self.guess = 0
def getNumberOfTries(self):
return self.getNumberOfTries
def getPlayerName(self):
return self.name
def play(self):
try:
self.guess = int(input("Enter an integer from 1 to 99: "))
self.getNumberOfTries+=1
return self.guess
except Exception as error:
print(error)
return None
import random
p1 = Player("Player 1")
p2 = Player("Player 2")
players = []
players.append(p1) #addding player
players.append(p2)
n1 = random.randint(1, 99)
NUMBER_OF_TRIES = 5
print(n1) #for debug
while players:
for player in players:
print(player.getPlayerName() + " turn, you have " + str(NUMBER_OF_TRIES - player.getNumberOfTries) + " turns left")
guess = player.play()
if guess < n1:
print("guess is low")
elif guess > n1:
print ("guess is high")
else:
print(player.getPlayerName()," you guessed it")
players.clear() # exit game
break #exit loop
if player.getNumberOfTries == NUMBER_OF_TRIES:
print(player.getPlayerName(), " out of chances")
players.remove(player)
Hope I got your question right, and excuse me If there is any errors or typos, I just created something fast that you can be inspired by. I highly suggest you get into OOP, it very simple and it can make your life much easier :)
All the best!
I'm currently creating a card came in python and in creating my draft() function used for drafting the player a deck I encountered a problem with my while loop.
I can't seem to figure out why the while loop doesn't loop.
If anyone can figure out why please do let me know.
player_deck = []
#draft function to draft a player deck should be used when starting game
def draft():
while len(player_deck) < 10:
random_variable = random.random()
if random_variable < 0.2:
print("Your choise is between Drake and Recovery")
print("---> " + drake.description)
print("---> " + recovery.description)
player_choice = input("Which do you choose: ")
if player_choice.lower() == "drake":
player_deck.append(drake)
if player_choice.lower() == "recovery":
player_deck.append(recovery)
else:
return "Please pick one of the two"
if random_variable >= 0.2 and random_variable <= 0.999999:
print("Your choise is between Blast Cone and Eminem")
print("---> " + blast_cone.description)
print("---> " + eminem.description)
player_choice = input("Which do you choose: ")
if player_choice.lower() == "blast cone":
player_deck.append(blast_cone)
if player_choice.lower() == "eminem":
player_deck.append(eminem)
else:
return "Please pick one of the two"
return player_deck
print(draft())
The while loop does not repeat because the last return exits the loop before it has a chance to repeat:
def draft():
while len(player_deck) < 10:
# bla
# bla
return player_deck
print(draft())
I assume you wanted indent the return differently, maybe
def draft():
while len(player_deck) < 10:
# bla
# bla
return player_deck
print(draft())
Your return statement is inside he while loop. As soon as python hits it, the function ends. It should be moved outside of the while loop. Here is the code:
player_deck = []
#draft function to draft a player deck should be used when starting game
def draft():
while len(player_deck) < 10:
random_variable = random.random()
if random_variable < 0.2:
print("Your choise is between Drake and Recovery")
print("---> " + drake.description)
print("---> " + recovery.description)
player_choice = input("Which do you choose: ")
if player_choice.lower() == "drake":
player_deck.append(drake)
if player_choice.lower() == "recovery":
player_deck.append(recovery)
else:
return "Please pick one of the two"
if random_variable >= 0.2 and random_variable <= 0.999999:
print("Your choise is between Blast Cone and Eminem")
print("---> " + blast_cone.description)
print("---> " + eminem.description)
player_choice = input("Which do you choose: ")
if player_choice.lower() == "blast cone":
player_deck.append(blast_cone)
if player_choice.lower() == "eminem":
player_deck.append(eminem)
else:
return "Please pick one of the two"
return player_deck
I am trying to make first function, opt1(), make health go down by 50 points however for some reason it doesn’t work. The code works when not in a function.
The line that doesn’t work specifically: health = int(health) - 50
import random
health = "100"
p = "1"
def opt1():
print("Du förlorade striden")
health = int(health) - 50
print(health)
def opt2():
print("hej2")
def opt3():
print("hej3")
q = [opt1, opt2, opt3]
ind = random.randint(0,len(q)-1)
print("you have ", p, " potions")
print("Your health is ", health,)
while True:
print("Commands: Add, drink, sleep, fight, quest")
a = input("Enter a command: ")
if a == "add":
health = int(health)
p = int(p) + 1
print("you have ", p, " potions")
print("Your health is ", health,)
if a == "fight":
q[ind]()
So I have changed the health variable to an int.
And add the global to the function:
import random
health = 100
p = "1"
def opt1():
global health
print("Du förlorade striden")
health -= 50
print(health)
def opt2():
print("hej2")
def opt3():
print("hej3")
q = [opt1, opt2, opt3]
ind = random.randint(0,len(q)-1)
print("you have ", p, " potions")
print("Your health is ", health,)
while True:
print("Commands: Add, drink, sleep, fight, quest")
a = input("Enter a command: ")
if a == "add":
health = int(health)
p = int(p) + 1
print("you have ", p, " potions")
print("Your health is ", health,)
if a == "fight":
q[ind]()
In addition, you can read more on scoping in Python here.
Hope this helps you!
def opt1():
inside opt1 you should declare variable that you are giving into a function.
for example:
def opt1(health):