Pig Two Computers Game - python-3.x

I have an assignment where I need the computer to play a game of pig on his own and stop once 100 is rolled. So, I have two computer players going head to head, but the problem is that although the players could've had 100 total they keep going until turntotal >= 20 which in return gives the other player a chance to win because there was a point where 100 could be reached. It specifically states in our assignment to look out for this problem, but I have no clue how to go about solving this issue. Also any ways to make the code cleaner would be helpful.
def playerOne(score):
turntotal = 0
scoretotal = 0
while(scoretotal >= 0 and scoretotal <= 100):
while(scoretotal < 100):
roll = random.randint(1,6)
print('Rolled a ', roll)
if(turntotal <= 20 and roll != 1):
turntotal = turntotal + roll
scoretotal = scoretotal + roll
if(turntotal >= 20):
break
if(roll == 1):
scoretotal = scoretotal - turntotal
turntotal = 0
print('Pigged Out!!!')
break
print('Turn score =', turntotal)
turntotal = 0
return scoretotal
def printScore():
print(' ')
print("Player One score is", PlayerOneScore)
print("Player two score is", PlayerTwoScore)
print(' ')
PlayerOneScore = 0
PlayerTwoScore = 0
flipcoin = random.randint(1,2)
if(flipcoin == 1):
while(PlayerOneScore < 100 or PlayerTwoScore < 100):
printScore()
print("Player 1's turn")
PlayerOneScore += playerOne(PlayerOneScore)
if(PlayerOneScore >= 100):
break
printScore()
print("Player 2's turn")
PlayerTwoScore += playerOne(PlayerTwoScore)
if(PlayerTwoScore >= 100):
break
else:
while(PlayerOneScore < 100 or PlayerTwoScore < 100):
printScore()
print("Player 2's turn")
PlayerTwoScore += playerOne(PlayerTwoScore)
if(PlayerTwoScore >= 100):
break
printScore()
print("Player 1's turn")
PlayerOneScore += playerOne(PlayerOneScore)
if(PlayerOneScore >= 100):
break
printScore()
if(PlayerTwoScore > PlayerOneScore):
print("PLAYER 2 WINS")
else:
print("PLAYER 1 WINS")

Related

Running a loop 10,000 times in order to test expected value

Playing a 2 person game where player A and B take turns drawing stones out of a bag.
10 stones, 9 white, 1 black
You lose if you draw the black stone.
Assuming you alternate drawing stones, is going first an advantage, disadvantage, or neutral?
I'm aware that this can be solved using conditional probability, but I'd like to also prove it by using significant sample size data
import random
import os
import sys
stones = 4
player1Wins = 0
player2Wins = 0
no_games = 100000
gameCount = 0
fatal_stone = random.randint(1, int(stones))
picked_stone = random.randint(1, int(stones))
def pick_stone(self, stones):
for x in range(1, int(stones) + 1):
if picked_stone == fatal_stone:
if (picked_stone % 2) == 0:
player2Wins += 1 print("Player 2 won")
break
if (picked_stone % 2) == 1:
player1Wins += 1
print("Player 1 won")
break
else:
stones -= 1 picked_stone = random.randint(1, int(stones))
self.pick_stone()
pick_stone()
# def run_games(self, no_games): #for i in range(1, int(no_games) + 1): #gameCount = i #self.pick_stone()
print(fatal_stone)
print(picked_stone)
print(int(fatal_stone % 2))
print(int(picked_stone % 2))
print(gameCount)
print("Player 1 won this many times: " + str(player1Wins))
print("Player 2 won this many times: " + str(player2Wins))
The following code works. And it suggests that both players' chances of winning are equal, regardless of who plays first.
import random
import os
import sys
num_stones = 4
no_games = 100000
player1Wins = 0
player2Wins = 0
def pick_stone(player: int, stones: list, fatal_stone: int):
global player1Wins, player2Wins
picked_stone = random.choice(stones)
stones.remove(picked_stone)
if (picked_stone == fatal_stone):
if player == 1:
player2Wins += 1
else:
player1Wins += 1
return False
return True
def run_games(no_games: int):
for _ in range(no_games):
stones = [i for i in range(num_stones)]
fatal_stone = random.choice(stones)
# player 1 and 2 pick stones in turn
player = 1
playing = True
while playing:
playing = pick_stone(player, stones, fatal_stone)
player = player % 2 + 1
print(f"Total rounds: {no_games}")
print("Player 1 won this many times: " + str(player1Wins))
print("Player 2 won this many times: " + str(player2Wins))
run_games(no_games)

I'm running a odd/even game in Python and I get stuck once I need to define a winner

#Here I define the user and cpu function
cpu_num = random.randint(1,6)
user_selection = ["Odd", "Even"]
def cpu_choice():
choice = random.randint(1,6)
print("The computer's choice is",choice)
return choice
def user_choice():
while(True):
choice = input("Odd or Even? ")
if choice in user_selection:
print("Your choice is",choice)
return choice
else:
print("You did not write your answer correctly, please try again.")
#In this function I define the result of each round based on previous formulas and two new variables (num_rounds and user_lives) and everything works well
def round_result():
num_rounds = 0
user_lives = 10
while num_rounds < 8 and user_lives > 0:
user_pick = user_choice()
cpu_pick = cpu_choice()
if (cpu_pick % 2 == 0) and (user_pick == "Even"):
print (f'You have {user_lives + cpu_pick} lives left')
num_rounds += 1
user_lives = user_lives + cpu_pick
if (cpu_pick % 2 == 0) and (user_pick == "Odd"):
print (f'You have {user_lives - cpu_pick} lives left')
num_rounds += 1
user_lives = user_lives - cpu_pick
if (cpu_pick % 2 != 0) and (user_pick == "Even"):
print (f'You have {user_lives - cpu_pick} lives left')
num_rounds += 1
user_lives = user_lives - cpu_pick
if (cpu_pick % 2 != 0) and (user_pick == "Odd"):
print (f'You have {user_lives + cpu_pick} lives left')
num_rounds += 1
user_lives = user_lives + cpu_pick
#Everything works well until here, I don't know what am I doing wrong in the winner function
def winner():
user_won = user_lives > 0 and num_rounds == 8
cpu_won = user_lives < 0
game = round_result()
while game:
if user_won is True:
print ('You won')
if cpu_won is True:
print ('Cpu won')

