A simple Game of Pig - python-3.x

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.

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)

Python Word guessing game, cannot get While loop to repeat program

I am trying to create a word guessing game in python. I can get the program to run once,
but I want it to run five times in a row keeping track of wins and losses, and this is where
I am running into issues. I have tried adding a counter and nesting the while loop but this does not seem to work. Any help or suggestions would be greatly appreciated. Thanks.
Here is the code I have written:
import random
print('Welcome to the word guessing game!')
input("What is your name? ")
print('Try to guess the word letter by letter, you have ten guesses, good luck!')
words = ['cowboy', 'alien', 'dog', 'airplane',
'trees', 'bridge', 'snake', 'snow',
'popcorn', 'apples', 'road', 'smelly',
'eagle', 'boat', 'runner']
word = random.choice(words)
print("Guess the word!")
guesses = ''
trys = 5
wins = 0
losses = 0
rounds = 0
while rounds < 5:
while trys > 0:
failed = 0
for char in word:
if char in guesses:
print(char, end=" ")
else:
print("*")
failed += 1
if failed == 0:
print("You Win")
print("The word is: ", word)
wins = wins + 1
rounds = rounds + 1
break
print()
guess = input("Enter your letter:")
guesses += guess
if guess != word:
trys -= 1
print("Plesae try again, You have", + trys, 'more guesses')
if trys == 0:
print("You Loose, better luck next time")
losses = losses + 1
rounds = rounds + 1
print('Wins:', wins )
print('Losses:', losses)

Stimulate rolling dice game

I want to write a program that stimulate a game as follows:
A random number between 1 and 2 is generated to determine which player
starts the game (player1 or player2).
The player who starts the game will now throw a dice repeatedly adding
the points scored in each throwing until either the player collects 20
or more points or until the player gets a 1 point score.
If the player collects 20 or more points, then the score is added to
the total points of the player and it becomes the other player's turn.
If the player gets a 1 point score before reaching 20 or more points,
then the player loses his turn without getting any points and it
becomes the other player's turn.
The other player now starts to play and plays with the same rules as
described above.
Once the second player ends his turn (either after reaching 20 or more
points or loses the his turn), then it becomes the first player's turn
and the game continues.
The first player who reaches a total score of 1000 points wins the
game.
My program works well, but are there any ways that I can solve the problem by defining only Function play without changing its parameters? Can I make Function turnPoint be a part of Function play without using any loops?
import random
def turnPoint(playerTurnPoint):
if (playerTurnPoint >= 20):
return playerTurnPoint
else:
p = random.randint(1, 6)
print(p, end = " ")
if (p == 1):
return 0
else:
playerTurnPoint += p
return turnPoint(playerTurnPoint)
def play(player1Total, player2Total, currentPlayer):
if (player1Total >= 1000):
print("Player 1 won.")
return None
elif (player2Total >= 1000):
print("Player 2 won.")
return None
else:
playerTurnPoint = 0
if (currentPlayer == 1):
print("Player 1 playing...")
print("Points obtained in this turn: ", end = " ")
playerTurnPoint = turnPoint(0)
print()
print("Turn total points = ", playerTurnPoint)
player1Total += playerTurnPoint
print("Player 1 total points = ", player1Total)
play(player1Total, player2Total, 2)
else:
print("PLayer 2 playing...")
print("Points obtained in this turn:", end = " ")
playerTurnPoint = turnPoint(0)
print()
print("Turn total points = ", playerTurnPoint)
player2Total += playerTurnPoint
print("Player 2 total points = ", player2Total)
play(player1Total, player2Total, 1)
#Main Program
player1Total = 0
player2Total = 0
currentPlayer = random.randint(1, 2)
print("Starting the Game")
print("=================")
play(player1Total, player2Total, currentPlayer)

Unable to record how many times my while loop runs- Python3

