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.
Related
I am a beginner programmer
I am trying to code a simple game of "pig" where the rules are this: Two players roll dice to make it to 100. Player one starts and can roll as many times as they wish, or stop at any time and pass to the next player. If player one rolls a one, their totals for that round are 0 and the next players turn starts. If player one rolls anything other than a one, they can pass and add that round's totals to their final, or continue to roll and build up that round's total, then pass. Player two then chooses to roll and can continue or stop, and must stop if they roll a 1 and lose that round's totals. The first player to 100 points wins.
import random
player1_score = 0
player2_score = 0
while player1_score!=100 and player2_score!=100:
turn = 0
if (turn%2) == 0:
player1_turnscore = 0
while player1_turnscore<100:
rollornot = input("Player one, would you like to roll the dice or pass? Roll (R) or Pass (P) ")
if rollornot == "R":
dice_value1= random.randint(1,6)
print("you rolled a",dice_value1)
player1_turnscore +=dice_value1
if dice_value1==1:
player1_turnscore = 0
print("You have lost all points you accumulated this turn. Your score is still",player1_score," Player 2 starts.")
turn+=1
break
else:
turn+=1
player1_score+=player1_turnscore
print("Your score after that round is",player1_score)
break
print("your current score this turn is",player1_turnscore)
else:
player2_turnscore = 0
while player2_turnscore<100:
rollornot2 = input("Player two, would you like to roll the dice or pass? Roll (R) or Pass (P) ")
if rollornot2 == "R":
dice_value2= random.randint(1,6)
print("you rolled a",dice_value2)
player2_turnscore +=dice_value2
if dice_value2==1:
player2_turnscore = 0
print("You have lost all points you accumulated this turn. Your score is still",player2_score," Player 2 starts.")
turn+=1
break
else:
turn+=1
player2_score+=player2_turnscore
print("Your score after that round is",player2_score)
break
print("your current score this turn is",player2_turnscore)
Now I'm not sure how to switch to player 2 upon a player 1 pass or lose condition. I have the turn variable being added to every time so it should be 1 after player 1 gets done the first time, but it just replays the first rollornot
Link to the rules in case my explanation is horrible, which it probably is:
https://www.dicegamedepot.com/dice-n-games-blog/pig-dice-game-rules/
The 'if' statement at the top of the main 'while' statement checks what turn it is by checking for an even number, player 1 turn will always be even.
The problem was I had the turn=0 variable inside of the while loop, resetting it to 0 on each recursion. Then the if statement checks each time if turn is even or not, if it is even then it is player 1's turn, if not then player 2. I have posted my finished program here, which is a complete 2 human player game of pig.
import random
player1_score = 0
player2_score = 0
turn=0
winner=False
while player1_score<101 and player2_score<101 and winner==False:
if turn%2==0: #this checks whether the turn is an even-numbered integer. If it is even, it is player one's turn
player1_turnscore = 0
while player1_turnscore<101 and winner==False:
print("Player 1, your overall score is",player1_score)
rollornot = input("Player 1, Would you like to roll the dice or pass? Roll (R) or Pass (P) ")
if rollornot == "R":
dice_value1= random.randint(1,6)
print("you rolled a",dice_value1)
player1_turnscore +=dice_value1 #cumulative score per round
if dice_value1==1:
player1_turnscore = 0
turn+=1
print("You have lost all points you accumulated this turn. Your score is still",player1_score,". Player 2 starts.")
break
if (player1_turnscore+player1_score)>=100:
print("Congratulations, Player 1, you won!")
winner=True #this helps close the while loop
break
else:
turn+=1
player1_score+=player1_turnscore
print("Player 1, your overall score after that round is",player1_score)
break
print("your current score this turn is",player1_turnscore)
else: #when turn is not even
player2_turnscore = 0
while player2_turnscore<101 and winner==False:
print("Player 2, your overall score is",player2_score)
rollornot2 = input("Player 2, would you like to roll the dice or pass? Roll (R) or Pass (P) ")
if rollornot2 == "R":
dice_value2= random.randint(1,6)
print("you rolled a",dice_value2)
player2_turnscore +=dice_value2 #cumulative score per round
if dice_value2==1:
player2_turnscore = 0
print("You have lost all points you accumulated this turn. Your score is still",player2_score,". Player 1 starts.")
turn+=1
break
if (player2_turnscore+player2_score)>=100:
print("Congratulation, Player 2, you won!!")
winner=True
break
else:
turn+=1
player2_score+=player2_turnscore
print("Player 2, your overall score after that round is",player2_score)
break
print("your current score this turn is",player2_turnscore)
I need help changing the range and showing the user what the range is so they know if they are closer or not. I have given the description I have been given. On what I need to do . I have given the code that I have come up wit so far. Let me know if you need anything else from me.
Step 6 – Guiding the user with the range of values to select between
Add functionality so that when displaying the guess prompt it will display the current range
to guess between based on the user’s guesses accounting for values that are too high and too
low. It will start out by stating What is your guess between 1 and 100, inclusive?, but as
the user guesses the range will become smaller and smaller based on the value being higher
or lower than what the user guessed, e.g., What is your guess between 15 and 32,
inclusive? The example output below should help clarify.
EXAMPLE
----------------
What is your guess between 1 and 44 inclusive? 2
Your guess was too low. Guess again.
import random
import sys
def main():
print("Assignment 6 BY enter name.")
welcome()
play()
#Part 1
def welcome():
print("Welcome to the guessing game. I have selected a number between 1 and 100 inclusive. ")
print("Your goal is to guess it in as few guesses as possible. Let’s get started.")
print("\n")
def play():
''' Plays a guessing game'''
number = int(random.randrange(1,10))
guess = int(input("What is your guess between 1 and 10 inclusive ?: "))
number_of_guess = 0
while guess != number :
(number)
#Quit
if guess == -999:
print("Thanks for Playing")
sys.exit(0)
#Guessing
if guess < number:
if guess < number:
guess = int(input("Your guess was too low. Guess Again: "))
number_of_guess += 1
elif guess not in range(1,11):
print("Invalid guess – out of range. Guess doesn’t count. : ")
guess = int(input("Guess Again: "))
else:
guess = input("Soemthing went wrong guess again: ")
if guess > number:
if guess > number:
guess = int(input("Your guess was too high. Guess Again: "))
number_of_guess += 1
elif guess not in range(1,11):
print("Invalid guess – out of range. Guess doesn’t count. : ")
guess = int(input("Guess Again: "))
else:
guess = input("Soemthing went wrong guess again: ")
#Winner
if guess == number :
number_of_guess += 1
print("Congratulations you won in " + str(number_of_guess) + " tries!")
again()
def again():
''' Prompts users if they want to go again'''
redo = input("Do you want to play again (Y or N)?: ")
if redo.upper() == "Y":
print("OK. Let’s play again.")
play()
elif redo.upper() == "N":
print("OK. Have a good day.")
sys.exit(0)
else:
print("I’m sorry, I do not understand that answer.")
again()
main()
What you'll need is a place to hold the user's lowest and highest guess. Then you'd use those for the range checks, instead of the hardcoded 1 and 11. With each guess, if it's a valid one, you then would compare it to the lowest and highest values, and if it's lower than the lowest then it sets the lowest value to the guess, and if it's higher than the highest it'll set the highest value to the guess. Lastly you'll need to update the input() string to display the lowest and highest guesses instead of a hardcoded '1' and '10'.
You need to simplify a lot your code. Like there is about 6 different places where you ask a new value, there sould be only one, also don't call method recursivly (call again() in again()) and such call between again>play>again.
Use an outer while loop to run games, and inside it an inner while loop for the game, and most important keep track of lower_bound and upper_bound
import random
import sys
def main():
print("Assignment 6 BY enter name.")
welcome()
redo = "Y"
while redo.upper() == "Y":
print("Let’s play")
play()
redo = input("Do you want to play again (Y or N)?: ")
def welcome():
print("Welcome to the guessing game. I have selected a number between 1 and 100 inclusive. ")
print("Your goal is to guess it in as few guesses as possible. Let’s get started.\n")
def play():
lower_bound, upper_bound = 0, 100
number = int(random.randrange(lower_bound, upper_bound))
print(number)
guess = -1
number_of_guess = 0
while guess != number:
guess = int(input(f"What is your guess between {lower_bound} and {upper_bound - 1} inclusive ?: "))
if guess == -999:
print("Thanks for Playing")
sys.exit(0)
elif guess not in list(range(lower_bound, upper_bound)):
print("You're outside the range")
continue
number_of_guess += 1
if guess < number:
print("Your guess was too low")
lower_bound = guess
elif guess > number:
print("Your guess was too high")
upper_bound = guess
print("Congratulations you won in", number_of_guess, "tries!")
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 need to write some code which shows a random single number/card from 1-12, the player then guesses whether the next card will be higher or lower than the first card/number. (play your cards right british game) if they guess right they get another go, if they guess wrong (they say higher or lower and it's the opposite) they lose and the game ends. if they guess four in a row right they win.
I have a very rough idea of how to go about this.
Could you please lend a hand?
import random
guessesTaken = 0
print('Hello! I am going to show you a card, guess whether the next card is higher or lower, get four in a row to win!')
number = random.randint(1, 12)
number1 = random.randint(1, 12)
number2 = random.randint(1, 12)
number3 = random.randint(1, 12)
number4 = random.randint(1, 12)
#five variables for five cards, all random cards between 1 and 12
print('Well I am thinking of a card between 1 and 12, the first number is:')
print (number) #shows them first card
while guessesTaken < 5: #limit number of guesses to make game less than 4 to win?
print('Take a guess, is the next card higher or lower? Please enter a number from 1 to 12.')
guess = input()
guess = str(guess) # limit input to "h" or "l"?
guessesTaken = guessesTaken + 1 #increment guesses taken
if guess = h and guess !> number1:
print ("you lose")
break
if guess =l and guess !< number1:
print('you lose')
if guess = h and guess !< number1:
print ("well done")
#ask about next card
if guess =l and guess !> number1:
print('well done')
#ask about next card
if guess == number1:
print ('you lose it was neither higher nor lower')
break
#basically I know the middle comparison for values higher or lower for the four cards can be done with a loop, just not sure how, very new to this.
second version (working sort of)
import random
guessesTaken = 0
print('Hello! I am going to show you a card, guess whether the next card is higher or lower, get four in a row to win!')
number = random.randint(1, 12)
#five variables for five cards, all random cards between 1 and 12
print('Well I am thinking of a card between 1 and 12, the first number is:')
print (number) #shows them first card
guess = input('Take a guess, is the next card higher or lower? Please enter either "h" or "l".')
while guessesTaken <= 4: #limit number of guesses to make game less than 4 to win?
if guessesTaken == 4:
print("You win")
break
else:
nextnumber = random.randint(1,12)
print(nextnumber)
if guess == "h" and nextnumber <= number:
print ("you lose")
break
elif guess == "l" and nextnumber >= number:
print ("you lose")
break
else:
guess = input("the card was" + str(nextnumber) + "is the next card higher or lower?")
guessesTaken += 1 #increment guesses taken
number = nextnumber
Well, lets make your code a little more pythonic...
import random
DECK_SIZE = 5
# See that it generates 5 unique random number from 1 to 12
# (not including 13) thus simulating a deck of cards,
# where cards cannot repeat. We add a None in the end to
# indicate end of deck
deck = random.sample(range(1, 13), DECK_SIZE) + [None]
# use of the zip method to create pairs of cards to compare
# (the final card will be a None, so we can see when cards ended)
for card,next_card in zip(deck[:-1],deck[1:]):
if next_card == None: # End of deck, user won the game
print("You won")
break
# we calculate the expected correct guess
# based on the pair of cards
correct_guess = "h" if next_card > card else "l"
# We get the user input
guess = input("card is {card} is next h or l? ".format(card=card))
# We verify if user input is the expected correct guess
if guess != correct_guess:
print("You lost, card was {next_card}".format(next_card=next_card))
break
I hope you can improve your python skills by studying this code and making changes to fulfill your needs. It uses a few python idiosyncrasies that may help you get some knowledge.
I am very new to programming so I decided to start with Python about 4 or 5 days ago. I came across a challenge that asked for me to create a "Guess the number" game. After completion, the "hard challenge" was to create a guess the number game that the user creates the number and the computer (AI) guesses.
So far I have come up with this and it works, but it could be better and I'll explain.
from random import randint
print ("In this program you will enter a number between 1 - 100."
"\nAfter the computer will try to guess your number!")
number = 0
while number < 1 or number >100:
number = int(input("\n\nEnter a number for the computer to guess: "))
if number > 100:
print ("Number must be lower than or equal to 100!")
if number < 1:
print ("Number must be greater than or equal to 1!")
guess = randint(1, 100)
print ("The computer takes a guess...", guess)
while guess != number:
if guess > number:
guess -= 1
guess = randint(1, guess)
else:
guess += 1
guess = randint(guess, 100)
print ("The computer takes a guess...", guess)
print ("The computer guessed", guess, "and it was correct!")
This is what happened on my last run:
Enter a number for the computer to guess: 78
The computer takes a guess... 74
The computer takes a guess... 89
The computer takes a guess... 55
The computer takes a guess... 78
The computer guessed 78 and it was correct!
Notice that it works, however when the computer guessed 74, it then guessed a higher number to 89. The number is too high so the computer guesses a lower number, however the number chosen was 55. Is there a way that I can have the computer guess a number that is lower than 89, but higher than 74? Would this require additional variables or more complex if, elif, else statements?
Thank you Ryan Haining
I used the code from your reply and altered it slightly so the guess is always random. If you see this, let me know if this is the best way to do so.
from random import randint
def computer_guess(num):
low = 1
high = 100
# This will make the computer's first guess random
guess = randint(1,100)
while guess != num:
print("The computer takes a guess...", guess)
if guess > num:
high = guess
elif guess < num:
low = guess + 1
# having the next guess be after the elif statement
# will allow for the random guess to take place
# instead of the first guess being 50 each time
# or whatever the outcome of your low+high division
guess = (low+high)//2
print("The computer guessed", guess, "and it was correct!")
def main():
num = int(input("Enter a number: "))
if num < 1 or num > 100:
print("Must be in range [1, 100]")
else:
computer_guess(num)
if __name__ == '__main__':
main()
what you are looking for is the classic binary search algorithm
def computer_guess(num):
low = 1
high = 100
guess = (low+high)//2
while guess != num:
guess = (low+high)//2
print("The computer takes a guess...", guess)
if guess > num:
high = guess
elif guess < num:
low = guess + 1
print("The computer guessed", guess, "and it was correct!")
def main():
num = int(input("Enter a number: "))
if num < 1 or num > 100:
print("Must be in range [1, 100]")
else:
computer_guess(num)
if __name__ == '__main__':
main()
The algorithm works by selecting a low and high limit to start with (in your case low=1 and high=100). It then checks the midpoint between them.
If the midpoint is less than number, the midpoint becomes the new lower bound. If the midpoint is higher, it becomes the new upper bound. After doing this a new midpoint is generated between the upper and lower bound.
To illustrate an example let's say you're looking for 82.
Here's a sample run
Enter a number: 82
The computer takes a guess... 50
The computer takes a guess... 75
The computer takes a guess... 88
The computer takes a guess... 82
The computer guessed 82 and it was correct!
So what's happening here in each step?
low = 1, high = 100 => guess = 50 50 < 82 so low = 51
low = 51, high = 100 => guess = 75 75 < 82 so low = 76
low = 76, high = 100 => guess = 88 88 > 82 so high = 88
low = 76, high = 88 => guess = 82 82 == 82 and we're done.
Note that the time complexity of this is O(lg(N))
I briefly made the game which you need with follows:
import random
guess=int(input("Choose a number you want the computer to guess from 1-100: "))
turns=0
a=None
compguess=random.randint(1,100)
while turns<10 and 100>guess>=1 and compguess!=guess: #computer has 10 turns to guess number, you can change it to what you want
print("The computer's guess is: ", compguess)
if compguess>guess:
a=compguess
compguess=random.randint(1,compguess)
elif compguess<guess:
compguess=random.randint(compguess,a)
turns+=1
if compguess==guess and turns<10:
print("The computer guessed your number of:" , guess)
turns+=1
elif turns>=10 and compguess!=guess:
print("The computer couldn't guess your number, well done.")
input("")
This is a bit rusty, but you could improve it by actually narrowing down the choices so the computer has a greater chance of guessing the right number. But where would the fun in that be? Notice how in my code, if the computer guesses a number which is greater than than the number the user has inputed, it will replace 100 from the randint function with that number. So if it guesses 70 and its too high, it won't choose a number greater than 70 after that. I hope this helps, just ask if you need any more info. And tell me if it's slightly glitchy
This is how I went about mine...
__author__ = 'Ghengis Yan'
print("\t This is the age of the computer")
print("\n The computer should impress us... the Man")
import random
#User chooses the number
the_number = int(input("Human Choose a number between 0 and 100 "))
tries = 1
computer = random.randint(0,100)
# User choose again loop
while the_number > 100:
the_number = int(input("I thought Humans are smarter than that... \nRetype the number... "))
if the_number <= 100:
print("Good")
# Guessing Loop
while computer != the_number:
if computer > the_number:
print(computer, "lower... Mr. Computer")
else:
print(computer, "higher... Mr. Computer")
computer = int(random.randint(0,100))
tries += 1
print("Computer Congratulations... You beat the human! The Number was ", the_number)
print("It only took a computer such as yourself", tries, "tries to guess it right... pathetic")
input("\nPress the enter key to exit.")
What I did for the same challenge was:
1) Define a variable that records the max value input by guessing computer.
Ex:
max_guess_number = 0
2) Define another variable with the lowest guessed value.
Ex.
min_guess_number = 0
3) Added in the "if computer_guess > secret_number" clause the following code (I added -1 so that the computer wouldn't try to guess the already previously tried number):
max_guess_number = guess - 1
computer_guess = random.randint(min_guess_number, max_guess_number)
4) Added the following code in the "if computer_guess < secret_number":
min_guess_number = guess + 1
computer_guess = random.randint(min_guess_number, max_guess_number)
Worth noting is the fact that I set my while loop to loop until another variable "guess_status" changes into a value 1 (the default I set to 0). This way I actually saw the result when the while loop finished.
print 'Please think of a number between 0 and 100!'
low = 0
high = 100
while(True):
rand = (high+low)/2
print 'Is your secret number '+str(rand)+'?'
ans = raw_input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly.")
if ans=='h':
high = rand
elif ans=='l':
low = rand
elif ans=='c':
print "Game over. Your secret number was:",rand
break
else:
print "Sorry, I did not understand your input"
You only need two new variables to keep track of the low and high limits :
low = 1
high = 100
while guess != number:
if guess > number:
high = guess - 1
else:
low = guess + 1
guess = randint(low, high)
print ("The computer takes a guess...", guess)
Try this:
import random
player = int(input("tap any number: "))
comp = random.randint(1, 100)
print(comp)
comp_down = 1
comp_up = 100
raw_input("Press Enter to continue...")
while comp != player:
if comp > player:
comp_up = comp - 1
comp = random.randint(comp_down, comp_up)
print(comp)
if comp < player:
comp_down = comp + 1
comp = random.randint(comp_down, comp_up)
print(comp)
if comp == player:
break
If you use the stuff in the chapter (guessing this is from the Dawson book) you can do it like this.
import random
#program allows computer to guess my number
#initial values
user_input1=int(input("Enter number between 1 and 100: "))
tries=1
compguess=random.randint(1, 100)
#guessing loop
while compguess != user_input1:
if compguess > user_input1:
print("Lower Guess")
compguess=random.randint(1, 100)
print(compguess)
elif compguess < user_input1:
print("Higher Guess")
compguess=random.randint(1, 100)
print(compguess)
tries += 1 #to have program add up amount of tries it takes place it in the while block
print("Good job Computer! You guessed it! The number was,", user_input1, \
" and it only took you", tries, " tries!")
import random
corr_num = random.randint(1,100)
player_tries = 0
com_tries = 0
while player_tries <5 and com_tries < 5:
player = int(input("player guess is "))
if player > corr_num:
print("too high")
player_tries +=1
if player < corr_num:
print("too low")
player_tries +=1
if player == corr_num:
print("Player wins")
break
computer = random.randint(1,100)
print("computer guess is ", computer)
if computer > corr_num:
print("too high")
com_tries = 0
if computer < corr_num:
print("too low")
com_tries = 0
if computer == corr_num:
print ("computer wins")
break
else:
print("Game over, no winner")**strong text**
import random
x = 1
y = 99
hads = random.randint(x,y)
print (hads)
javab = input('user id: ')
while javab != 'd':
if javab == 'b':
x = hads
hads = random.randint(x,y)
print(hads)
javab = input('user id: ')
else:
javab == 'k'
y = hads
hads = random.randint(x,y)
print(hads)
javab = input('user id: ')
This is the code that I created to simplify the problem you were facing a lot more.
num = int(input("Enter a number between 1 and 100: "))
low = 1
high = 100
guess = (low+high)//2
while guess != num:
guess = (low+high)//2
print("The computer takes a guess...", guess)
if guess > num:
high = guess
else:
low = guess + 1
print("The computer guessed", guess, "and it was correct!")
import random
userNum = int(input("What will the secret number be (1-100)? "))
attempts = 0
guess = 0
lowCap = 1
highCap = 100
while guess != userNum:
guess = random.randint(lowCap,highCap)
if guess > userNum:
highCap = guess
attempts += 1
elif guess < userNum:
lowCap = guess
attempts += 1
print("The computer figured out the secret number in", + attempts, "tries.")
I was doing a similar scenario today for an assignment and only now figured out how to make it easily cut down through the numbers by changing random.randint(1, 100) to random.randint(lowCap, highCap) which will change as the computer keep making guesses.