I'm trying to develop "Going to Boston" in python. A lot of the rules are explained in the code, as well as a lot of the code being explained in the comments. I'll answer any questions, but I'm having some issues with my output. Here is what I have.
# This code aims to recreate the game "Going to Boston" for four players.
# Rules:
# - Each player rolls three dice.
# – Each player keeps their highest die and sets it aside.
# – The remaining two dice are re-rolled and the highest of the two is set aside.
# – The last die is rolled and the final score is the sum of the three dice.
# ----------------------------------------------------------------------------------------------------------------------
# We'll use the random module for the dice.
import random
# This variable is just to count rounds
RoundCount = 0
# These global variables are being used to save the score of each player.
Score1 = 0
Score2 = 0
Score3 = 0
Score4 = 0
FinalScore = [] # We'll use this to decide the winner(s).
# Here is our class for player.
class Player:
def __init__(self, name):
self.name = name # Storing their name, just to more easily identify each player.
d1 = random.randint(1,6) # Randomly choosing a number from 1-6 to simulate a dice.
d2 = random.randint(1,6)
d3 = random.randint(1,6)
self.dice = [d1, d2, d3]
self.SavedDice = [] # We'll be using this variable to save dice.
def score(self):
# here is where dice are actually coded and saved.
# Here, we'll save the max value in dice.
self.SavedDice.append(max(self.dice))
self.dice.remove(max(self.dice)) # We're removing the max value, and maintaining the previous two dice.
for i in self.dice:
i = random.randint(1,6)
self.dice.append(i)
#return print(self.name,"\b's score is:",sum(self.SavedDice))
return(self.dice)
def __str__(self): # Here is where we return the saved dice.
return print(self.name,'Saved Dice:',self.SavedDice)
# Here is where we actually play.
# First, we setup the players.
Player1 = Player('Player 1')
Player2 = Player('Player 2')
Player3 = Player('Player 3')
Player4 = Player('Player 4')
# We'll use a loop to manage rounds.
while RoundCount < 3:
RoundCount += 1
# We use the __str__ method to show the currently saved dice.
Player1.__str__()
Player2.__str__()
Player3.__str__()
Player4.__str__()
# We'll assign values for scoring, to be used later, here
FScore1 = Player1.score()
FScore2 = Player2.score()
FScore3 = Player3.score()
FScore4 = Player4.score()
# Here is where we'll score each player.
# We'll first append all the final scores of each player to be compared.
FinalScore.append(FScore1, FScore2, FScore3, FScore4)
WinningScore = max(FinalScore)
if FScore1 == WinningScore:
print('Player 1 Won!')
if FScore2 == WinningScore:
print('Player 2 Won!')
if FScore3 == WinningScore:
print('Player 3 Won!')
if FScore4 == WinningScore:
print('Player 4 Won!')
# Just cleanly exiting the code.
print(' ')
exit('End of Game')
I end up getting an output like this, and I'm not sure why. I also need to keep def str(self): and use it.
Player 1 Saved Dice: []
Player 2 Saved Dice: []
Player 3 Saved Dice: []
Player 4 Saved Dice: []
Seems like it isn't looping all the way through or being cancelled somehow, and the values aren't being saved to self.SavedDice or SavedDice.
You're infinite-looping on the following block:
for i in self.dice:
i = random.randint(1,6)
self.dice.append(i)
Try replacing with SavedDice:
for i in self.dice:
i = random.randint(1,6)
self.SavedDice.append(i)
import random
# Here is our class for player.
class Player:
def __init__(self, name):
self.name = name # Storing their name, just to more easily identify each player.
d1 = random.randint(1,6) # Randomly choosing a number from 1-6 to simulate a dice.
d2 = random.randint(1,6)
d3 = random.randint(1,6)
self.dice = [d1, d2, d3]
self.saved_dice = [] # We'll be using this variable to save dice.
def roll(self):
# here is where dice are actually coded and saved.
# Here, we'll save the max value in dice.
max_dice = max(self.dice)
self.saved_dice.append( max_dice )
self.dice.remove( max_dice ) # We're removing the max value, and maintaining the previous two dice.
self.dice = [ random.randint(1,6) for _ in self.dice ] # recreate list with size of remained values
#property
def score(self):
return sum(self.saved_dice)
def __str__(self): # Here is where we return the saved dice.
return f'{self.name} Saved Dice: { self.saved_dice }'
def main():
max_players = 4
round_count = 0
# Create set of players
players = { Player(f'Player { i + 1 }') for i in range(max_players) }
while round_count < 3:
round_count += 1
for player in players:
# Roll each player per each round
player.roll()
print(player)
# Choosing winner player
winner = max( players, key=lambda p: p.score )
print(f'{winner.name} Won!')
print(' ')
exit('End of Game')
if __name__ == '__main__':
main()
Related
Ok, so I'm experiencing a weird error, and unfortunately, I don't know that I can show both examples here.
Take a look at the following code (apologies for the length):
import random
suits = ('Hearts', 'Diamonds', 'Spades', 'Clubs')
ranks = ('Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace')
values = {'Two':2, 'Three':3, 'Four':4, 'Five':5, 'Six':6, 'Seven':7, 'Eight':8,
'Nine':9, 'Ten':10, 'Jack':10, 'Queen':10, 'King':10, 'Ace':11}
class Card():
def __init__(self,suit,rank):
self.suit = suit
self.rank = rank
## Attributes listed in the __init__ statement do not have to
## correlate to called objects (ie: suit,rank)
self.value = values[rank]
## Values represents the integer value of each card as compared
## to it's string (word) based rank
def __str__(self):
return self.rank + " of " + self.suit
## Allows for printing in the form of X of Y, or Two of Hearts as an example
# Deck will be a compilation of all card objects to a single list
# that can then be shuffled, dealt from, etc.
class Deck():
def __init__(self):
## All cards starts off with a blank list
self.all_cards = []
## For each suit in suits
for suit in suits:
### For each rank in ranks
for rank in ranks:
#### Create the Card object equal to the suit and rank of the card
#### ie: Two of spades, three of clubs, etc.
created_card = Card(suit,rank)
#### Then append each card created to the self.all_cards list.
self.all_cards.append(created_card)
def shuffle(self):
## Method call to randomize the self.all_cards list internally
random.shuffle(self.all_cards)
def deal_one(self):
return self.all_cards.pop()
game_deck = Deck()
game_deck.shuffle()
## Checking to make sure the deck is full before continuing
print(len(game_deck.all_cards))
## Attempt without watching tutorial
class Player():
def __init__(self,name):
self.name = name
self.player_hand = []
self.balance = 100
self.bet = 0
def deposit(self,dep_amt):
self.balance += dep_amt
print(f'{dep_amt} added to balance. New balance is: ${self.balance}')
def withdraw(self,wit_amt):
self.balance -= wit_amt
print(f'{wit_amt} subtracted from balance. New balance is: ${self.balance}')
def player_bet(self,bet_amt = 0):
while True:
bet_amt = int(input("How much would you like to bet? \n"))
if bet_amt > self.balance:
print("Sorry, you don't have enough money, try again.")
elif bet_amt < 1:
print('Sorry, you must bet at least $1')
else:
print(f'Thanks, your bet is ${bet_amt}')
self.balance -= bet_amt
print(f'Your remaining balance is ${self.balance}')
break
## May need to be adjusted to clear the hand entirely, unsure
def remove_one(self):
return self.player_hand.pop(0)
# NOTE: The most cards a player can hold without busting is 11
def add_cards(self,new_cards):
### Single card object
self.player_hand.append(new_cards)
def __str__(self):
return f'{self.name} has a balance of ${self.balance}.'
## Attempt without watching tutorial
class Dealer():
def __init__(self,name):
self.name = name
self.player_hand = []
self.balance = 500
def deposit(self,dep_amt):
self.balance += dep_amt
print(f'{dep_amt} added to balance. New balance is: ${self.balance}')
def withdraw(self,wit_amt):
self.balance -= wit_amt
print(f'{wit_amt} subtracted from balance. New balance is: ${self.balance}')
def remove_one(self):
return self.player_hand.pop(0)
def add_cards(self,new_cards):
### Single card object
self.player_hand.append(new_cards)
def __str__(self):
return f'{self.name} has a balance of ${self.balance}.'
## Full Game Code
game_on = True
playing = False
while game_on == True:
game_check = input('Would you like to play Black Jack, Y/N? ').lower()
if game_check == 'y':
round_counter = 0
dealer_name = 'Klaus the Dealer'
dealer = Dealer(dealer_name)
player_name = input("Player One, what is your name? ")
player_one = Player(player_name)
print(f"Nice to meet you {player_name}, you'll be playing against {dealer_name}\n")
print(player_one)
print(dealer)
print("Let's play Black Jack!\n")
playing = True
else:
print('Ok, have a nice day')
game_on = False
break
while playing == True:
round_counter +=1
for x in range(2):
player_one.add_cards(game_deck.deal_one())
dealer.add_cards(game_deck.deal_one())
So when I run this code all at once, at the very last 2 lines, I get an index error when the code hits the player_one.add_cards(game_deck.deal_one()) stating IndexError: pop from empty list
The thing is, if I run this code in separate lines in a Jupiter notebook, and separate out the class calls from the rest of the game code, the player_one.add_cards(game_deck.deal_one()) works just fine.
Can anyone tell me what is causing this error?
You are running out of cards... :)
the line you reference is inside of an infinite loop.
while playing == True:
round_counter +=1
for x in range(2):
player_one.add_cards(game_deck.deal_one())
dealer.add_cards(game_deck.deal_one())
suggestion: while you are troubleshooting, just pop a little print statement in the deal_one() function to see what is being dealt and then delete it later.
Ok, so thanks to Jeff H for pointing out that the call for the card deal was inside an infinite loop, even though I couldn't fix the problem by breaking the loop itself, I did figure out how to start off the initial deal by absorbing it into the game_check statement above, like so:
while game_on == True:
game_check = input('Would you like to play Black Jack, Y/N? ').lower()
if game_check == 'y':
round_counter = 0
dealer_name = 'Klaus the Dealer'
dealer = Dealer(dealer_name)
player_name = input("Player One, what is your name? ")
player_one = Player(player_name)
print(f"Nice to meet you {player_name}, you'll be playing against {dealer_name}\n")
print(player_one)
print(dealer)
print("Let's play Black Jack!\n")
playing = True
for x in range(2):
player_one.add_cards(game_deck.deal_one())
dealer.add_cards(game_deck.deal_one())
This won't account for having to deal cards into the hand later while in another while loop, but it will fix the first issue.
I´m making a project for school and it is a dice game. This snippet of my code is like a catch 22.
I need to define a variable otherwise it flags, so I do this but then every time the button is run it changes the value to zero instead of increasing it.
if Rollnop1 == 0 :
Userscore1 = Randomnumber
print ("User 1 ",Userscore1 )
Rollnop1 = Rollnop1+1 #But this changes it so it will go to the next players roll, every
#time the button is pressed it changes the variable back to 0
def gamerun():
global Player
global usernamestr
global passwordstr
global usernamestr2
global passwordstr2
Rollnop1 = 0
def roll2():
Rollnop2 = 0
Randomnumber = random.randint(2,12)
print ("Console: Random Number 2 = ",Randomnumber)
if Rollnop2 == 0 :
Userscore2 = Randomnumber
print ("User 2 ",Userscore2 )
def roll1():
Rollnop1 = 0 #Need to define this here otherwise It wont work
Randomnumber = random.randint(2,12)
print ("Console: Random Number = ",Randomnumber)
if Rollnop1 == 0 :
Userscore1 = Randomnumber
print ("User 1 ",Userscore1 )
Rollnop1 = Rollnop1+1 #But this changes it so it will go to the next players roll, every
#time the button is pressed it changes the variable back to 0
else:
roll2()
actdicegame = Tk()
gamerunl0 = Label(actdicegame, text = usernamestr, fg = "black")
gamerunl0.pack()
gamerunl1 = Label(actdicegame, text = "Roll The Dice", fg = "black")
gamerunl1.pack()
gamerunb1 = Button(actdicegame, text="ROLL",fg="Black", command=roll1)#Register Butto
gamerunb1.pack()
actdicegame.geometry("350x500")
print ("Console: GUI RUNNING 1")
actdicegame.mainloop()
snippet https://pastebin.com/FSWwBGpA
Use an option where you provide the player as part of the roll, that way you say which player is playing at any given time. The function below plays for the provided player and returns who is playing next
def roll(Rollnop=0):
UserScore = random.randint(2,12)
print ("Console: Random Number 2 = ", UserScore)
if Rollnop == 0 :
print ("User 1 ", UserScore)
return 1
else:
print ("User 2 ", UserScore)
return 0
This could answer your question: nested function change variable in an outside function not working. Basically you need to assign Rollnop1 = 0 and Rollnop2 = 0 in gamerun and declare them as nonlocal inside roll1 & roll2 before attempting to change their value.
– DarrylG Thank You so much and to everyone else who helped.
More here
nested function change variable in an outside function not working
so I'm trying to make a scoring system using my current code for blackjack. The game is versus the computer and a player and the rules are a bit different , but that has all been setup. I need to purpose the code for scoring both player and computer's cards. I also should make it so an ace is set to be the value of 1, if to avoid busting. I was thinking of doing so as cards are drawn, but I'm not entirely sure. I tried cross class variables and I didn't find much success. Maybe I could fuse the player and deck classes?
Anyways, here is what I have, I'll provide any more information you need and there should be fairly thorough comments.
# This is a game of blackjack versus a computer.
# ------------------------------------------------------------------------------------------------------
# importing necessary files
import random
# A couple global variables for any necessary repeats and scoring.
RepeatCardChoice = 0
YourScore = 0
ComputerScore = 0
HitCount = 0 # The amount of times the player hits. Used for showing cards.
# Our deck itself.
class Card: # This is for developing the cards in the first place.
def __init__(self, suit, rank):
self.suit = suit
self.rank = rank
def show(self):
print(str(self.rank) + str(self.suit))
class Deck: # This is for deck behaviors and creating a deck.
def __init__(self):
self.cards = []
self.Cards()
def Cards(self):
for suit in ["S", "C", "D", "H"]: # S = Spades, C = Clubs, D = Diamonds, and H = Hearts
for rank in range(1, 14):
value = rank
if rank == 1:
rank = 'A' # Makes all 1 values = to ace.
elif rank == 11:
rank = 'J' # Makes all 11 values = to jack or j.
elif rank == 12:
rank = 'Q' # Makes all 12 values = to queen or Q.
elif rank == 13:
rank = 'K' # Makes all 13 values = to king or K.
if rank == (11) or (12) or (13):
value = 10
elif rank == 1:
value == 11
self.value = value
self.cards.append(Card(suit, rank))
def show(self): # Shows each card individually.
for card in self.cards:
card.show() # Really just reusing another function to display results.
def shuffle(self):
random.shuffle(self.cards)
def drawCard(self):
return self.cards.pop()
class Player: # This class is for player behaviors such as drawing and showing your hand.
def __init__(self, name):
self.name = name # Allows the player to choose their name.
self.hand = [] # Assigns their cards to a list, to be saved.
self.Deck = Deck()
def draw(self, deck, CardCount): # How the player draws one card at a time. It wasn't necessary to allow more.
count = 0
while count != CardCount:
count += 1
self.hand.append(deck.drawCard())
return self
def showHand(self, showCount): # Shows each card in the player's hand.
count = 0 # A counter is used to limit how much is drawn.
for card in self.hand: # This is so "card" doesn't stay an unresolved reference.
if count == showCount:
return
count += 1
card.show()
# Below is where we apply the classes and play the game. The computer will operate without input, unlike the player.
# Here is the deck.
deck = Deck()
deck.shuffle() # Shuffling the deck in preparation.
PlayerName = str(input('What is your name?')) # Just so the player can choose their name.
# Setting up the players.
Computer = Player("The Computer")
You = Player(PlayerName)
# Giving both players their hand to start off with.
Computer.draw(deck, 2)
You.draw(deck, 2)
# Here is where one card in each hand is shown.
print('You are showing:')
You.showHand(1)
print('The computer is showing:')
Computer.showHand(1)
# Here is where you decide to hit or stand.
while RepeatCardChoice == 0:
CardChoice = str(input('Hit (H) or Stand (S)?'))
if CardChoice == 'H':
You.draw(deck, 1)
HitCount += 1
You.showHand(1+HitCount)
RepeatCardChoice = 0 # This is so the player can keep deciding whether they still want to hit?
elif CardChoice == 'S':
RepeatCardChoice = 21 # Get it, because the winning score in blackjack is 21?
HitCount = 0
else:
RepeatCardChoice = 0
# Here is where we check your score.
if YourScore > 21:
exit('You busted and the computer wins!')
elif YourScore == 21:
exit('Blackjack, you win!')
# Here is where the computer hits or stands.
while ComputerScore <= 17:
Computer.draw(deck, 1)
HitCount +=1
Computer.showHand(1+HitCount)
if ComputerScore>21:
exit('The computer busted and you win!')
elif ComputerScore == 21:
exit('Blackjack, the computer wins!')
# Here is where we compare the scores to decide the winner.
if ComputerScore > YourScore:
exit('The computer wins!')
elif YourScore > ComputerScore:
exit('You win!')
elif ComputerScore == YourScore:
exit('You tied')
The output shouldn't provide any errors if the scoring system is successful, and I setup some variables that I might use to assign the score, however this can be changed as needed. Here is the output anyways.
What is your name?Sample
You are showing:
KC
The computer is showing:
JS
Hit (H) or Stand (S)?H
KC
8S
Hit (H) or Stand (S)?S
JS
...
Traceback (most recent call last):
File "Censored", line 119, in <module>
Computer.draw(deck, 1)
File "Censored", line 66, in draw
self.hand.append(deck.drawCard())
File "Censored", line 54, in drawCard
return self.cards.pop()
IndexError: pop from empty list
Essentially, what is happening is that the computer hits infinitely due to a lack of scoring, until there is nothing left to draw, this is after you stand. I skipped a lot of lines in the output, as they're just a bunch of cards getting drawn.
The project: Write a program in python in which the virtual dealer Jake plays against the virtual players: Mike and Will. Mike and Will are free to bet on different outcomes with different payout ratios. This will allow the comparison of various strategies. You should keep track of each player's bank roll (including the dealer)
The game is played with a 7 faced die with numbers [0 - 6] numbers[1, 2, 3] are blue and numbers [4, 5, 6] are green.
Correct Parity Pays: 2/1
Correct Colour Pays: 2/1
Exact Number Pays: 5/1
Here is the first draft with the modifications #Harvey Summer suggested. Comments on how I can improve the code's structure and performance are appreciated.
from random import choice
from random import randint
class die_face():
# This class is used to define the properties linked to each outcome on the dice.
def __init__(self, num, colour, parity):
self.num = num
self.colour = colour
self.parity = parity
# Determine the properties linked to each outcome on the dice.
zero = die_face(0, 'none', 'none')
one = die_face(1, 'blue', 'odd')
two = die_face(2, 'blue', 'even')
three = die_face(3, 'blue', 'odd')
four = die_face(4, 'green', 'even')
five = die_face(5, 'green', 'odd')
six = die_face(6, 'green', 'even')
options = [zero, one, two, three, four, five, six,]
class bet():
# Define the bets
def __init__(self, bet_type, odds):
self.bet_type = bet_type
self.odds = odds
num_bet = bet('num', 5)
colour_bet = bet('colour', 2)
parity_bet = bet('parity', 2)
class broker():
# Define the properties of the broker.
def __init__(self, name, balance):
self.name = name
self.balance = balance
def __str__(self):
result = "Name: {} \n" \
"Balance: {}" .format(self.name, self.balance)
return result
def modify_balance(self, amount):
self.balance += amount
main_broker = broker('Main',1e3)
def random_strategy():
# Bet a random amount on a random game with a random guess.
guess = 'empty'
game_mode= choice([num_bet, colour_bet, parity_bet])
if game_mode == num_bet:
guess = randint(0,6)
elif game_mode == colour_bet:
guess = choice(['blue','green'])
elif game_mode == parity_bet:
guess = choice(['even','odd'])
value = randint(1,10)
return game_mode , value, guess
class player():
# This class defines each player
def __init__(self, name, strategy, bank_roll):
self.name = name
self.strategy = strategy
self.bank_roll = bank_roll
def modify_balance(self, amount):
self.bank_roll += amount
def __str__(self):
result = "Name: {} \n" \
"Bank Roll: {}" .format(self.name, self.bank_roll)
return result
def play(self):
return self.strategy()
# Add the players
Will = player("Will",random_strategy,100)
def dealer(type, bet_value, guess):
#Roll the dice
correct = choice(options)
#Return amount based on Win or Lose
if type == num_bet.bet_type:
if correct.num == guess:
return num_bet.odds * bet_value - bet_value
else:
return -bet_value
if type == colour_bet.bet_type:
if correct.colour == guess:
return colour_bet.odds * bet_value - bet_value
else:
return -bet_value
if type == parity_bet.bet_type:
if correct.parity == guess:
return parity_bet.odds * bet_value - bet_value
else:
return -bet_value
def main_play(player):
# Collect the bets from the players
bets = player.play()
# Roll and return bets
amount = dealer(bets[0].bet_type, bets[1], bets[2])
# Distribute the money
main_broker.modify_balance(amount*-1)
player.modify_balance(amount)
print(player)
print(main_broker)
I would create a bettingtable as a broker where money is put at risk and the outcome to the dealer and players are exchanged based on the play outcome, and allow players and dealer to place bet and collect winnings. Encapsulate betting logic to the players and abstracted it from a game rules class. Each player should have a risk tolerance or game play style (lame, aggressive, cheater, etc.)
If you build this right, it shouldn't matter what the game is: dice, cards, etc. should basically play the same.
I'm a complete novice to python and sage so I need some help and clarification on the steps all the way through. This is a question concerning game theory.
First I will describe the algorithm and then I will propose a solution the best I can.
The algorithm:
I want to start the program with a random variable from 1-100. This
variable will be defined 'S'. I also want to define a set of variables
'C' which can be deducted from S every turn, this set is {1,2,3,4,5,6}
(in other words the user and computer can deduct 1, 2, 3, 4, 5 or 6
from S. If variable S is divisible by 7 (e.g. 21), then print: "I
lose". If not, the game can begin.
Let's say that the random variable turns out to be 20. The player is
now prompted to enter a number within the range of C. When the player
has entered the number, I want the program to deduct that number from
S, so if the player enters 4 (a legal move), S is then 20-4=16. The
computer then calculates mod(S,7) and finds out that modulo 16,7 is 2
so it deducts 2 from S, in other words, 16-2=14.
If the player enters a number which results in S being divisible by 7, such as 6 (20-6=14) then the computer simply deducts 1 and attempts to get to such a number again next round.
The game continues until the computer eventually wins as the player is
eventually placed at 7 and has to deduct a number which the computer
can finish with (user deducts 6, computer deducts the last one and
wins). Print: "I win".
So like I said, I have literally no experience in python and sage so I can only go by my (limited) java experience:
I would attempt to establish a variable S with some 'ran' element (no idea what it's called in python). I would then attempt something like:
if S%7=0 then print "I lose"
else
prompt "Pick a number between 1 and 6, those included".
Declare user input as variable U.
Do S-U=S
Now do S-S%7=S
Now I want the program to realize when S=7 and then print: "You lose". If you can help me go all the way, though, that would be great.
import random
def playgame():
s = random.randint(1,100) #grabs a random integer between 1 and 100
POSS = range(1,7) #range ignores the last number, so this is [1,2,3,4,5,6]
if not s % 7: #if s%7 != 0
print("I lose")
return #exit the function
while s > 0: #while s is still positive
choice = 0 #set choice to 0 (this may as well have been "foo",
# I just needed it to not be in POSS)
while choice not in POSS: #until the user picks a valid number
choice = int(input("Select a number between 1 and 6: ")) #prompt for input
s -= choice #subtract choice from s, then set the difference to s
print("You subtracted {}, leaving {}".format(choice,s)) #print for the user
comp_choice = s%7 #the computer's choice is always s%7
s -= comp_choice #subtract the comp's choice from s, then set the diff to s
print("I subtracted {}, leaving {}".format(comp_choice,s)) #print for user
print("I win!") #since we know computer will always win, I don't have to do a check
playgame() #run the function
Here's a vastly more complicated function that does essentially the exact same thing ;-)
class Entity(object):
"""Base class that should not be instantiated on its own -- only
exists to be inherited from. Use Player() and Computer() instead"""
def __init__(self,name=None):
if name is None:
name = input("What's your name? ")
self.name = name
self.myturn = False
def __str__(self):
# this magic function means calling str(self) returns str(self.name)
# included so I can do print(player)
return self.name
def makemove(self,choice):
"""finds the global s and subtracts a given choice from it,
printing the choice and the result to the user."""
global s
s -= choice
print("{} chooses {}, leaving {}".format(self,choice,s))
return choice
def activate(self):
self.myturn = True
return self
def deactivate(self):
"""does exactly self.myturn = False"""
self.myturn = False
class Player(Entity):
"""A player-controlled Entity"""
def getchoice(self):
"""Prompts the user for a choice, ensuring it's between 1 and 6, then
calls Entity's makemove() with that as an argument"""
choice = None
while choice not in range(1,7):
choice = int(input("Pick a number between 1 and 6: "))
return super().makemove(choice)
class Computer(Entity):
def __init__(self):
super().__init__(name="Computer Player")
#overrides to ensure every Computer object has the name Computer Player
def getchoice(self):
"""grabs a number for the computer, and makes its move"""
global s
choice = s%7
if choice == 0: #edge case where computer goes first on an s where s%7==0
choice = random.randint(1,6)
return super().makemove(choice)
class Game(object):
"""Class defining an instance of the Game
FUNCTIONS:
Game.start() <-- use this to start the game"""
def __init__(self,playerArray=[]):
"""defines s as a global, ensures the players array is built
correctly, and gives s a random int value between 1-100"""
global s
if type(playerArray) is Player:
playerArray = [playerArray]
while len(playerArray) < 2:
playerArray.append(Computer())
self.players = playerArray
s = random.randint(1,100)
def start(self):
"""Let's play!"""
global s
print ("""
====================================
THE GAME BEGINS NOW!!!
We will begin with a value of: {:3}
====================================""".format(s).lstrip())
turn = random.randint(1,len(self.players))-1
while True:
try:active_player = self.players[turn].activate()
except IndexError: print(turn)
choice = active_player.getchoice()
if s <= 0: break
active_player.deactivate() # is active_player.myturn = False
turn += 1
if turn == len(self.players): turn = 0 #wrap the list
for player in self.players:
#this will execute the turn s becomes zero
if player.myturn:
winner = player
break
print("Winner: {}".format(winner))
import random
game = Game()
game.start()
S=random.randint(1,100) #will pick a random number
user_input = int(raw_input("Enter a number:")) #will get an integer from the user
#subtraction and modulo work just like in any other language ...
if(condition):
do_something() #is the format for if statements
does that cover all your questions? or did I miss some?