def and return error in python2 - python-3.x

Hey I'm working on a console game and I have a problem.Firstly the program should work as follows:
User chooses an attack power,
an attack with magnitude M will be successful with a chance of (100-M)%. That is, higher magnitude means higher risk of missing it. For instance, if M is 30, the chance of succeeding would 70%, whereas M if 10, the probability of succeeding would be 90%.If the attack is succesfull hp will decrease and the program will display hp's of players.I wrote something:
import random
def attack1():
hp2=100
chance_of_damaging=random.randint(0,100)
print "your chance of damaging", chance_of_damaging
while True:
attack_magnitute=input("Choose your attack magnitude between 1 and 50: ")
if attack_magnitute > 50:
print "The attack magnitude must be between 1 and 50."
elif attack_magnitute < 1:
print "The attack magnitude must be between 1 and 50."
else:
break
while True:
if chance_of_damaging > attack_magnitute:
print "attack is succesful"
hp2=hp2-attack_magnitute
return hp2
else:
print "attack is unsuccesful"
return hp2
print attack1()
def attack2():
hp1=100
chance_of_damaging=random.randint(0,100)
print "your chance of damaging", chance_of_damaging
while True:
attack_magnitute=input("Choose your attack magnitude between 1 and 50: ")
if attack_magnitute > 50:
print "The attack magnitude must be between 1 and 50."
elif attack_magnitute < 1:
print "The attack magnitude must be between 1 and 50."
else:
break
while True:
if chance_of_damaging > attack_magnitute:
print "attack is succesful"
hp1=hp1-attack_magnitute
return hp1
else:
print "attack is unsuccesful"
return hp1
print attack2()
The program should continue to run until one of the hp values is equal zero
When I try to call the hp1 or hp2 variable, the value is deleted.
Can someone help me with where I made mistakes?I have to submit my project in 30 hours.Thanks in advance.

Look at the new main funtion at the bottom, the hp values are passed in and returned instead of being reinitialized at the beginning of the attack functions. The loop continues until one of the hps is <= 0
import random
def attack1(current_hp):
hp2=current_hp
chance_of_damaging=random.randint(0,100)
print "your chance of damaging", chance_of_damaging
while True:
attack_magnitute=input("Choose your attack magnitude between 1 and 50: ")
if attack_magnitute > 50:
print "The attack magnitude must be between 1 and 50."
elif attack_magnitute < 1:
print "The attack magnitude must be between 1 and 50."
else:
break
while True:
if chance_of_damaging > attack_magnitute:
print "attack is succesful"
hp2=hp2-attack_magnitute
return hp2
else:
print "attack is unsuccesful"
return hp2
def attack2(current_hp):
hp1=current_hp
chance_of_damaging=random.randint(0,100)
print "your chance of damaging", chance_of_damaging
while True:
attack_magnitute=input("Choose your attack magnitude between 1 and 50: ")
if attack_magnitute > 50:
print "The attack magnitude must be between 1 and 50."
elif attack_magnitute < 1:
print "The attack magnitude must be between 1 and 50."
else:
break
while True:
if chance_of_damaging > attack_magnitute:
print "attack is succesful"
hp1=hp1-attack_magnitute
return hp1
else:
print "attack is unsuccesful"
return hp1
def main():
hp1, hp2 = (100,100)
while hp1 > 0 and hp2 > 0:
hp1 = attack1(hp1)
hp2 = attack2(hp2)
main()
EDIT:
If you want to print out the final state of hp1 and hp2 make your def main() like this:
def main():
hp1, hp2 = (100,100)
while hp1 > 0 and hp2 > 0:
hp1 = attack1(hp1)
hp2 = attack2(hp2)
print "Final State of hp1: " + str(hp1)
print "Final State of hp2: " + str(hp2)

Related

Number Guessing game Computer Playing