How do I add a score to this game

I've been trying to figure out how to add a score to this for ages. I'm still not sure ;( sorry I'm new to coding.
this is the code for the main part
while roundsPlayed > 0:
chips_left = MAX_CHIPS
n = 1
rounds = 1
while chips_left > 0:
while True:
print("Number of chips left {}".format(chips_left))
if n%2 == 0:
print("{} How many chips would you like to take (1 - 3): ".format(playerTwo))
else:
print("{} How many chips would you like to take (1 - 3): ".format(playerOne))
try:
chipsTaken = int(input())
if chipsTaken < 1 or chipsTaken > 3:
print("Please enter a valid number from 1 to 3!")
else:
break
except:
print("Thats not even a number brotherman")
n += 1
chips_left = chips_left - chipsTaken
roundsPlayed = roundsPlayed - 1
rounds += 1

Python Error handling for an input requiring a integer

I would like to implement error handling so that if the user puts in anything besides an integer they get asked for the correct input. I believe try/except would work but I am wondering how I can get it to check for both a correct number within a range and ensuring there are no other characters. I have pasted my code below for review.
Thanks!
# Rock Paper Scissors
import random as rdm
print("Welcome to Rock/Paper/Scissors, you will be up against the computer in a best of 3")
# game_counter = 0
human_1 = input("Please enter your name: ")
GameOptions = ['Rock', 'Paper', 'Scissors']
hmn_score = 0
cpt_score = 0
rps_running = True
def rps():
global cpt_score, hmn_score
while rps_running:
hmn = int(input("""Please select from the following:
1 - Rock
2 - Paper
3 - Scissors
\n""")) - 1
while not int(hmn) in range(0, 3):
hmn = int(input("""Please select from the following:
1 - Rock
2 - Paper
3 - Scissors
\n""")) - 1
print('You Chose: ' + GameOptions[hmn])
cpt = rdm.randint(0, 2)
print('Computer Chose: ' + GameOptions[cpt] + '\n')
if hmn == cpt:
print('Tie Game!')
elif hmn == 0 and cpt == 3:
print('You Win')
hmn_score += 1
elif hmn == 1 and cpt == 0:
print('You Win')
hmn_score += 1
elif hmn == 2 and cpt == 1:
print('You Win')
hmn_score += 1
else:
print('You Lose')
cpt_score += 1
game_score()
game_running()
def game_score():
global cpt_score, hmn_score
print(f'\n The current score is {hmn_score} for you and {cpt_score} for the computer \n')
def game_running():
global rps_running
if hmn_score == 2:
rps_running = False
print(f"{human_1} Wins!")
elif cpt_score == 2:
rps_running = False
print(f"Computer Wins!")
else:
rps_running = True
rps()
To answer your question, you can do something like the following
options = range(1, 4)
while True:
try:
choice = int(input("Please select ...etc..."))
if(choice in options):
break
raise ValueError
except ValueError:
print(f"Please enter a number {list(options)}")
print(f"You chose {choice}")
As for the a code review, there's a specific stack exchange for that, see Code Review

A simple Game of Pig

The code I have for the game runs just fine, but I'm having trouble getting the game to end when one person reaches at least 100 points.
def dont_Be_Greedy(turn):
points = 0
keepPlaying = 121
print('Lets start!')
input('Press enter to roll')
while keepPlaying == 121:
roll = roll_Dice()
print('You rolled a ' + str(roll))
if roll == 1:
points = 0 * roll
keepPlaying = 110
enter = input('Your turn is over. Next player.')
elif roll > 1:
points += roll
print('your total is', points)
passPlay = input('Do you want to keep playing or pass?'
'\ntype pass or play. ')
if passPlay == 'play':
keepPlaying = 121
else:
keepPlaying = 110
enter = input('Your turn is over. Next player.')
return points
player1 = 0
player2 = 0
while player1 < 100 and player2 < 100:
print('Player 1 points are: ' + str(player1))
print('Player 2 points are: ' + str(player2))
gameOn = dont_Be_Greedy(1)
player1 += gameOn
print('Player 1 points are: ' + str(player1))
print('Player 2 points are: ' + str(player2))
gameOn = dont_Be_Greedy(2)
player2 += gameOn
if player1 >= 100:
print('Player 1 is the winner!')
elif player2 >= 100:
print('Player 2 is the winner!')
Instead of the program stopping when one player reaches 100, it lets them continue their turn. After they pass their turn, it lets the next player start rolling until they pass or roll one then the program stops and states the winner (person with the higher of the two scores).
I'm not sure where the problem is.
EDIT: I added dont_Be_Greedy I tried moving the if and elif statements just below the loop and the program stops without printing the winner.
Seems like your problem lies with dont_Be_Greedy().
It doesn't stop when it reaches 100.

Resources