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)
Related
This issue seems pretty simple but I'm stuck on it... I want to create multiple rounds of a for loop-based card game until the computer or user wins. My for loop is not working and stops immediately after naming how many cards are left.
I have tried messing around with the indentation and the style of the for loop.
def card_game():
print("New Game start")
cards = int(21)
comp_pick = 0
user_choice = input("Do you want to go first? y/n: ")
if user_choice == "y":
for n in range(cards):
while n < 21 and n > 0:
return print("There are",cards - comp_pick,"cards left")
user_pick = int(input("How many cards do you pick? (1-3): "))
comp_pick = int(4 - user_pick)
if user_pick > int(3):
return print("You cannot pick",user_pick,"cards")
elif user_pick < int(1):
return print("You cannot pick",user_pick,"cards")
else:
cards = cards - user_pick
if comp_pick == 1:
return print("There are",cards,"left \n\tI pick",comp_pick,"card")
else:
return print("There are",cards,"left \n\tI pick",comp_pick,"cards")
n = cards - comp_pick
if user_choice == "n":
#assuming the computer will always pick 1 card first
#taking 1 card will allow the number of cards to remain divisible by 4
return print("There are",cards,"cards left \n\tI pick 1 card \nThere are 20 cards left")
for n in range(1, 20):
while n < 20 and n > 0:
user_pick = int(input("How many cards do you pick? (1-3): "))
if user_pick > int(3):
return print("You cannot pick",user_pick,"cards")
if user_pick < int(1):
return print("You cannot pick",user_pick,"cards")
else:
cards = cards - user_pick
comp_pick = 4 - user_pick
if comp_pick == 1:
return print("There are",cards,"left \n\tI pick",comp_pick,"card")
else:
return print("There are",cards,"left \n\tI pick",comp_pick,"cards")
n = cards - comp_pick
I expect the output to be:
There are 21 cards left
How many cards do you pick (1-3): 3
You picked 3 cards
There are 18 cards left
I pick 2 cards
-----------------------------------------
There are 16 cards left
How many cards do you pick (1-3): 4
This is based off if the user decides to go first. I got the first couple of lines, but my for loop does not continue for the next game.
The main issue was definitely the return print statements, and as you realized, there is no real need for the while loops. Since the two blocks after the y/n question are pretty much identical, you could make a function so that it consolidates the code, and makes it more readable. There were other little things here and there that I adjusted, but there's still missing the winning logic. Anyhow, hope this helps now and in the future.
def card_loop(start_count):
cards = start_count # how many cards we start with, as it depends
while cards > 0: # it is always decremented, so just check for zero threshold
print("There are", cards, "cards left")
user_pick = int(input("How many cards do you pick? (1-3): "))
if 1 <= user_pick <= 3:
# valid user pick, proceed with calculations
cards -= user_pick # cards left from user pick
comp_pick = 4 - user_pick # computer pick logic
print("There are", cards, "left \n\tI pick", comp_pick, "card")
cards -= comp_pick # cards left from computer pick
else:
# invalid user pick, do nothing, will ask user to pick again
print("You cannot pick", user_pick, "cards")
def card_game():
print("New Game start")
user_choice = input("Do you want to go first? y/n: ")
if user_choice == "y":
card_loop(21)
elif user_choice == "n":
# assuming the computer will always pick 1 card first
# taking 1 card will allow the number of cards to remain divisible by 4
card_loop(20)
card_game()
Your loop logic is convoluted. Also, you've tried to code several game features at once, without testing any of them, which makes your current debugging harder. Let's tackle just the game loop. Decompose the hierarchy, perhaps something like this:
# Play one game.
# Start with 20 cards
# Continue until there are no cards left
deck = 20
while deck > 0:
# Each player gets a turn: human first
human_take = int(input("How many cards do you want?"))
deck -= human_take
print("You took", human_take, "cards; there are", deck, "remaining")
computer_take = 4 - human_take
deck -= computer_take
print("You took", computer_take, "cards; there are", deck, "remaining")
That's the gist of the game loop you might want. I've omitted the input validation (there are plenty of answers on this site for that topic), among other things.
Can you continue from there?
Like Sal said, the return statement will exit the function. Also the line n = cards - comp_pick gets overridden in the for statement. See this example:
for n in range(10):
print(n)
n += 2
One would think that this prints: 0, 2, 4, ...18, but it actually prints: 0, 1, 2 ... 9. This is because the range function returns a lazily computed list. Therefore the above code block can be written as:
for n in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]:
print(n)
n += 2
Here it is clear that after the line n += 2, n is then assigned to the next element in the list.
In this game I've been tasked to do, one part of it is where all players in the game start off with 0 points, and must work their way to achieve 100 points, which is earned through dice rolls. After player decides to stop rolling, each player's score is displayed. My problem is that I don't know how to individually assign each player a "Score" variable, in relation to how many players are playing initially, so for e.g.
Player 1: Rolls a 2 and a 5
Player 1 score = +25
and etc. for every other player
Essentially, I need help on how to check if for example user at the start inputs that 3 players are playing, 3 different variables will be assigned to each player that contains their scores, which will change as the game progresses.
I have no idea what the proper code should actually contain, hence why I'm looking for help
import random
playerList = []
count = 0
def rollTurn():
dice1 = random.randint(1,6)
dice2 = random.randint(1,6)
print("Your first dice rolled a: {}".format(dice1))
print("Your second dice rolled a: {}".format(dice2))
print("-------------------------MAIN MENU-------------------------")
print("1. Play a game \n2. See the Rules \n3. Exit")
print("-------------------------MAIN MENU-------------------------")
userAsk = int(input("Enter number of choice"))
if userAsk == 1:
userNun=int(input("Number of players?\n> "))
while len(playerList) != userNun:
userNames=input("Please input name of player number {}/{}\n> ".format(len(playerList)+1, userNun))
playerList.append(userNames)
random.shuffle(playerList)
print("Randomizing list..:",playerList)
print("It's your turn:" , random.choice(playerList))
rollTurn()
while count < 900000:
rollAgain=input("Would you like to roll again?")
if rollAgain == "Yes":
count = count + 1
rollTurn()
elif rollAgain == "No":
print("You decided to skip")
break
I would like that during a player's turn, after rolling their dices, the value of those two rolled dices are added to that individual's score, and from there, a scoreboard will display showcasing all the players' in the lobby current scores, and will continue on to the next player, where the same thing happens.
instead of using a list for playerList, you should use a dict:
playerList = {}
playerList['my_name'] = {
"score": 0
}
You can iterate on the keys in the dict if you need to get data. For example in Python3:
for player, obj in playerList.items():
print(player, obj['score'])
And for adding data its a similar process:
playerList['my_name']['score'] = playerList['my_name']['score'] + 10
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.
number = 1
p1 = 0
p2 = 0
while number <5:
gametype = input("Do You Want To Play 1 Player Or 2 Player")
if gametype == "2":
player1areyouready = input("Player 1, Are You Ready? (Yes Or No)") #Asking If Their Ready
if player1areyouready == "yes": #If Answer is Yes
print ("Great!")
else: #If Answer Is Anything Else
print ("Ok, Ready When You Are! :)")
player2areyouready = input("Player 2, Are You Ready? (Yes Or No)") #Asking If Their Ready
if player2areyouready == "yes":
print ("Great, Your Both Ready!") #If Both Are Ready
else:
print ("Ok, Ready When You Are! :)")
print ("Lets Get Right Into Round 1!") #Start Of Round 1
game1 = input("Player 1, What Is Your Decision? (Rock, Paper or Scissors?) (No Capitals Please)") #Asking Player 1 For their Decision
game2 = input("Player 2, What Is Your Decision? (Rock, Paper or Scissors?) (No Capitals Please)") #Asking Player 2 For Their Decision
if game1 == game2:
print("Tie!")
p1 + 0
p2 + 0
print ("Player 1's Score Currently Is...")
print (p1)
print ("Player 2's Score Currently Is...")
print (p2) #I'm Programming A Rock, Paper Scissors Game
In This Rock Paper Scissors Game, I'm Finding Trouble With My Score Variables. For Some Reason The Way I Programmed My Code Means That My Score Won't Add Up. Please Help :)
Thanks In Advance
When it is a tie, you don't need to update the score. However:
if game1 != game2:
p1 = p1 + score # Replace score with a number or assign score a value
p2 = p2 + score
Currently score is not being updated, because doing p1 + score will not update p1's value. You need to reassign to it. So do p1 = p1 + score or p1 += score
When I run your code on my IDLE I get all kinds of problems. That aside if all you are trying to do is add to a variable and its all numbers then you can do
# Put this at the end of the if statement where player one is the winner.
p1 += 1
# Put this at the end of the if statement where player two is the winner.
p2 += 1
All this is doing is adding 1 to the current number in the variable.
It should be that simple.
You haven't added anything to the scores. First, your only statement dealing with the scores is an expression, not an assignment. You need to keep the value by storing the result back in the variable, such as
number = number + 1
which you can shorten to
number += 1
Second, you've added 0 to p1 and p2. Even if you store the results, the value doesn't change.
REPAIR
You will need to determine which player wins, and then increment that player's score. I won't write the detailed code for you, but consider this:
if game1 == game2:
print ("Tie!")
elif game1 == "Rock" and game2 == "Scissors":
print ("Player 1 wins!")
p1 += 1
elif game1 == "Rock" and game2 == "Paper":
print ("Player 2 wins!")
p2 += 1
print ("Player 1's Score Currently Is...", p1)
print ("Player 2's Score Currently Is...", p2)
Do you see how that works? Update a score only when a player wins a round. Of course, you'll want to find a more general way of picking the winner, rather than working through all six winning combinations, but that's an exercise for the student. :-)
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.