Cannot change a variable(score) dynamically in python - python

My program objective:
A dice game, two dice roll Everytime the player is ready. If the two numbers are equa, player gets +5 score. Else, -1 score.
My trouble: my program can't change the score. It is set to 0 initially. But Everytime it's only either -1 or +5. It has to keep decreasing or increasing. I also tried global variables.
Here is my code:
from random import randint
# this function returns two random numbers in list as dice result.
def roll_dice():
dice1 = randint(1, 7)
dice2 = randint(1, 7)
rolled_dice = [dice1, dice2]
return rolled_dice
# game function is all the game, if player is ready.
def game():
score = 0
rolled_dice = roll_dice()
print(rolled_dice)
if rolled_dice[0] != rolled_dice[1]:
score -= 1
elif rolled_dice[0] == rolled_dice[1]:
score += 5
print(f"score is {score}")
#also my code in pycharms, not asking if I want to continue game. but ignore it I it bothers you, I can figure it out.
#help here also if you can.. :)
conti = input("continue?")
if conti == 'y':
game()
else:
quit()
# this is the whole program.
def main():
ready = input("ready? (y/n)")
if ready == 'y':
game()
elif ready == 'n':
quit()
else:
print("type only y/n")
main()
I appreciate any help.

The reset happens because you keep calling your game() function each time a user types y to continue the game. You can change your game() function to be a loop and that will solve your problem:
def game():
score = 0
while True:
rolled_dice = roll_dice()
print(rolled_dice)
if rolled_dice[0] != rolled_dice[1]:
score -= 1
else: # you can change here to else, because being equals is the complement of the first if clause
score += 5
print(f"score is {score}")
conti = input("continue?")
if conti == 'n':
break

Related

A little confused about my issues with printing a string while inserting a score

I'm really new to Python and one of the things I'm struggling with is getting my code to run properly, I want it to print the current score every round but I'm having an issue adding the score into the string (Ideally not inline but if I have to I can do).
If anyone has any ideas, even if it's not specifically about the problem but instead just making the code overall more efficient, any help would be appreciated.
from random import randint
play = 1
while play == 1:
# Get user input & choose value
player, opponentInt = input("Rock, Paper, or Scissors? (r/p/s)\n"), randint(1,3)
player = player.lower()
# Assigning player input to int value
playerInt = []
if player == 'r':
playerStr, playerInt = 'Rock', 1
elif player == 'p':
playerStr, playerInt = 'Paper', 2
elif player == 's':
playerStr, playerInt = 'Scissors', 3
# Assigning randint function input to str value
if opponentInt == 1:
opponentStr = 'Rock'
elif opponentInt == 2:
opponentStr = 'Paper'
elif opponentInt == 3:
opponentStr = 'Scissors'
# Define strings
def winStr():
print("You chose {}, and I chose {}. Congratulations! You won! (Score = {})".format(player, opponentStr, score))
def loseStr():
print("You chose {}, and I chose {}. Unfortunately, you lost. (Score = {})".format(player, opponentStr, score))
def drawStr():
print("You chose {}, and I chose {}. It was a draw. (Score = {})".format(player, opponentStr, score))
# Give result of game
score = 0
if playerInt == []:
print('Unexpected value, please play again and check spellings.')
elif playerInt == 1 and opponentInt == 3:
score = score + 1
winStr()
elif playerInt == 3 and opponentInt == 1:
score = score - 1
loseStr()
elif playerInt > opponentInt:
score = score + 1
winStr()
elif playerInt < opponentInt:
score = score - 1
loseStr()
elif playerInt == opponentInt:
drawStr()
# Ask user if they would wish to play again
play = 2
while play == 2:
playAgain = input("Would you like to play again? (y/n) ")
playAgain = playAgain.lower()
if playAgain == 'y':
play = 1
elif playAgain == 'n':
play = 0
else:
play = 2
print("Unexpected value...")
# Print score
print("Your score was {}.".format(score))
Thanks for any help.
I have tried making strings using:
str = "String here. Score = {}".format(score)
Along with my latest:
def str():
print("String here. Score = {}".format(score))
str()
You should pass these variables as arguments to your functions
def print_str(score):
print("String here. Score = {}".format(score))
print_str(5)
As an aside you could use f-strings instead of str.format
def print_str(score):
print(f'String here. Score = {score}')
I have now fixed it and thank you to #CodyKramer for the tip in assigning formatting a string. Turned out I had an issue where the loop was resetting the variable I found after the string was actually printing the score change.
play = 1
while play == 1:
...
score = 0
if ...
score += 1
print(score)
...
Where in fact it should have been:
play = 1
score = 0
while play == 1:
...
if ...
score += 1
print(score)
...

