I want to make a card game simulation called 'Game of War" in Python, which can input the number of times that we want to play, for example, 3 times, the output should be like this Enter in the number of simulations for War Game: 10 Sim 1 Player 1 is the winner Sim 2 Player 1 is the winner Sim 3 The game was a draw FINAL RESULT: Player 1 won 2 times Player 2 won 0 times There were 1 draw
For now, I'm having a problems with create a function sim_num_games(sim_num) that asks the user for how many simulations they would like to run. The function must return the results for player 1, player 2 and the number of times a game was a tie. Then its must display how many times Player 1 wins, how many times Player 2 wins, and how many times the game was a tie. This is what I got so far.
deck = []
suits = ["Clubs", "Diamonds", "Hearts", "Spades"]
def create_deck():
for suit in suits:
for rank in range(2,15):
deck.append((rank,suit))
return deck
def deal_cards(the_deck):
if the_deck[0] <= 10: rank = str(the_deck[0])
if the_deck[0] == 11: rank = "Jack"
if the_deck[0] == 12: rank = "Queen"
if the_deck[0] == 13: rank = "King"
if the_deck[0] == 14: rank = "Ace"
fullname = rank + " of " + the_deck[1]
return fullname
def draw_card(player):
the_deck = deck[0]
deck.remove(deck[0])
print(player + 'has: ' + deal_cards(the_deck))
return the_deck
def play_game(p1_cards,p2_cards):
if p1_cards[0] > p2_cards[0]:
return "Player one"
if p1_cards[0] < p2_cards[0]:
return "Player two"
else:
return "DRAW!!!!!!!!"
def main():
deck = create_deck()
random.shuffle(deck)
round_play = 1
p1_score = 0
p2_score = 0
draw = 0
print("ALRIGHT, Let's Play...")
while len(deck) >= 2:
print("Hand number: ", round_play)
player_one_card = draw_card("Player 1 ")
player_two_card = draw_card("Player 2 ")
winner = play_game(player_one_card, player_two_card)
round_play += 1
if winner == "Player one": p1_score += 1
if winner == "Player two": p2_score += 1
if winner == "DRAW!!!!!!!!": draw += 1
print(f"{winner} wins")
else:
print("-"*15)
print("FINAL GAME RESULTS:","\nPlayer 1 won ", p1_score," hands" ,"\nPlayer 2 won ", p2_score," hands","\n",draw," hands were draw")
main()```
This can generate the deck and play but I cannot put the sim_num_games(sim_num) function in since it always error..
I would do something like this as your main structure.
p1_score = 0
p2_score = 0
draw = 0
ngames = int(input("How many games you want to simulate?"))
for _ in range(ngames):
winner = play_game()
if winner == 1:
p1_score += 1
elif winner == 2:
p2_score += 1
else:
draw += 1
if p1_score > p2_score:
print(f"Player 1 wins {p1_score} of {ngames} games")
elif p1_score < p2_score:
print(f"Player 2 wins {p2_score} of {ngames} games")
else:
print("draw")
Now, you have to put all the logic that initializes a game, plays it and determines a winner inside a function play_game(), which will return either 0, 1 or 2
Ideally you should create a class to have things better organized, but having functions hanging around will also work since it's a small project.
You can also make helper functions, so your main structure keeps as clean as possible. For example you can create a function update_scores() and a function determine_winner() that will take code out of the main structure and make it cleaner.
Related
I am a python newbie and this is my first question on stackoverflow so sorry if it's not correct. I am programming my own rock, paper scissors game in Python, which includes a computer class which remembers the previous turn of the player. However, I can only get it to return random.choice moves, and I am not sure where I am going wrong?
moves = ['rock', 'paper', 'scissors']
class Player:
def __init__(self):
self.my_move = None
self.their_move = None
def learn(self, my_move, their_move):
self.my_move = my_move
self.their_move = their_move
def beats(one, two):
return ((one == 'rock' and two == 'scissors') or
(one == 'scissors' and two == 'paper') or
(one == 'paper' and two == 'rock'))
class MemoryPlayer(Player):
def move(self):
if self.their_move in moves:
return self.their_move
else:
return random.choice(moves)
class Game:
def __init__(self, p1, p2):
self.p1 = p1
self.p2 = p2
self.scorep1 = 0
self.scorep2 = 0
# starting score of both players
def play_round(self):
firstmove = self.p1.move()
secondmove = self.p2.move()
print(f"Player 1: {firstmove} Player 2: {secondmove}")
# prints move of Player 1 and Player 2 after each round
if beats(firstmove, secondmove):
self.scorep1 += 1
print(f"Player 1 Wins. Score: {self.scorep1}"
f" to {self.scorep2}")
elif beats(secondmove, firstmove):
self.scorep2 += 1
print(f"Player 2 Wins. Score: {self.scorep2}"
f" to {self.scorep1}")
else:
print(f"Boring - TIE. Score: {self.scorep1}"
f" to {self.scorep2}")
# uses beats function in if and else statement to define score increase
# if player 1 move beats player 2 move and vice versa
def play_game(self):
print("Game start!")
self.rounds = 3
for round in range(self.rounds):
print(f"Round {round}:")
self.play_round()
print(f"Game over! Final score:\
Player 1: {self.scorep1}), Player 2: {self.scorep2}")
# prints final secores for Player 1 and Player 2
if self.scorep1 > self.scorep2:
print("Player 1 is Triumphant")
# if player 1 score is greater than player 2 - prints winning statement
elif self.scorep2 > self.scorep1:
print("Player 2 is Triumphant")
# if player 2 score is greater than player 1 - prints winning statement
else:
print("Boring - TIE")
if __name__ == '__main__':
game = Game(HumanPlayer(), MemoryPlayer())
# randomly chooses opposing NPC
game.play_game()
I am trying to write a program to play 100 games of Craps and print out the overall results. I have an infinite loop at the end of my code.
Does anyone see the problem?
I assume my 2nd function could be calling diceRoll again for secondRoll. Trying that now...
Specs:
The player must roll two six-side dice and add the total of both
dice.
The player will win on the first roll if they get a total of 7 or 11
The player will lose on the first roll if they get a total of 2, 3,
or 12
If they get any other result (4, 5, 6, 8, 9, 10), they must roll
again until they either match their first roll (a win) or get a
result of 7 (a loss)
Use at least two functions in your program
from random import randrange as rd
winTuple = 7, 11
lossTuple = 2, 3, 12
wins = 0
losses = 0
x = 1
def diceRoll (number, type = 6):
result = 0
for i in range(number):
result += rd(1, type +1)
return result
while x < 101:
firstRoll = diceRoll(2)
if firstRoll in winTuple:
wins += 1
elif firstRoll in lossTuple:
losses += 1
else:
secondRoll = diceRoll(2)
while secondRoll != 7 or secondRoll != firstRoll:
if secondRoll == 7:
wins += 1
elif secondRoll == firstRoll:
wins += 1
else:
secondRoll = diceRoll(2)
x += 1
print("wins: ", wins)
print("losses: ", losses)
Looks like you need to eliminate your inner loop. First, the loop conditions are in direct conflict with your conditional statements, so the loop never exits. Second, why would you want a loop here? Even if you fixed it, all it would do is keep rolling the second dice until a win is scored.
while x < 101:
firstRoll = diceRoll(2)
if firstRoll in winTuple:
wins += 1
elif firstRoll in lossTuple:
losses += 1
else:
secondRoll = diceRoll(2)
if secondRoll == 7 or secondRoll == firstRoll:
wins += 1
x += 1
In response to your comment, this is how you create your second loop. You make an infinite loop with while True and break out of it when the conditions are met.
while x < 101:
firstRoll = diceRoll(2)
if firstRoll in winTuple:
wins += 1
elif firstRoll in lossTuple:
losses += 1
else:
while True:
secondRoll = diceRoll(2)
if secondRoll == 7:
losses += 1
break
elif secondRoll == firstRoll:
wins += 1
break
x += 1
If your firstRoll != 7 (let's say firstRoll = 8) then your script cannot exit the second nested loop because either secondRoll != 7 or secondRoll = 7 and therefore firstRoll != secondRoll (7 != 8)
I am not sure how your program goes through 100 games of craps, here is an example of a program I wrote quick that goes through 100 games. Games being times you either hit or don't hit the point.
Clearly you need to understand how craps works to make something like this, so I am assuming you do. The program you were trying to write, even though you were stuck in the loop, was not actually playing a full game of craps.
You can choose the amount of games you want and the only thing it stores is if you won or lost.
You can add other statistics if you would like, for example points hit and which points they were etc.,
I added text to, also, make it user friendly if this is for a school project.
There are many different ways to do this, I used a main while loop and created two functions for whether the button is on or off.
You could obviously condense this, or write a class instead but I simply put this together quick to give you an idea and see how it goes through every loop and statement.
I am still a novice, so I apologize to anyone else reading, I know the below is not the most efficient/does not perfectly follow PEP8 especially the long if statement in the main loop.
This does perform what you wanted and feel free to change the number of games. Enjoy!
import random
wins = 0
losses = 0
gamenum = 0
#Used a list to pull the dice numbers from but not mandatory
dicenum = [2,3,4,5,6,7,8,9,10,11,12]
#Function when point is off
def roll_off():
#Random roll from list
roll = random.choice(dicenum)
if roll == 2:
print("2 craps")
elif roll == 3:
print("3 craps")
elif roll == 4:
print("Point is 4")
return(4)
elif roll == 5:
print("Point is 5")
return(5)
elif roll == 6:
print("Point is 6")
return(6)
elif roll == 7:
print("Winner 7")
elif roll == 8:
print("Point is 8")
return(8)
elif roll == 9:
print("Point is 9")
return(9)
elif roll == 10:
print("Point is 10")
return(10)
elif roll == 11:
print("Yo 11")
elif roll == 12:
print("12 craps")
#Function when point is on
def roll_on(x):
#Random roll from list
roll = random.choice(dicenum)
if roll == 2:
print("2 craps")
elif roll == 3:
print("3 craps")
elif roll == 4:
print("You rolled a 4")
elif roll == 5:
print("You rolled a 5")
elif roll == 6:
print("You rolled a 6")
elif roll == 7:
print("7 out")
elif roll == 8:
print("You rolled a 8")
elif roll == 9:
print("You rolled a 9")
elif roll == 10:
print("You rolled a 10")
elif roll == 11:
print("Yo 11")
elif roll == 12:
print("12 craps")
#Check if you hit the point
if x == 4 and roll == 4:
print("You win!")
return (True)
elif x == 5 and roll == 5:
print("You win!")
return (True)
elif x == 6 and roll == 6:
print("You win!")
return (True)
elif x == 7 and roll == 7:
print("You win!")
return (True)
elif x == 8 and roll == 8:
print("You win!")
return (True)
elif x == 9 and roll == 9:
print("You win!")
return (True)
elif x == 10 and roll == 10:
print("You win!")
return (True)
#Check if you 7'ed out
if roll == 7:
print("You lose!")
return (False)
#Main game, change the amount of games you want to play
while gamenum < 100:
diceresult = roll_off()
#If statement to check the point
if diceresult == 4 or diceresult == 5 or diceresult == 6 or diceresult == 8 or diceresult == 9 or diceresult == 10:
active = True
print("The point is on!")
while active == True:
curentstate = roll_on(diceresult)
if curentstate == False:
gamenum += 1
losses += 1
print("------------")
print("Games:", gamenum)
print("Losses:", losses)
print("Wins:", wins)
print("------------")
break
elif curentstate == True:
gamenum += 1
wins += 1
print("------------")
print("Games:", gamenum)
print("Losses:", losses)
print("Wins:", wins)
print("------------")
break
I have made a dice roll game on Python 3 but want to add a betting function.
I have tried a few things but I can only play one game. I want the game to have multiple rounds.
How do I make it a game where the player(s) can bet on multiple rounds until money ends at 0, or possibly keep playing until they want to stop?
import random
import time
print("this is a dice roll game")
def main():
player1 = 0
player1wins = 0
player2 = 0
player2wins = 0
rounds = 1
while rounds != 5:
print("Round" + str(rounds))
time.sleep(1)
player1 = dice_roll()
player2 = dice_roll()
print("Player 1 rolled " + str(player1))
time.sleep(1)
print("Player 2 rolled " + str(player2))
time.sleep(1)
if player1 == player2:
print("The round is a draw")
elif player1 > player2:
player1wins += 1
print("Player 1 wins the round")
else:
player2wins += 1
print("Player 2 wins the round")
rounds = rounds + 1
if player1wins == player2wins:
print("The game ended in a draw")
elif player1wins > player2wins:
print("Player 1 wins the game, Rounds won: " + str(player1wins))
else:
print("Player 2 wins the game, Rounds won: " + str(player2wins))
def dice_roll():
diceroll = random.randint(1,6)
return diceroll
main()
Adding to the comment by John Coleman, you can modify your while loop so that it does not end when the number of rounds is different to 5, something like:
while True:
// Rest of code...
if moneyP1 <= 0 OR moneyP2 <=0:
print("Someone ran out of money")
// Implement deciding who won
break
user_confirmation = raw_input("Keep playing? (YES/NO): ")
if user_confirmation == "NO":
break
Python novice here trying to trouble shoot my game of nim code.
Basically the code removes stones 1, 2 or 3 stones until their is none left. I'm trying to prevent the user and AI from going into the negatives (if their is one stone left the AI/the user shouldn't be able remove two or three stones.) Here is my code so far:
import random
Stones = random.randint(15, 30)
User = 0
YourTurn = True
print("This is a game where players take turns taking stones from a pile of stones. The player who
takes the last stone loses.")
print("The current stone count is:", Stones)
while True:
while YourTurn == True and Stones > 0:
User = int(input("How many stones do you want to remove?"))
if User == 1:
Stones -= 1
print("You removed 1 stone! The current stone count is:", Stones)
YourTurn = not True
elif User == 2:
Stones -= 2
print("You removed 2 stone! The current stone count is:", Stones)
YourTurn = not True
elif User == 3:
Stones -= 3
YourTurn = not True
print("You removed 3 stone! The current stone count is:", Stones)
else:
print("You can only remove a maximum of 3 stones.")
while YourTurn == False and Stones > 0:
AI = random.randint(1, 3)
if AI == 1:
Stones -= 1
print("The A.I removed 1 stone! The current stone count is:", Stones)
YourTurn = not False
elif AI == 2:
Stones -= 2
print("The A.I removed 2 stone! The current stone count is:", Stones)
YourTurn = not False
elif AI == 3:
Stones -= 3
print("The A.I removed 3 stone! The current stone count is:", Stones)
YourTurn = not False
if Stones <= 0:
if YourTurn == True:
print("The A.I took the last stone it lost. You won the game!")
break
elif YourTurn == False:
print("You took the last stone you lost. The A.I won the game!")
break
I have no idea how you would make the code not go into the negatives, the if and elif statements I had before were being ignored by the code. I would appreciate any help.
import random
stonesLeft = random.randint(15, 30)
stonesToRemove = 0
userTurn = True
print("This is a game where players take turns taking stones from a pile of stones. The player who takes the last stone loses. The current stone count is: ", stonesLeft)
while stonesLeft > 0:
while userTurn == True and stonesLeft > 0:
stonesToRemove = int(input("How many stones do you want to remove?"))
if stonesToRemove > 3:
print( "You can't remove more than three stones at a time!
The current stone count is: " + str(stonesLeft) )
elif stonesLeft - stonesToRemove < 0:
print("There aren't that many stones left!") #Give user error!
else:
stonesLeft -= stonesToRemove
print( "You removed " + str(stonesToRemove) +
" stone(s)! The current stone count is: " + str(stonesLeft) )
userTurn = False
while userTurn == False and stonesLeft > 0:
aiRemoves = random.randint( 1, min(3, stonesLeft) ) #Take smaller value between 3 and the stones that are left
stonesLeft -= aiRemoves
print( "The A.I. removed " + str(aiRemoves) +
" stone(s)! The current stone count is: " + str(stonesLeft) )
userTurn = True
if userTurn == True:
print("The A.I took the last stone, it lost. You won the game!")
else:
print("You took the last stone, you lost. The A.I. won the game!")
I'm writing code for a rock paper scissors game, it has a random number generator between 1-3 which simulates the computer's throw, and it works totally fine. What I'm trying to do is add a score counting system, for 3 different scores:
userWins
compWins
gamesPlayed
I also have a loop which allows you to play mulitple games.
but I can't find a way for the scores to update while playing.
Any help would be greatly appreciated,
You could define a global variable:
gamesPlayed = 0
userWins = 0
compWins = 0
def playOneRound():
global gamesPlayed
global userWins
global compWins
compThrow = getCompThrow()
userThrow = getUserThrow()
result = compareThrows(userThrow, compThrow)
if result == "Win":
print("Winner Winner Chicken Dinner")
print("-------------------------------------------------")
userWins += 1
elif result == "Lose":
print("Loser Loser Chicken Loser ")
print("-------------------------------------------------")
compWins += 1
else:
print("Tie")
print("-------------------------------------------------")
gamesPlayed += 1
Second, maybe better approach:
class Scores:
def __init__(self):
self.gamesPlayed = 0
self.userWins = 0
self.compWins = 0
scores = Scores()
def playOneRound():
compThrow = getCompThrow()
userThrow = getUserThrow()
result = compareThrows(userThrow, compThrow)
if result == "Win":
print("Winner Winner Chicken Dinner")
print("-------------------------------------------------")
scores.userWins += 1
elif result == "Lose":
print("Loser Loser Chicken Loser ")
print("-------------------------------------------------")
scores.compWins += 1
else:
print("Tie")
print("-------------------------------------------------")
scores.gamesPlayed += 1