i have been stuck in this problem for a while now,
am trying to make a game where the user is given only 100 number to create a well defined shinobi ( got the name from watch Naruto and i love the series)
so i made my own class attributes. am trying to create a function to store the game inside and trying to make it so if the player uses more than 100 or = 100, the code should stop running but instead the code run even to negative a figure
let me put out the code for understanding ( sorry for my long write up, its actually my first time here)
print("ok, lets beging the game")
import Avatars # importing my own customised class
s = Avatars.Shinobi('naruto', 'uzimaki', 'genin', 100, 50, 70) # original class attributes
name = input('enter your name: ')
print(f'welcome onboard {name}, so you have to make your own ninja using (1- 100) '
f'and each time you make a ninja, we minus the number from the 100 you have '
f'GoodLuck!!')
print(" all you have to do is make a ninja that has 'strength', 'chakra', and 'skill' ")
def game(): # putting everything inside a function
try:
numb = 100 # the max number given by me to the player
while numb > 0:
a = (s.set_skill()) # using the imported class
a1 = int(a)
numb -= a
print('you have ', numb)
b = (s.set_chakra()) # using the imported class
b1 = int(b)
numb -= b
print(' you have ', numb)
c = (s.set_strength()) # using the imported class
c1 = int(c)
numb -= c
print('you have', numb)
if numb < 0: # using an if statement to cut the game half way, if the user inputs more than 100
print('you have run out of numbers')
else:
print('you still have more numbers to go!!')
except:
print('enter only number')
print(game())
OUTPUT:
ok, lets beging the game
enter your name: emma
welcome onboard emma, so you have to make your own ninja using (1- 100) and each time you make a ninja, we minus the number from the 100 you have GoodLuck!!
all you have to do is make a ninja that has 'strength', 'chakra', and 'skill'
enter skill rate (1 - 100): 50
you have 50
enter chakra level (1 - 100): 50
you have 0
enter strength level (1 - 100): 60
you have -60
you have run out of numbers
the code was suppose to stop, since i have input 50 twice and have no number left
Thanks for the help!
Hi Emmanuel Chidera, this is happening because you are substracting from numb after each set operation but checking numb value 'til the end. In order to prevent this to occur, you may check the numb variable value after each set operation and if its value is <= 0 you end right there the program execution.
To help you to understand this situation a bit better, I'm going to provide this short code snippet demonstrating the difference between your approach (checking numb value at the end) and the possible solution.
def initShinobi():
#This is similar to your approach
print("Inside initShinobi function\n")
maxPoints = 100 # the maximum stat points
skill = int(input("Enter skill level: "))
maxPoints -= skill
print(f'You have {maxPoints} points left to assign.')
chakra = int(input("Enter chakra level: "))
maxPoints -= chakra
print(f'You have {maxPoints} points left to assign.')
strength = int(input("Enter strength level: "))
maxPoints -= strength
print(f'You have {maxPoints} points left to assign.')
if maxPoints < 0:
print('you have run out of numbers')
def haveAvailablePoints(points):
"""Helper function to check your available points"""
if points > 0:
print(f'You have {points} points left to assign.')
return True
else:
print('You have run out of points')
return False
def initShinobi2():
# This is the possible solution
print("\n\nInside initShinobi2 function\n")
maxPoints = 100 # the maximum stat points
skill = int(input("Enter skill level: "))
maxPoints -= skill
if not haveAvailablePoints(maxPoints):
return
chakra = int(input("Enter chakra level: "))
maxPoints -= chakra
if not haveAvailablePoints(maxPoints):
return
strength = int(input("Enter strength level: "))
maxPoints -= strength
if not haveAvailablePoints(maxPoints):
return
if __name__ == '__main__':
initShinobi()
initShinobi2()
Assuming skill = 50, chakra = 50 and strength = 60 the code snippet above produces this output:
Inside initShinobi function
Enter skill level: 50
You have 50 points left to assign.
Enter chakra level: 50
You have 0 points left to assign.
Enter strength level: 60
You have -60 points left to assign.
you have run out of numbers
Inside initShinobi2 function
Enter skill level: 50
You have 50 points left to assign.
Enter chakra level: 50
You have run out of points
Successful execution. Press Enter to exit...
As you can see, in initShinobi2 function after I entered skill and chakra level it won't ask for me to enter the strength level since we have reached the maximum value with the first two parameters.
Note: You may notice in initShinobi2 function that if you type skill = 50 and chakra = 60 the output will be similar to the demonstration here but logically it has overpassed the maximum value, but that's something that I delegate you to solve.
Related
I have produced a simple game using the turtle module. The objective of the game is to return to the original position in a certain number of moves, through left and right inputs. Therefore, I tried to make a scoring (point) system that counts the number of moves the user has done and prints a winning message if the user returns to the original position in the specified number of moves. If the user (player) fails to do so it prints a failure message. However, it doesn't count up each move (point) and when it prints the score it always prints "1" no matter how many moves the player has done. Apologies if the questions seem too simple but help is much appreciated.
Here is the code:
import turtle
print("Try to return to original position in exactly 12 moves")
my_turtle = turtle.Turtle()
fx = my_turtle.pos()
score = 0
tries = 12
def turtles():
while True:
score = 0
directions = input("Enter which way the turtle goes: ")
if directions == "Right" or directions == "R":
my_turtle.right(90)
my_turtle.forward(100)
score += 1
print(score)
if fx == my_turtle.pos() and tries == score:
print("Well done")
elif fx == my_turtle.pos and tries > score or score > tries:
print("Return to original position in exactly 12 moves")
directions1 = input("Enter which way the turtle goes: ")
if directions1 == "Left" or directions1 == "L":
my_turtle.left(90)
my_turtle.forward(100)
score += 1
print(score)
if fx == my_turtle.pos() and tries == score:
print("Well done")
elif fx == my_turtle.pos and tries > score or score > tries:
print("Return to original position in exactly 12 moves")
turtles()
turtle.done()
The problem is the score = 0 call at the top of the loop. This resets the score at every loop iteration, so there's no way score could ever be anything other than 0 or 1.
Hi everyone this is my first time posting and I'm quite a novice at coding in general, I've always preferred hardware. I'm currently in an intro to python class and unfortunately, much of the work is way more beyond what we are seeing in the text for the class. I'm trying to get code working that I've written that is supposed to take an integer grade and place it into a current list, and then have the list sorted. I also have to be able to pull out the highest and lowest grades on the list. When I started the I was able to get the list working and then as I went forward the code fell apart with it now saying that my float() can't be added to my list or even shown when I try to print the list. And when I go to try to pull out the highest and lowest scores my list decides to not exist. Below I've added my code and if any of you have any tips on this code or just python, in general, it would be helpful.
print('Scoring Engine')
menu = """
1: Exit
2: List scores so far
3: Add a score
4: Display the highest and lowest scores
"""
done = False
while not done:
print(menu)
selection = input('Please make a selection: ')
print()
if selection == '1':
done = True
elif selection == '2':
print('Scores recorded so far:')
scores = ['85.30', '85.20', '21.99']
scores.sort(reverse = True)
index = 0
while index < len(scores):
print(scores[index])
index += 1
elif selection == '3':
added_score = input('Please enter a score between 0 and 100: ')
added_score = float(added_score)
if added_score < 0:
print('The number is less than zero please enter a score between 0 and 100.')
elif added_score > 100:
print('The number is larger than zero please enter a score between 0 and 100.')
else:
scores.append(added_score)
elif selection == '4':
for i in range(0, len(scores)):
print('Highest score: {}:'.formtat(i, scores[i]) + ' ' + ' ' + 'Lowest score: {}::'.format(i, scores[i]))
else:
print('Selection is not valid please enter choice 1,2,3 or 4.')
I see two problems with the current code.
The main problem is that you compare strings with floats. Assume a user inputs a valid number between range 0 and 100. Then, that value will be appended to the score list. The problem occurs when you sort the score list, which contains values that are in strings, as score is currently defined as scores = ['85.30', '85.20', '21.99']. Instead, What you want is score to be a list of floats so that you can sort them.
The score list is defined within the while loop. This means that at each iteration of the loop, the score list is "reset" to its original value, i.e. any new values that were appended to the list would be gone. What you want to do, therefore, is to declare the score list outside of the scope of the while loop.
Based on these observations, here is the revised code:
print('Scoring Engine')
menu = """
1: Exit
2: List scores so far
3: Add a score
4: Display the highest and lowest scores
"""
scores = [85.30, 85.20, 21.99] # Declared outside loop, elements of type float
done = False
while not done:
print(menu)
selection = input('Please make a selection: ')
if selection == '1':
done = True
elif selection == '2':
print('Scores recorded so far:')
index = 0
while index < len(scores):
print(scores[index])
index += 1
elif selection == '3':
added_score = input('Please enter a score between 0 and 100: ')
num_score = float(added_score)
if num_score < 0:
print('The number is less than zero please enter a score between 0 and 100.')
elif num_score > 100:
print('The number is larger than zero please enter a score between 0 and 100.')
else:
scores.append(num_score)
scores.sort(reverse=True)
elif selection == '4':
for i in range(0, len(scores)):
print('Highest score: {}:'.formtat(i, scores[i]) + ' ' + ' ' + 'Lowest score: {}::'.format(i, scores[i]))
else:
print('Selection is not valid please enter choice 1,2,3 or 4.')
print('Exited')
P.S. Good luck self-studying Python. I was on the same boat just a few months ago, and I know how difficult it can feel at times. Keep it up.
I have figured out most of the problem but can't seem to figure out how to loop through each of the players to let them play the game. This is the code I have so far. I think that my while loop in the main() function is wrong but I don't know what to do to fix it. Let me know if you can point me in the right direction. I also need to figure out how to end the turn if you roll a 1.
import random
def instructions():
print ("==================================================")
print ("\nWelcome to the Game of Pig. To win, be the")
print ("player with the most points at the end of the")
print ("game. The game ends at the end of a round where")
print ("at least one player has 100 or more points.\n")
print ("On each turn, you may roll the die as many times")
print ("as you like to obtain more points. However, if")
print ("you roll a 1, your turn is over, and you do not")
print ("obtain any points that turn.\n")
def num_players():
while True:
players = raw_input("How many players will be playing? ")
if players.isdigit():
return int(players)
else:
print "\nPlease enter a valid number of players.\n"
def name_players(players):
count = 1
list_of_players = []
for i in range(players):
name = raw_input("Enter the name for Player {}: ".format(count))
list_of_players.append(name)
count += 1
print ""
return list_of_players
def start_game(list_of_players):
points = 0
for player in list_of_players:
print "{0} has {1} points.".format(player, points)
print ("==================================================\n")
s = input("How many sides of the dice do you want? ")
for player in list_of_players:
print ("\n{0}'s turn:").format(player)
answer = raw_input("Press y to roll the dice?")
while answer == 'y' and points <= 100:
roll = random.randrange(1, s)
if roll > 1:
points += roll
print "{0} has {1} points.".format(player, points)
answer = raw_input("Press y to roll the dice?")
def main():
instructions()
players = num_players()
list_of_players = name_players(players)
start_game(list_of_players)
if __name__ == "__main__":
main()
The problem you encountered is due to the local variable, points, in function start_game. All your players are sharing the same variable to keep tracking their score. Therefore, once, your first player reaches/passes 100 points, the game logic will move to the second player. However, the points variable is still keeping the score from the previous player (which is more than or equal to 100). Because of that, the following players will never get chance to get into while loop.
You should declare points vriable for each players OR reset points variable every time when points variable holds value is greater than or equal to 100.
def start_game(list_of_players):
points = 0 #<----------------- points is local variable to the function
for player in list_of_players:
print("{0} has {1} points.".format(player, points))
print ("==================================================\n")
s = int(input("How many sides of the dice do you want? ")) ###
# validate value of s?
for player in list_of_players:
### the variables declared in for loop is unique to each player
print ("\n{0}'s turn:".format(player))
answer = input("Press y to roll the dice?")
while answer == 'y' and points <= 100:
roll = random.randrange(1, s + 1, 1) ### randrange
if roll > 1:
points += roll
print("{0} has {1} points.".format(player, points))
answer = input("Press y to roll the dice?")
PS. I'm running your code with Python 3.6.1.
Furthermore, one more thing you need to take care of is that for random.randrange(start, stop, step). The output will not include the value of stop. e.g. random.randrange(0, 10, 1) will generate integers from 0 to 9 inclusive. Therefore, if a player chose 6 sides of dice, that means the random number range should be from 1 to 6. In this way, you need to increment whatever number player entered.
e.g. 6 sides of dice
either random.randrange(0, 6+1, 1) or random.randrange(6+1) should work.
I'm working my way through the Code Academy Python course and have been trying to build small side projects to help reinforce the lessons.
I'm currently working on a number game. I want the program to select a random number between 1 and 10 and the user to input a guess.
Then the program will return a message saying you win or a prompt to pick another higher/lower number.
My code is listed below. I can't get it to reiterate the process with the second user input.
I don't really want an answer, just a hint.
import random
random.seed()
print "Play the Number Game!"
x = raw_input("Enter a whole number between 1 and 10:")
y = random.randrange(1, 10, 1)
#Add for loop in here to make the game repeat until correct guess?
if x == y:
print "You win."
print "Your number was ", x, " and my number was ", y
elif x > y:
x = raw_input("Your number was too high, pick a lower one: ")
elif x < y:
x = raw_input("Your number was too low, pick a higher one: ")
You need use a while loop like while x != y:. Here is more info about the while loop.
And you can only use
import random
y = random.randint(1, 10)
instead other random function.
And I think you should learn about int() function at here.
These are my hints :)
import random
n = random.randint(1, 10)
g = int(raw_input("Enter a whole number between 1 and 10: "))
while g != n:
if g > n:
g = int(raw_input("Your number was too high, pick a lower one: "))
elif g < n:
g = int(raw_input("Your number was too low, pick a higher one: "))
else:
print "You win."
print "Your number was ", g, " and my number was ", n
Ok so I've written this and for some reason the multiplier and final score isn't always working for instance:
Would you like to read the rules?(Y/N) n
Would you like to play?(Y/N) y
Lowest number: 1
Hightest number: 6
I'm thinking of a number guess what it is...
Guess: 3
Well Done! You guessed Correctly!
You scored 15 points!
Would you like to play again?[Y/N] n
You scored a total of 15 points!
Your score multipler is 1!
Your final score is 22!
Now as you can see the score is right. The multiplier should be 1.5 which means the the final score should be 22.5. However it's saying the multiplier is 1 and the final score is 22?
However sometimes is works like this:
Would you like to read the rules?(Y/N) n
Would you like to play?(Y/N) y
Lowest number: 1
Hightest number: 10
I'm thinking of a number guess what it is...
Guess: 5
Too low!
You guessed incorrectly. You have 2 live(s) remaining.
Guess: 7
Well Done! You guessed Correctly!
You scored 10 points!
Would you like to play again?[Y/N] n
You scored a total of 10 points!
Your score multipler is 2!
Your final score is 25!
As you can see the range is 10 so the multiplier should be 2.5 however it prints it as 2. With the write multiplier the answer would be 25 however with the answer it provides it should be 20.
I will include my code underneath but this is really really confusing me. I need help soon as I have to had this in tomorrow Please Please Please help me!!
code
#imports required modules
import random
#score set as global variable with the value 0
global score
score = 0
def start():
#askes if user needs rules
rules = input('Would you like to read the rules?(Y/N) ')
#if yes rules are printed
if rules.lower() == 'y':
#prints inctructions
input('\t\t\t\t\tRules\n')
input("Guess the number the computer is thinking of to win but you only have 3 lives.")
input("\nStart by choosing the range of numbers the computer can choose from.")
input("""For example if I wanted a number between 1 and 10 I would type 1 for
lowest number and 10 for highest number.""")
input("""\nThe more lives you have left when you win the more points you get.
The larger the range of numbers you give the computer
the larger your score multipler.""")
input("\nIt can be harder than you think!")
input("\n\t\t\t\t\tEnjoy!")
#if not player is aksed to play
play = input("\nWould you like to play?(Y/N) ")
if play.lower() == 'n':
#if they don't game quits
quit()
#main game code
def main():
global low
global up
#generates number at random between the users two inputs
comp_num = random.randint(low,up)
#score set as global variable within function
global score
#lives created
lives = 3
while lives >= 1:
#player guesses
guess = int(input('Guess: '))
if comp_num == guess:
#if correct says well done
print('\nWell Done! You guessed Correctly!')
#1 live left player gets 5 points
if lives == 1:
score += 5
print('\nYou scored 5 points!\n')
#2 lives left player gets 10 points
elif lives == 2:
score += 10
print('\nYou scored 10 points!\n')
#3 lives left player gets 15 points
elif lives == 3:
score += 15
print('\nYou scored 15 points!\n')
break
elif guess > up:
#if number is high than possible player gets told
print('\nThat is higher than the highest number you slected')
#reminded of boundries
print('\nRemember your lowest number is',low,'and your highest number is',up,'.')
#asked to try again
print('\nPlease try again!\n')
elif comp_num >= guess:
#if guess is too low tells player
#one live taken for incorrect guess
lives = lives -1
print('\nToo low!\n')
#player is told how many lives they have left
print('You guessed incorrectly. You have',lives,'live(s) remaining.\n')
if lives == 0:
#if player guesses incorrectly they get told the correct awnser
print('The number I was thinking of was...',comp_num,'!\n')
elif comp_num <= guess:
#if guess is too high tells player
#one live taken for incorrect guess
lives = lives -1
print('\nToo high!\n')
#player is told how many lives they have left
print('You guessed incorrectly. You have',lives,'live(s) remaining.\n')
if lives == 0:
#if player guesses incorrectly they get told the correct awnser
print('The number I was thinking of was...',comp_num,'!\n')
def end():
#asks player if they want to play again
play_again = input('Would you like to play again?[Y/N] ')
while play_again.lower() == 'y':
#if they do game resets and plays again
if play_again.lower() == 'y':
comp_num = random.randint(1,10)
#starts game
print('\nI\'m thinking of a number guess what it is...\n')
main()
play_again = input('Would you like to play again?[Y/N] ')
if play_again.lower() == 'n':
#if they don't want to play again while loop breaks
break
if play_again.lower() == 'n':
#if they don't game ends
#prints score
input('\nYou scored a total of %i points!\n' % score)
#prints mulipler
input('Your score multipler is %i!\n' % multi)
#calculates total score
total = float(score*
multi)
#prints total score
input('Your final score is %i!\n' % total)
input('Press enter to exit')
#calls intial game function to start
start()
#lower number set as global and value of user input
global low
low = int(input('\nLowest number: '))
#lower number set a global and value of user input
global up
up = int(input('Hightest number: '))
#sets up the score mulitpler
rang = float(up - low + 1)
multi = float(rang/4)
#if the multipler is less then 1 it gets sent to 1 so it doesn't remove points
if multi < 1:
multi = 1
#starts atcual game
print('\nI\'m thinking of a number guess what it is...\n')
#calls main section of game
main()
#calls end of game to give option of playing again and resetting game
end()
Check this:
#if they don't game ends
#prints score
input('\nYou scored a total of %i points!\n' % score)
#prints mulipler
input('Your score multipler is %i!\n' % multi)
#calculates total score
total = float(score*
multi)
#prints total score
input('Your final score is %i!\n' % total)
You print numbers like 15, 1, 22. Those numbers are calculated as they should, but not printed as they should. this is caused by you using wrong format identifiers.
Replace the %i formatters with %f formatters and it will work.