Implement the following problem as a self-contained Python program (module). Please write in beginner level code! Thanks!
The game of Pig is a simple two-player dice game in which the first player to reach 100 or more points wins. Players take turns. On each turn, a player rolls a six-sided die. After each roll:
a) If the player rolls a 1 then the player gets no new points and it becomes the other player’s turn.
b) If the player rolls 2-6 then they can either roll again or hold. If the player holds, the sum of all rolls is added to his/her score and the turn passes to the other player.
Write a program that plays the game of Pig where one player is human and the other is the computer. When it is the human’s turn the program should show the score of both players and the previous roll. Allow the human to input “r” for roll again and “h” for hold. (Hint: use the input function).
Note:
All the details of code has been given inside the code as comments. It is one of the easiest way to implement this game. Though it looks larger it is too simple. If you go throught the code 2 to three times you will get the clear view of code.
Code
import random
#True defines current player's' turn
player = True
computer=False
pv=0
cv=0
while(True): #infinite loop till any of one wins
if(player): #player turn
print()
dv=random.randint(1,6) # roll the dice
if(dv==1): # player rolled.1,hence becomes computer turn
print("player rolled 1")
player=False
computer=True
else: #player rolled between 2-6
print("player rolled ",dv)
print("enter choice r or h :")
ch=input() #get input r or h
if(ch=='r'): # roll again
print("player chose",ch)
player=True
compuyer=False
elif(ch=='h'): # hold the value and pass the turn to computer
print("player chose",ch)
player=False
computer=True
pv+=dv
print("player score is ",pv)
if(pv>100): #player wins
print("player won")
break #exit the loop
elif(computer): #computer turn
print()
dv=random.randint(1,6) # roll the dice
if(dv==1): # computer rolled 1,becomes player turn
print("computer rolled 1")
player=True
computer=False
else: # computer rolled between 2-6
print("computer rolled ",dv)
print("enter choice r or h :")
ch=random.choice(['r','h'])
print("computer chose",ch)
if(ch=='r'): # roll again
player=False
compuyer=True
elif(ch=='h'): #hold the value and pass to the player
player=True
computer=False
cv+=dv
print("computer score is",cv)
if(cv>=100): #computer wins
print("computer won")
break #exit the loop
Terminal work
.
Get Answers For Free
Most questions answered within 1 hours.