Dice roll sum game

Okay, I'm at a loss. I am trying to make a game where you roll a die as many times as you like, but if the sum of your rolls is greater than or equal to 14, you lose. (note I'm pretty new to programing, so sorry if it's pretty bad.) The issue is that the code keeps on running, as in it keeps on asking the user for input" even if the sum of "your_list" is greater than 14.
import random
your_list = []
def dice_simulate():
number = random.randint(1,6)
print(number)
while(1):
flag = str(input("Do you want to dice it up again:Enter 1 and if not enter 0"))
if flag == '1':
number = random.randint(1,6)
your_list.append(number)
print(number)
print (your_list)
elif sum(your_list) >= 14:
print ('you lose')
else:
print("ending the game")
return
dice_simulate()
Add the condition for winning and return in this case. Also, add return to the condition where you lose.
Additional changes to improve the code:
Remove the useless first dice roll (which does not get counted in your case).
Declare your_list in the smallest scope possible (here, inside the function).
Improve the prompt.
import random
def dice_simulate():
your_list = []
while True:
flag = str(input("Roll the dice (y/n)? "))
if flag == 'y':
number = random.randint(1,6)
your_list.append(number)
print(number)
print (your_list)
list_sum = sum(your_list)
if list_sum > 14:
print ('you lose')
return
elif list_sum == 14:
print ('you win')
return
else:
print("ending the game")
return
dice_simulate()

Loops, Scoring, and File Management for "Snakes & Ladders" in Python

Thanks for checking!
I'm just seeing what this site is all about and need help with an assignment. So far, I actually have a functioning game of "Snakes & Ladders" in Python. What I need it to do is make it so that when the game is over, the list of 5 best scores is displayed, then the user is asked if he wants to play again. I am having issues with the loop of the overall game, and saving scores. If there is anyone out there that wants to give this a try, your assistance would be greatly appreciated. I'm a noob.
So, here's what I have so far:
from random import *
# Basic Game Setup
def setup_game():
players=6
while True:
try:
print("How many players are in the game?")
players = int(input())
if players > 4 or players < 2:
print("Must be less than 5 and greater than 1")
else:
break
except ValueError:
print("Must be a number")
names = {}
for i in range(1,players+1):
while True:
name = input("What is the name of Player {}? ".format(i))
if not name in names:
names[name] = 0
break
else:
print('Cannot have duplicate names')
return names
# Dice Roll
def roll_dice():
return randint(2,12)
# Short Game
def move_player(player, current_pos):
snake_squares = {20:15, 21:2, 50:40,52:18}
ladder_squares = {4:15,7:90,35:45,60:80,77:98}
total_moves = 0 #total_moves is where I'm trying to keep score
throw = roll_dice()
next_pos = current_pos + throw
total_moves += throw
print("{0} rolled a {1} and is now on square {2}".format(player, throw, next_pos))
if next_pos in snake_squares:
print("Player got bitten by a snake and is now on square {}".format(snake_squares[next_pos]))
next_pos = snake_squares[next_pos]
elif next_pos in ladder_squares:
print("Player climbed a ladder and is now on square {}".format(ladder_squares[next_pos]))
next_pos = ladder_squares[next_pos]
return next_pos
# Long Game
def move_player2(player, current_pos):
snake_squares2 = {20:15, 21:2, 50:40,52:18,99:6,170:100,190:171,199:111}
ladder_squares2 = {4:15,7:90,35:45,60:80,77:98,2:155,55:166,66:177,77:188,100:150,171:180}
total_moves = 0
throw = roll_dice()
next_pos = current_pos + throw
total_moves += throw
print("{0} rolled a {1} and is now on square {2}".format(player, throw, next_pos))
if next_pos in snake_squares2:
print("Player got bitten by a snake and is now on square {}".format(snake_squares2[next_pos]))
next_pos = snake_squares2[next_pos]
elif next_pos in ladder_squares2:
print("Player climbed a ladder and is now on square {}".format(ladder_squares2[next_pos]))
next_pos = ladder_squares2[next_pos]
return next_pos
# Game Definition
def game(players):
winner = {}
length = "s"
print("{}, Welcome To Snakes And Ladders - Select s for short game or l for Long game".format(" ".join(players)))
length = str(input())
#Short
while length == "s":
# For each player
for player, current_pos in players.items():
# Move player
players[player] = move_player(player, current_pos)
# Check win
if players[player] >= 100:
return player
# Next player
input("Press Enter")
# Long
while length == "l":
# For each player
for player, current_pos in players.items():
# Move player
players[player] = move_player2(player, current_pos)
# Check win
if players[player] >= 200:
return player
# Next player
input("Press Enter")
else:
print("Error")
# Game Loop
if __name__ == "__main__":
players = setup_game()
winner = game(players)
total_moves = move_player
print("{} won the game!!!!!".format(winner))
input("Play Again? Press Enter".format(setup_game)) # game loop that doesn't work..
This is actually a really good program, the loop issue can be fixed by using a while loop in the 'game loop':
if __name__ == "__main__":
while True:
players = setup_game()
winner = game(players)
total_moves = move_player
print("{} won the game!!!!!".format(winner))
input("Play Again? Press Enter".format(setup_game))
I would also recommend using '\n' in your code to neaten the output between turns.

