Stimulate rolling dice game - python-3.x

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)

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)

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().

Python 3 - Object Oriented Programming - Classes & Functions

I have been studying Python 3 for a few months now and have just begun looking at Object Oriented programming. I asked a question on Stack Overflow about a text adventure game I was trying to write and it was suggested that it would be better to use OOP.
I did some searching as I wanted a very simple combat system that could be used in the game. I have the basic framework from the game but I would like some help with the combat system side.
Here is the code I have so far:
import random
import time as t
class Die:
def __init__(self, sides = 6):
self.sides = sides
def roll(self):
return random.randint(1, self.sides)
class Player:
def __init__(self):
self.hit_points = 10
def take_hit(self):
self.hit_points -= 2
class Enemy:
def __init__(self):
self.hit_points = 10
def take_hit(self):
self.hit_points -= 2
p = Player()
e = Enemy()
d = Die(6)
battle = 1
while battle != 0:
human = d.roll() + 6
print("Your hit score: ",human)
enemy = d.roll() + 6
print("Enemy hit score: ",enemy)
if human > enemy:
e.take_hit()
print("Your hit points remaining: ",p.hit_points)
print("Enemy points remaining: ", e.hit_points)
if e.hit_points == 0:
battle = 0
t.sleep(2)
elif human < enemy:
p.take_hit()
print("Your hit points remaining: ",p.hit_points)
print("Enemy points remaining: ", e.hit_points)
if p.hit_points == 0:
battle = 0
t.sleep(2)
The Die class is to simulate a six sided die, and player and enemy are used for game characters. After that the code is used to roll random number and the highest number win the round until either the player or the enemy reach zero points.
I am unsure how to use those last lines of code after the three classes and create a class from it also.
I need to be able to run a battle multiple times in the game and also store the player score with points deducted after each battle.
I really like and enjoy the use of objects and would like to become better, so any help with this is very much appreciated.
You can re-use a class and create more instances from one template. The Player and Enemy class have a identical functionality. You can create different instances from one class simply using the __init__ method with different arguments.
import random
import time as t
class Player:
def __init__(self, hit_points, sides):
self.hit_points = hit_points
self.sides = sides
def take_hit(self):
self.hit_points -= 2
def roll(self):
return random.randint(1, self.sides)
p = Player(hit_points=10, sides=6)
e = Player(hit_points=8, sides=6)
battle = 1
while battle != 0:
human = p.roll()
print("Your hit score: ",human)
enemy = e.roll()
print("Enemy hit score: ",enemy)
if human > enemy:
e.take_hit()
print("Your hit points remaining: ",p.hit_points)
print("Enemy points remaining: ", e.hit_points)
elif human < enemy:
p.take_hit()
print("Your hit points remaining: ",p.hit_points)
print("Enemy points remaining: ", e.hit_points)
t.sleep(2)
if e.hit_points == 0 or p.hit_points == 0:
battle = 0

How to convert my python file into an int?

the program is supposed to double the number of the player with a 75% chance and decrease by 1 with a 25% chance. If a new player receives a higher score than the last player, save the players name along with score to the file. The program exits once a player loses 5 points.
import random
points = 1
play = "yes"
name = input("what is your name?")
counter = 0
while play.lower() == "yes":
risk = random.randint(0,3)
play = input(name.upper() + "!...want to risk it to bisk it?")
if risk == 0:
points -= 1
counter += 1
if counter == 5:
break
else:
points *= 2
fi = open("score.txt", "r")
score = fi.readlines()
fi.close()
scores = int(score[0])
if (scores > points):
fi = open("score.txt","w")
fi.write(points + ":" + name)
fi.close()
print(score)
On the bottom is the text file "score.txt" which has the following:
0:No Name
you mean read the data back in as an usable int?
with open('score.txt') as F:
scores = F.readlines()
scores = [s.strip().split(':') for s in scores]
Now if you want to loop through the scores data:
for score, name in scores:
print(f"{name} scored:\t {int(score)}")

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