I have created this game. User is giving a number from 1 to 100. Computer is trying to guess it. User is giving hint to computer to go lower or go higher. I am open for any feedback.
Thank you in advance.
import os
import random
os.system('clear')
user = int(input("Please enter a number between 1-100: "))
print("Your Number is: " + str(user))
comp_list = list(range(1,101))
comp_selection = random.choice(comp_list)
count = 0
def game(num, a = 1, b = 100):
global count
print("I have chosen " + str(num) + "\nShould I go Higher or Lower or Correct? ")
user = input("Your Selection: ")
if user == "L":
count = count + 1
low_game(a, num)
elif user == "H":
count = count + 1
high_game(num, b)
else:
print("I have guessed correctly in " + str(count) + " tries")
def low_game(old_low, new_High):
x = new_High
new_comp_list = list(range(old_low, x))
new_comp_selection = random.choice(new_comp_list)
game(new_comp_selection, old_low, x)
def high_game(new_low, old_high):
x = new_low + 1
new_comp_list = list(range(x, old_high))
new_comp_selection = random.choice(new_comp_list)
game(new_comp_selection,x, old_high)
game(comp_selection)
I agree, you have over complicated the game with recursive functons.
Here is a much simplified game with penalties for player who does not answer correctly
or falsifies the answer:)
import sys, random
wins = 0
loss = 0
while 1:
user = input('Please enter a number between 1-100: (return or x = quit) > ' )
if user in [ '', 'x' ]:
break
elif user.isnumeric():
user = int( user )
if user < 1 or user > 100:
sys.stdout.write( 'Number must be between 1 and 100!!\n' )
else:
low, high, count = 1, 100, 0
while 1:
p = random.randint( low, high )
count += 1
while 1:
answer = input( f'Is your number {p}? Y/N > ').upper()
if answer in [ 'Y','N' ]:
break
else:
sys.stderr.write( 'Answer must be Y or N\n' )
if answer == 'N':
if p != user:
if input( f'Is my number (H)igher or (L)ower? > ').upper() == 'H':
if user < p:
high = p - 1
else:
sys.stderr.write( f'Wrong!! Your number was lower. You loss\n' )
loss =+ 1
break
else:
if user > p:
low = p + 1
else:
sys.stderr.write( f'Wrong!! Your number higher. You loss\n' )
loss =+ 1
break
else:
sys.stderr.write( f'Cheat!! Your number is {user}!! You loss\n')
loss =+ 1
break
else:
if user == p:
sys.stdout.write( f'I guessed Correctly in {count} guesses\n' )
wins += 1
else:
sys.stderr.write( f'Cheat!! This is not your number. You loss\n' )
loss =+ 1
break
print( f'Computer won = {wins} : You lost = {loss}' )
Happy coding.
You have really overly complicated the problem. The basic process flow is to have the computer guess a number within a fixed range of possible numbers. If the guess is incorrect, the user tells the computer how to adjust the list by either taking the guessed number as the low end or the high end of the guessing range. So to accomplish this, I would do the following:
from random import randint
# Function to request input and verify input type is valid
def getInput(prompt, respType= None):
while True:
resp = input(prompt)
if respType == str or respType == None:
break
else:
try:
resp = respType(resp)
break
except ValueError:
print('Invalid input, please try again')
return resp
def GuessingGame():
MAX_GUESSES = 10 # Arbritray Fixed Number of Guesses
# The Game Preamble
print('Welcome to the Game\nIn this game you will be asked to provide a number between 1 and 100 inclusive')
print('The Computer will attempt to guess your number in ten or fewer guesses, for each guess you will respond by telling the computer: ')
print('either:\n High - indicating the computer should guess higher\n Low - indicating the computer should guess lower, or')
print(' Yes - indicating the computer guessed correctly.')
# The Game
resp = getInput('Would You Like To Play?, Respond Yes/No ')
while True:
secret_number = None
if resp.lower()[0] == 'n':
return
guess_count = 0
guess_range = [0, 100]
secret_number = getInput('Enter an Integer between 1 and 100 inclusive', respType= int)
print(f'Your secret number is {secret_number}')
while guess_count <= MAX_GUESSES:
guess = randint(guess_range[0], guess_range[1]+1)
guess_count += 1
resp =getInput(f'The computer Guesses {guess} is this correct? (High?Low/Yes) ')
if resp.lower()[0] == 'y':
break
else:
if resp.lower()[0] == 'l':
guess_range[1] = guess - 1
else:
guess_range[0] = guess + 1
if guess == secret_number:
print (f'The Computer has Won by Guessing your secret number {secret_number}')
else:
print(f'The Computer failed to guess your secret number {secret_number}')
resp = getInput('Would You Like To Play Again?, Respond Yes/No ')