My program produces print statement infinity in a loop. Don't know how to fix it [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
So I'm trying to learn Python and I have written a program that is essentially designed to play a game with the user and a computer.
This game's mechanics are:
There are two players: the user and the computer, who alternate turns until one of them reaches 100 points or higher.
• The user is always the first player.
• If any player reaches 100 points or more at the end of their turn, the game ends immediately and the other player does not get another turn.
• One turn consists of the following: the player rolls a 6-sided die.
o If they roll a 1, they score 1 point and their turn is over. Even if a player has
accumulated points from previous rolls, if they roll a 1, their score for that turn will be 1 point and their turn is over.
o If they roll any other number, the roll score is added to the turn total.
o Then, they have the option to continue rolling or to hold. There is no restriction on how many times a player can roll in a turn.
• Holding: if a player holds, they score their current turn total and their turn ends. If,
for example, a player rolled a 3, 4, and 2, then decides to hold, they score 9 points.
• If the player is the user, they are given the option as to whether they would like to
continue rolling or hold after each time they roll the die and do not get a 1.
• If the player is the computer, they will always continue rolling until their turn total
reaches the value 10 or higher.
The problem with the code is it produces an infinite print statement when the code runs. I worked it down to the Boolean statement in the main function where I set is_user_turn = True. I have sorted through the code but there is something I am not seeing and need help fixing it.
Here is the code:
import random
def welcome():
print("Welcome to Jeopordy")
def print_current_player(is_user_turn):
if (is_user_turn == True):
print("It is now human's turn")
if (is_user_turn == False):
print("It is now computer's turn")
def roll_die():
roll = random(1,6)
return roll
def take_turn(is_user_turn,Computer_Hold):
turn_total = 0
if(is_user_turn == True):
while(is_user_turn == True):
roll = roll_die()
if(roll == 1):
return 1
turn_total = turn_total + roll
print("Your turn total is 1")
is_user_turn = False
else:
print("You rolled a ",roll)
turn_total = turn_total + roll
print("Your turn total is ",turn_total)
play = input("Do you want to roll gain (Y/N)?")
if(play == 'N' or play == 'n'):
is_user_turn = False
return turn_total
else:
is_user_turn == True
if(is_user_turn == False):
while(is_user_turn == False):
roll = roll_die()
while(turn_total <= Computer_Hold):
if(roll + turn_total <= Computer_Hold):
print("You rolled a ", roll)
turn_total = turn_total + roll
print("Your turn total is ",turn_total)
return turn_total
def report_points(userscore,computerscore):
print("computer: ",computerscore)
print("user: ",userscore)
def get_next_player(is_user_turn):
if(is_user_turn == True):
is_user_turn = False
return is_user_turn
else:
is_user_turn = True
return is_user_turn
def main():
Game_End_Points = 100
Computer_Hold = 10
is_user_turn = True
userscore = 0
computerscore = 0
welcome()
while(userscore <= Game_End_Points and computerscore <= Game_End_Points):
print_current_player(is_user_turn)
if(get_next_player(is_user_turn) == True):
userscore = userscore + take_turn(is_user_turn,Computer_Hold)
report_points(userscore,computerscore)
get_next_player(is_user_turn)
elif(get_next_player(is_user_turn) == False):
computerscore = computerscore + take_turn(is_user_turn,Computer_Hold)
report_points(userscore,computerscore)
get_next_player(is_user_turn)
main()
This part is the bug:
while(userscore <= Game_End_Points and computerscore <= Game_End_Points):
print_current_player(is_user_turn)
this executes this function infinitely:
def print_current_player(is_user_turn):
if (is_user_turn == True):
print("It is now human's turn")
if (is_user_turn == False):
print("It is now computer's turn")
since your function doesn't alter userscore or computerscore, it gets stuck there. That's my hint for now. If you need further help, just ask at comment.
Added Hint: "Indent"
also, just checked your whole code -- seems there are other bugs as well :)
I can't tell for sure but it looks like this might be causing the loop or is at least going to cause some problems for you:
if(play == 'N' or play == 'n'):
is_user_turn = False
return turn_total
else:
is_user_turn == True
In the else statement, you are checking that is_user_turn is True instead of assigning it a True value. Looks like it should be is_user_turn = True
The variable userscore will always be less than the Game_End_Points and so will be computer score and hence will loop infinitely, use some counter in the loop.
while(userscore <= Game_End_Points and computerscore <= Game_End_Points):
print_current_player(is_user_turn)
userscore=userscore+10 #something like this
computerscore+=10