I am working on a number guessing game for python3 and the end goal of this is to show the user if they play more than one game that they'll receive an average number of guesses. However, I am unable to record how many times the game actually runs. Any help will do.
from random import randint
import sys
def guessinggame():
STOP = '='
a = '>'
b = '<'
guess_count = 0
lowest_number = 1
gamecount = 0
highest_number = 100
while True:
guess = (lowest_number+highest_number)//2
print("My guess is :", guess)
user_guess = input("Is your number greater than,less than, or equal to: ")
guess_count += 1
if user_guess == STOP:
break
if user_guess == a:
lowest_number = guess + 1
elif user_guess == b:
highest_number = guess - 1
print("Congrats on BEATING THE GAME! I did it in ", guess_count, "guesses")
PLAY_AGAIN = input("Would you like to play again? y or n: ")
yes = 'y'
gamecount = 0
no = 'n'
if PLAY_AGAIN == yes:
guessinggame()
gamecount = gamecount + 1
else:
gamecount += 1
print("thank you for playing!")
print("You played", gamecount , "games")
sys.exit(0)
return guess_count, gamecount
print('Hello! What is your name?')
myname = input()
print('Well', myname, ', I want you to think of number in your head and I will guess it.')
print("---------------------------------------------------------------------------------")
print("RULES: if the number is correct simply input '='")
print("---------------------------------------------------------------------------------")
print(" if YOUR number is GREATER then the output, input '>'")
print("---------------------------------------------------------------------------------")
print(" if YOUR number is LESS then the output, input '<'")
print("---------------------------------------------------------------------------------")
print(" ALRIGHT LETS PLAY")
print("---------------------------------------------------------------------------------")
guessinggame()
guess_count = guessinggame()
print(" it took me this many number of guesses: ", guess_count)
## each game the user plays is added one to it
## when the user wants to the game to stop they finish it and
## prints number of games they played as well as the average of guess it took
## it would need to take the number of games and add all the guesses together and divide it.
It is because you are either calling guessinggame() everytime user wants to play again or you are exiting the program. Also you are setting gamecount to 0 every time you call guessinggame(). You should move gamecount declaration and initialization out of your function. Also increment gamecount before you call guessinggame().

Trying to do input validation for rps game

I'm making an rps game on python 3.6 and can't seem to figure out how to do input validation for my two player game function module. Whenever I run the program and select two player game and enter a number less than 1 or more than 4, it just asks if I want to play again.
def twoPlayerGame():
player1 = False
player2 = 0
player1Win = 0
player2Win = 0
tie_ = 0
#prompting for weapon choice
while player1 == False:
weaponMenu()
player1 = int(input("Player 1, please make a selection.\t"))
player2 = int(input("Player 2, please make a selection.\t"))
while player1 or player2 not in range(1,4):
print ("Invalid data entered, try again.")
weaponMenu()
player1 = int(input("Player 1, please make a selection.\t"))
player2 = int(input("Player 2, please make a selection.\t"))
#redirects to main
while player1 == 4 or player2 == 4:
main()
if player1 == player2:
print("It's a tie!\n")
tie_ = tie_ + 1
elif player1 == 1:
if player2 == 2:
print("Paper covers rock! Player 2 won!\n")
player2Win = player2Win + 1
else:
print("Rock smashes scissors! Player 1 won!\n")
player1Win = player1Win + 1
elif player1 == 2:
if player2 == 3:
print("Scissors cuts paper! Player 2 won!\n")
player2Win = player2Win + 1
else:
print("Paper covers rock! Player 1 won!\n")
player1Win = player1Win + 1
elif player1 == 3:
if player2 == 1:
print("Rock smashes scissors! Player 2 won!\n")
player2Win = player2Win + 1
else:
print("Scissors cuts paper! Player 2 won!\n")
p1ayer2Win = player2Win + 1
#ask user if they want to play again
again = input("Play again? Enter yes or no.\n")
again = again.lower()
#display scores
print("Ties:\t", tie_)
print("Player 1 wins:\t", player1Win)
print("Player 2 wins:\t", player2Win)
#if yes, player still playing
#if no, redirect to main
if again=="yes":
player1 = False
else:
player1 = True
main()
Problem is with this line:
while player1 or player2 not in range(1,4):
Whatever you put on each side of or should usually be a true or false value. Putting player1 on the left side, while acceptable to the Python interpreter, is incorrect here because what you want to do is check if it's in range. On the right side, player2 not in range(1,4) is an actual true/false value, so that's fine.
So change the thing on the left to player1 not in range(1,4), and the function works fine:
while player1 not in range(1,4) or player2 not in range(1,4):

Resources