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.
Related
I have this dice game made in python for class, I am using functions for the scoring logic (which I believe is all working as desired). I have put these functions in a while loop so that when either player reaches 100 banked score the game ends. However, I cannot get this to work as intended.
while int(player1Score) < 100 or int(player2Score) < 100:
player1()
player2()
Here is one of the functions (the other is the same with score added to player 2's variable and some output changes):
def player1():
global player1Score #global score to reference outside of function
rTotal = 0 #running total - used when gamble
print("\nPlayer 1 turn!")
while 1==1:
d = diceThrow() #dicethrow output(s)
diceIndexer(d)
print(f"Dice 1: {dice1} \nDice 2: {dice2}")
if dice1 == '1' and dice2 == '1': #both die = 1 (banked & running = 0)
player1Score = 0
rTotal = 0
print("DOUBLE ONE! Banked total reset, Player 2's turn.")
break
elif dice1 == '1' or dice2 == '1': #either die = 1 (running = 0)
rTotal = 0
print("Rolled a single one. Player 2's turn!")
break
else: #normal dice roll - gamble or bank
choice = input("Gamble (G) or Bank (B): ")
choice = choice.upper() #incase lowercase letter given
if choice == 'G': #if Gamble chosen - reroll dice & add to running
rTotal += int(dice1) + int(dice2)
elif choice == 'B': #used to save score.
rTotal += int(dice1) + int(dice2)
player1Score += rTotal
print(f"\nPlayer 1 banked! Total: {player1Score}")
break
print("Turn over")
I have tried changing the 'or' in the while loop to an 'and'. While that did stop faster, it did not stop exactly as the other player achieved a score higher than 10.
bro.
i read your code but i can't get some points as below.
if dice1 == '1' and dice2 == '1': #both die = 1 (banked & running = 0)
player1Score = 0
the code above makes player1Score as zero.
and there's no adding score code for player2Score.
For this reason, the while loop doesn't stop.
plz, check it first.
Boolean logic works like this.
You want both scores to be less then 100 while the game runs which also means one of the scores should not be 100 or higher.
both scores less then 100
int(player1Score) < 100 and int(player2Score) < 100
one of the socres is not 100 or higher
!int(player1Score) >= 100 or !int(player1Score) >= 100
The reason why the game didn't stop when you changed the "or" to "and" is because player1Score and player2Score are being evaluated after both player1() and player2() are called. Even if player1 scored over 100, the game wouldn't stop and the turn would go over to player2, goes into the next loop evaluation and finally stop the loop.
To fix this, change the while loop of both player1() and player() to this.
while player1Score < 100:
And also add evaluation after calculating scores.
else: #normal dice roll - gamble or bank
choice = input("Gamble (G) or Bank (B): ")
choice = choice.upper() #incase lowercase letter given
# rTotal += int(dice1) + int(dice2)
# rewriting the same code is a bad practice.
# In this case, you can just write the same code outside the if-else logic since if-else doesn't effect the code.
rTotal += int(dice1) + int(dice2)
if choice == 'G': #if Gamble chosen - reroll dice & add to running
# added evaluation to stop the game
if player1Score+rTotal >= 100:
break
if choice == 'B': #used to save score.
player1Score += rTotal
print(f"\nPlayer 1 banked! Total: {player2Score}")
break
Hope this helps.
What I did is inside the function put an if statement (outside of the while) to return a value from the function using return like this:
def exampleFunction1():
#scoring logic here
if bank > finalScore: #Score to reach to win game
print(f"Score is over {finalScore}!")
return 0
Then inside the while loop, attach the functions to a variable so that the return value could be identified. Use the return value to break the while loop:
while True: #Breaks as soon as either player gets above 100 score
x = exampleFunction1()
if x == 0:
break
x = exampleFunction2()
if x == 0:
break
(Sidenote: I rewrote my whole program to take one gameLogic() function and apply this to the different players, but I still used the while loop stated second)
Hy guys i have the following problem - Write a program to play the following simple game. The player starts with $100. On each
turn a coin is flipped and the player has to guess heads or tails. The player wins $9 for each
correct guess and loses $10 for each incorrect guess. The game ends either when the player
runs out of money or gets to $200.
My program is actually running. However when players points go bellow zero my program still runs and that is not what i expected. I need to know if there is something that i can do in my if sentences or if there is an easier way to make statements when i have to much conditions.
import random
list=['heads','tails']
def game():
p1=100
p2=100
while (p1>0 or p2>0)and(p1<200 or p2<200):
x=random.choice(list)
x1=input('digit your guess player1 - ')
x2=input('digit your guess player2 - ')
if x1==x:
p1+=30
else:
p1=p1-40
if x2==x:
p2+=30
else:
p2=p2-40
return p1,p2
print(game())
I expect the program to return the scores and end if any player points goes above 200 or bellow 0
If I consider your original problem, the problem is that you are returning whatever current value the player has, instead you should remember the last score and if the condition you want the game to stop on happens, return the last score. This will ensure only valid scores are returned
import random
list=['heads','tails']
def game():
player=100
last_score = 0
#Conditions to break while loop
while player > 0 and player < 200:
#Keep track of last score
last_score = player
#Get choice from player, and increase/decrease score
x=random.choice(list)
x1=input('digit your guess player1 - ')
if x1 == x:
player += 9
else:
player -= 10
#Return last score
return last_score
print(game())
Extending this idea to the 2 player game will solve your issue as well!
import random
list=['heads','tails']
def game():
p1=100
p2=100
last_scores = 0,0
# Conditions to break while loop
while (0<p1<200) and(0<p2<200):
# Keep track of last score
last_scores = p1,p2
# Get choice from player, and increase/decrease score
x=random.choice(list)
x1=input('digit your guess player1 - ')
x2=input('digit your guess player2 - ')
if x1==x:
p1+=30
else:
p1=p1-40
if x2==x:
p2+=30
else:
p2=p2-40
return last_scores
print(game())
Change the while condition to:
while p1>0 and p2>0 and p1<200 and p2<200
but it is more readable if:
while 0<p1<200 and 0<p2<200
I'm making a quiz. The user has 3 tries to guess the answer to the question.
My problem is that the scoring system isn't working properly. If the user guesses the answer the first time it adds 3 points, which works. However, the program adds 0 points if the user guesses the second time when it's supposed to add 1 point.
I've tried asking people around me and swapping the if statements, so that the possibility of the program assuming the score is lost.
songnameguess = input("Guess the name of the song!")
counter = counter + 1
while counter < 3 and songnameguess != randomsong :
songnameguess = input("Nope! Try again!")
counter = counter + 1
if songnameguess == randomsong:
print ("Well done!")
answer = input("Do you want to continue playing?")
print (counter)
if counter == 2:
score == score + 1
print (score)
elif counter == 1:
score = score + 3
print (score)
When the user guesses the answer correctly the first time, they are supposed to have 3 points added to their score, and when the user guesses the answer correctly the second time, they are supposed to have 1 point added to their score. If the user does not guess the score in three tries, the game ends.
This line of code is wrong
score == score + 1
== should not be used but = should be used
Hope it helps
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.
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.