Adding scoring system to a number guessing game including play again

I have my game working fine now but I still want to take it further. I want to have a point scoring system included. I want the player to score 5 points if they have 1 live left when they win, 10 if they have 2 and 15 if they have all 3. But I don't want the score to be reset if they play again I just want it to say when the quit the game you have scored " " points. I have tried to do this in many different ways but I can seem to get it work it resets the score every time press y on the play again. I've included my base game code below please try and help. Any other recomendations for this game are very welcome.
**My apologies I don't know if I made this clear enough before. I don't want the score to be stored after the programs closed just until the player presses n when asked to play again **
#imports required modules
import random
#correct number variable created
num = 0
#generates number at random
comp_num = random.randint(1,10)
print('I\'m thinking of a number guess what it is...\n')
#main game code
def main():
#generates number at random
comp_num = random.randint(1,10)
#set num as a global variable
global num
#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!\n')
break
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)
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':
break
if play_again.lower() == 'n':
#if they don't game ends
input('Ok, Press enter to exit')
exit()
#calls main section of game
main()
#calls end of game to give option of playing again and reseting game
end()
Use this pattern:
def game(): # Play a single game.
lives = 3
...
return 5 * lives # Return the score of the game.
def ask_again():
print 'Play again?'
answer = ...
return answer == 'y' # Return True iff the user wants to play again.
def main():
score = game()
while ask_again():
score += game()
print score
main()
You should use global variable for storing the amount of scored points.
So I added code for adding points and printing the message:
#imports required modules
import random
#correct number variable created
num = 0
score = 0
#generates number at random
comp_num = random.randint(1,10)
print('I\'m thinking of a number guess what it is...\n')
#main game code
def main():
#generates number at random
comp_num = random.randint(1,10)
#set num as a global variable
global num
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!\n')
# add score
if lives == 3:
score += 15
elif lives == 2:
score += 10
elif lives == 1:
score += 5
break
elif comp_num >= guess:
#if guess is too low tells player
#one live taken for incorrect guess
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 -= 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():
global score
#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)
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':
break
if play_again.lower() == 'n':
#if they don't game ends
print("You scored " + str(score) + " amazing points!")
input('Ok, Press enter to exit')
exit()
#calls main section of game
main()
#calls end of game to give option of playing again and reseting game
end()

Categories

Resources