How do I make the program roll the previous number of dice by just clicking enter?

This is what I have so far. It works great if you want to roll different amounts of dice each time, but if you are playing a game like Sequence Dice its can get pretty frustrating and monotonous. I want it to be able to roll the previous number of dice rolled when you click enter without having to enter a new value.
from random import randint
run = False
dice_num = 0
roll_num = 0
total_sum = 0
print()
print("Welcome to dice roller!")
print()
print("To quit, just type stop at any time.")
while run == False:
print()
num_of = input("How many dice do you want to roll? ")
print()
if num_of.lower() == "stop":
print()
print("Thank you!")
print(f"You rolled a total of {dice_num} dice in {roll_num} rolls.")
print()
break
try:
act_num = int(num_of)
print("You rolled...")
roll_num += 1
while act_num > 0:
dice_out = randint(1, 6)
print(dice_out)
act_num -= 1
dice_num += 1
total_sum += dice_out
print()
print(f"Sum: {total_sum}")
total_sum = 0
except ValueError:
print("Try Again.")
run == False```
I think this should do the job. I created variable previous_dice_num At the end of each loop, the value of num_of will be stored in previous_dice_num. Then, whenever the user enters nothing, the value of previous_dice_num will be used as num_of.
from random import randint
run = False
dice_num = 0
roll_num = 0
total_sum = 0
previous_dice_num = 0
print()
print("Welcome to dice roller!")
print()
print("To quit, just type stop at any time.")
while run == False:
print()
num_of = input("How many dice do you want to roll? ")
print()
if num_of == '':
num_of = previous_dice_num
if num_of.lower() == "stop":
print()
print("Thank you!")
print(f"You rolled a total of {dice_num} dice in {roll_num} rolls.")
print()
break
try:
act_num = int(num_of)
print("You rolled...")
roll_num += 1
while act_num > 0:
dice_out = randint(1, 6)
print(dice_out)
act_num -= 1
dice_num += 1
total_sum += dice_out
print()
print(f"Sum: {total_sum}")
total_sum = 0
except ValueError:
print("Try Again.")
previous_dice_num = num_of

Python3: How to loop my dice roller program back to the start

Writing my first solo program with no help from teacher or group, a simple code that can act as a D&D dice roller for any type or number of dice a user requires.
I've been working on it for about four hours, and I'm stuck on the last thing I want to do which is loop it back to the beginning instead of just ending when a user doesn't reroll the already chosen dice, I'd like it so it starts again from the top so the player can input a new dice value and number of rolls generated without closing the program and rerunning it.
import random
try:
min = 1
max = int(input("Enter the highest value of dice to be rolled: "))
except:
print("Your input was invalid, program rolled a d20 by default")
min = 1
max = 20
again = True
number_of_dice = int(input("Enter number of dice to roll: "))
for i in range(number_of_dice - 1):
print(random.randint(min, max))
while again:
print(random.randint(min, max))
reroll = input("Roll again? (y/n): ")
if reroll.lower() == "y" or reroll.lower() == "yes":
for i in range(number_of_dice - 1):
print(random.randint(min, max))
else:
print("Thank you")
break
You might try something like:
import random
while True:
try:
min = 1
max = int(input("Enter the highest value of dice to be rolled or 0 to exit: "))
except:
print("Your input was invalid, program rolled a d20 by default")
min = 1
max = 20
if max == 0:
break
if max < 0:
continue
again = True
number_of_dice = int(input("Enter number of dice to roll: "))
for i in range(number_of_dice - 1):
print(random.randint(min, max))
while again:
print(random.randint(min, max))
reroll = input("Roll again? (y/n): ")
if reroll.lower() == "y" or reroll.lower() == "yes":
for i in range(number_of_dice - 1):
print(random.randint(min, max))
else:
print("Thank you")
break
Also, I would suggest renaming "min" and "max" as they are reserved keywords

Python while loop through program not working

import random
replay = 1
while replay == 1:
replay = replay - 1
target = random.randint(1, 100)
guess = int(input("Guess the number 1-100: "))
count = 0
score = 0
while count == 0:
score = score + 1
if guess < target:
print ("The number is higher. Try again.")
guess = int(input("Guess the number 1-100: "))
elif guess > target:
print ("The number is lower. Try again.")
guess = int(input("Guess the number 1-100: "))
elif guess == target:
print ("You guessed Correctly!")
print ("Your score was:", score)
again = str(input("Play again? (yes or no)"))
if again == "yes" or "YES":
replay = replay + 1
elif again == "no" or "NO":
break
This is my code, except it doesn't do what I want it to do. After you guess the correct number, it doesn't see to properly loop through the game again when you say yes or no. It just goes through the final if statement again.
Why won't it go through the entire program again?
Your code will always be evaluated to true
if again == "yes" or "YES":
Change it to:
if again.lower() == "yes":
Or
if again in ("YES", "yes", "y",..)
When it is true, you need to break from you second loop:
if again.lower() == "yes":
replay = replay + 1
break
When it is false, don't break but exit the program using:
exit()
Since replay is only used to exit your code, you don't need it if you use exit().
Code would then be:
import random
while True:
target = random.randint(1, 100)
guess = int(input("Guess the number 1-100: "))
score = 0
while True:
score = score + 1
if guess < target:
print ("The number is higher. Try again.")
guess = int(input("Guess the number 1-100: "))
elif guess > target:
print ("The number is lower. Try again.")
guess = int(input("Guess the number 1-100: "))
elif guess == target:
print ("You guessed Correctly!")
print ("Your score was:", score)
again = str(input("Play again? (yes or no)"))
if again.lower() == "yes":
break
elif again.lower() == "no":
exit()

Python 3.6 elif syntax error

using a nested if statement and my indentation seems correct thru out yet still reviving a syntax error.thank you
# FIGHT Dragons
if ch3 in ['y', 'Y', 'Yes', 'YES', 'yes']:
# WITH SWORD
if sword == 1:
print ("You only have a sword to fight with!")
print ("You quickly jab the Dragon in it's chest and gain an advantage")
time.sleep(2)
print ("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print (" Fighting... ")
print (" YOU MUST HIT ABOVE A 5 TO KILL THE DRAGON ")
print ("IF THE DRAGON HITS HIGHER THAN YOU, YOU WILL DIE")
print ("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
time.sleep(2)
fdmg1 = int(random.randint(3, 10))
edmg1 = int(random.randint(1, 5))
print ("you hit a", fdmg1)
print ("the dragon hits a", edmg1)
time.sleep(2)
if edmg1 > fdmg1:
print ("The drgon has dealt more damage than you!")
complete = 0
return complete
this is where i run into a syntax error
elif fdmg1 < 5:
print ("You didn't do enough damage to kill the drgon, but you manage to escape")
complete = 1
return complete
else:
print ("You killed the drgon!")
complete = 1
return complete
Your return must be at the end of the if...elif...else statement. This works :
if edmg1 > fdmg1:
print ("The drgon has dealt more damage than you!")
complete = 0
elif fdmg1 < 5:
print ("You didn't do enough damage to kill the drgon, but you manage to escape")
complete = 1
else:
print ("You killed the drgon!")
complete = 1
return complete
Note that if the first if-condition is True, Python won't check for the subsequent ones.

Resources