calling function several times - python

I have another problem with my text game. I have written a function that generates a random mob depending on the roll.
def random_mob():
roll = twenty_sided_die.roll()
if roll <= 5 :
return Zombie()
elif roll <= 10:
return Ghul()
elif roll <= 15:
return Skeleton()
elif roll <= 19:
return Ghost()
else:
return Slime()
mob = random_mob()
Than I have a function called encounter:
def encounter():
for command, action in hero.COMMANDS.items():
print("Press {} to {}".format(command, action[0]))
while True:
command = input("~~~~~~~Press key to continue~~~~~~~")
if command not in hero.COMMANDS:
print("Not a valid command")
continue
print("You are fighting " + mob.name)
print("")
time.sleep(1)
break
while True:
if command:
hero.COMMANDS[command][1]()
PlayerAttack()
time.sleep(1)
if mob.hp > 0:
MonsterAttack()
time.sleep(1)
if hero.hp <= 0:
print("++++++You were killed++++++")
break
time.sleep(1)
else:
continue
When calling the function, random monster is being generated,fight and rolls begins. After each successful roll, monster looses its HP.
After the function ends I would like to call next encounter in the way that again a random mob is being generated and the fight starts over
Problem I have, that if I call encounter() again, it generates the same monster, with HP from previos fight, and the function ends after one roll.
How to deal with it?

You are not initializing hit points for the monster. Maybe mob should be an array, where you append/push new monster by encounter() method/function. Then, if during the fight the monster is killed you remove/pop it. For example (the monster to fight next is on top of the stack in this example, if the stack is empty fight is over):
#begin game
mob = []
...
# add monster object to the stack
mob.push(random_mob())
...
if mob.hp > 0:
#do fighting
else:
# remove monster object from the stack
mob.pop()

First, I think you've to learn how Python works and how variables manage their scope inside packages, classes and functions.
You should also learn more about general programming with objects to get started on a good foundation. You can find lots of tutorials on the web.
As said in the comments, your main problem is that your variable mob is never modified!
Here's an example of a factory that can randomly generate monsters when you call the function encounter():
from random import randint
class Zombie(object):
pass
class Ghul(object):
pass
class Skeleton(object):
pass
class Ghost(object):
pass
class Slime(object):
pass
class MobFactory(object):
# create() function will return a mob depending of roll value
#staticmethod
def create(roll):
if roll <= 5:
return Zombie()
elif roll <= 10:
return Ghul()
elif roll <= 15:
return Skeleton()
elif roll <= 19:
return Ghost()
else:
return Slime()
def encounter():
roll = randint(1, 20)
mob = MobFactory.create(roll)
print(mob.__class__)
if __name__ == '__main__':
# Here I simulate multiple call of encounter()
for _ in range(0, 3):
encounter()
I hope it will help you.

Related

How to make a Cage Fighting Simulation with user input instead of random for Python

Here is my code so far using random to pick moves:
import time
import random
PHealth = 10
CHealth = 10
PShots = [
"Great Body Shot To Your Opponent!",
"Nice Take Down!",
"Nice Punch!",
"Strong Kick!",
"You Have Him Pinned Against The Cage!",
"Excellent Counter-Shot!"
]
CShots = [
"You Took a Shot to the Body!",
"You Got Taken Down!",
"Strong Kick Hit You!",
"You Took A Big Punch!",
"You Are Pinned Against The Cage",
"Counter-Shot Got Ya!"
]
for i in range(20):
i = random.randint(0, 100)
if i >= 51:
print(random.choice(PShots))
CHealth = CHealth -1
if CHealth >= 1:
print("Player Health", PHealth)
print("Computer Health", CHealth)
time.sleep(5)
if i <= 50:
print(random.choice(CShots))
PHealth = PHealth -1
if PHealth >= 1:
print("Player Health", PHealth)
print("Computer Health", CHealth)
time.sleep(5)
if CHealth < 1:
print("What A Shot!")
time.sleep(1)
print("Down He Goes!")
time.sleep(1)
print("The Referee Has Stopped The Fight!!")
time.sleep(1)
print("Player Wins!!!")
break
if PHealth < 1:
print("What A Shot!")
time.sleep(1)
print("Down You Go!")
time.sleep(1)
print("The Referee Has Stopped The Fight!!")
time.sleep(1)
print("Computer Wins!!!")
break
Basically I'd like to understand how a player can input one move. So if a player inputs body shot it beats take down. If a player inputs kick it beats punch. If a player inputs take down it beats pinned against the cage, etc. Thinking 6-7 variations and counters.
Here is an idea of how you could implement something akin to what you seem to be looking for using a mix of classes and functions.
The following code should work with Python 3.9+ and has no additional dependencies.
First we define a Move class, instances of which need to have a name, a text_used (for when the player successfully uses the move), and a text_affected (for when move is used against the player). Each instance also stores a set of other Move objects, which it trumps, as well as a set of those it is trumped by. We have a helper method should_beat to easily define such a relationship between two moves.
class Move:
def __init__(self, name: str, text_used: str, text_affected: str, damage: int = 1) -> None:
self.name: str = name
self.text_used: str = text_used
self.text_affected: str = text_affected
self.damage: int = damage
self.trumps: set['Move'] = set()
self.trumped_by: set['Move'] = set()
def __str__(self) -> str:
return self.name
def should_beat(self, other_move: 'Move') -> None:
self.trumps.add(other_move)
other_move.trumped_by.add(self)
Next we define a Player class. Its instances have a name and an optional starting_health set to a previously defined constant by default.
A Player also has a use_move method that takes a Move object, another Player object (the opponent), and a second Move object (the move used by the opponent). That method checks which move beats which and calculates the health subtraction accordingly.
Finally, the Player object has win and lose methods that can be called to print out the win/loss statements when necessary.
class Player:
def __init__(self, name: str, starting_health: int = DEFAULT_STARTING_HEALTH) -> None:
self.name: str = name
self.health: int = starting_health
def __str__(self) -> str:
return self.name
def use_move(self, move: Move, vs_player: 'Player', vs_move: Move) -> None:
if vs_move in move.trumped_by:
self.health -= vs_move.damage
print(vs_move.text_affected)
elif move in vs_move.trumped_by:
vs_player.health -= move.damage
print(move.text_used)
else:
print(TEXT_NO_EFFECT)
def win(self, vs: 'Player') -> None:
print("What A Shot!")
sleep(1)
print(f"{vs} Goes Down!")
sleep(1)
print("The Referee Has Stopped The Fight!!")
sleep(1)
print(f"{self} Wins!!!")
def lose(self, vs: 'Player') -> None:
print("What A Shot!")
sleep(1)
print(f"Down You Go, {self}!")
sleep(1)
print("The Referee Has Stopped The Fight!!")
sleep(1)
print(f"{vs} Wins!!!")
Next, we want a function to define our moves and one that conveniently prints a list of moves to the terminal. Obviously you will want to expand the define_moves function to incorporate all your desired moves and their relationships. It should return a list of all your Move objects.
def define_moves() -> list[Move]:
kick = Move("kick", "Strong Kick!", "Strong Kick Hit You!")
punch = Move("punch", "Nice Punch!", "You Took A Big Punch!")
...
kick.should_beat(punch)
...
return [
kick,
punch,
]
def print_moves(moves_list: list[Move]) -> None:
print("Available moves:")
for i, move in enumerate(moves_list):
print(i, "-", move.name)
Now for the fun part, we need our main fighting loop. In each iteration, we prompt the player for a number that corresponds to an index in our list of moves defined earlier. (The player may also type h to see the moves again.) We do some checks to make sure we received a valid number to get our Move object.
Then we randomly chose a move for the computer opponent out of our moves list, and call our use_move method. It does the health calculations for us. So after that we just check, if someone is done to call the appropriate win or lose method and break out of the loop. Otherwise we print the current health stats and continue.
def fight_computer(player: Player, moves_list: list[Move]) -> None:
computer = Player(name="Computer")
while True:
string = input('Choose your move! (or type "h" to see available moves again)\n').strip().lower()
if string == 'h':
print_moves(moves_list)
continue
try:
i = int(string)
except ValueError:
print("You need to pick a number!")
continue
try:
move = moves_list[i]
except IndexError:
print("No move available with number", i)
continue
computer_move = choice(moves_list)
print(computer, "chose", computer_move)
player.use_move(move, vs_player=computer, vs_move=computer_move)
if player.health < 1:
player.lose(vs=computer)
break
if computer.health < 1:
player.win(vs=computer)
break
print(player, "health:", player.health)
print(computer, "health:", computer.health)
sleep(1)
Lastly, we need a main function to put it all together, prompt the player for his name, etc.
def main() -> None:
player_name = input("Enter your name: ").strip()
player = Player(player_name)
moves_list = define_moves()
print_moves(moves_list)
fight_computer(player, moves_list)
if __name__ == '__main__':
main()
Don't forget to add your imports and constant definitions to the start of the module:
from random import choice
from time import sleep
DEFAULT_STARTING_HEALTH = 10
TEXT_NO_EFFECT = "Your move had no effect!"
All together, this should give you a crude version of the game you described. Try it out. Hope this helps.

Simple Function Problem. Trying to make a simple dice roll race game that tracks the position when they roll the dice

Trying to figure out why the program won't run.
This is the error code I am getting:
update_position (random_roll_1, random_roll_2)
builtins.NameError: name 'random_roll_1' is not defined
I thought I had all the correct parameters but I guess not. Any help would be really appreciated
import random
from random import randint
#both of the players are able to roll out their turs
this is the function where the players can roll their dice and receive a random number
def roll_die(p1_move,p2_move):
if p1_move is True:
input('Press enter to roll the die for player 1')
random_roll_1 = randint(1,6)
random_roll_1 = str(random_roll_1)
print('Player 1 rolled ' + random_roll_1)
random_roll_1 = int(random_roll_1)
return random_roll_1
elif p2_move is true:
input('Press enter to roll the die for player 2')
random_roll_2 = randint(1,6)
random_roll_2 = str(random_roll_2)
print('Player 2 rolled ' + random_roll_2)
random_roll_2 = int(random_roll_2)
return random_roll_2
This part updates the position on where each player is after it rolls the dice. The players have to roll exactly 8 in order to win. Anything higher than that will cause the player to stay in its position
def update_position(random_roll_1, random_roll_2):
player_1_position = 0
player_2_position = 0
max_score = 8
if player_1_position < max_score:
if player_1_position + random_roll_1 > 8:
print('The roll was too high, player 1 stays in the same spot')
else:
player_1_position += random_roll_1
print('Player 1 moved up ' + random_roll_1 + ' spots!')
return player_1_position
elif player_2_position < max_score:
if player_2_position + random_roll_2 > 8:
print(' The roll was too high, player 2 stays in the same spot')
else:
player_2_position += random_roll_2
print('Player 2 moved up ' + random_roll_2 + ' spots!')
return player_2_position
this function checks to see if one of the players hit 8 as their score
#checks to see if any of the players have managed to reach the end of the game
def check_game_over(player_1_position, player_2_position):
if player_1_position == 8:
print('Player 1 has won!')
print('Thank you for playing!')
continue_game = False
return continue_game
elif player_2_position == 8:
print('Player 2 has won!')
print('Thank you for playing!')
continue_game = False
return continue_game
This function is what controls who's turn it is. I added in the roll dice function along with the update spot function as it would be easier to include them in one whole function together. This is where I am getting my problem.
#random_roll_1,random_roll_2, player_1_position, player_2_position
#change the turn over to the next player
def opponent():
p1_move = True
p2_move = False
if p1_move is True:
roll_die (p1_move, p2_move)
update_position (random_roll_1, random_roll_2)
p1_move = False
p2_move = True
return p1_move, p2_move
elif p2_move is True:
roll_die(p1_move, p2_move)
update_position (random_roll_1, random_roll_2)
p1_move = True
p2_move = False
return p1_move, p2_move
This function basically shows the user which location they are currently sitting at.
def display_state (player_1_position, player_2_position, p1_move, p2_move):
if p1_move is True:
player_1_position = str(player_1_position)
print('Player 1 is in ' + player_1_position + ' spot')
player_1_position = int(player_1_position)
elif p2_move is True:
player_2_position = str(player_2_positon)
print('Player 2 is in ' + player_2_position + ' spot')
player_2_position = int(player_2_position)
Not entirely sure if this function is right at all because I still don't understand main functions completely so not sure if this main function works
def main():
#display instructions
continue_game = True
while continue_game:
opponent()
display_state (player_1_position, player_2_position, p1_move, p2_move)
check_game_over(player_1_position, player_2_position)
main()
So there are a few errors in your program above. The runtime error you stated above is caused when you try to pass 2 variables into the update_position function before they have been defined.
roll_die (p1_move, p2_move)
## random_roll_1 and random_roll_2 have not been defined
update_position (random_roll_1, random_roll_2)
However, before you deal with this error, there is a key programming concept to understand. Global and Local variables.
A Global variable is one which the entire program can use. They are normally defined at the top of your program:
p1_move = True
p2_move = False
def roll_die(): ...
def main(): ...
etc
A Local variable is one which can only be used inside of the function it was created in.
def foo():
x = 10
y = 5
return x + y
In this example, the variables x and y are local variables and cannot be used in other functions of your program (as they only exist inside the function foo).
One thing to note, in the case where you pass a variable as a functional argument, then modify that variable in the function without returning the modified variable. That variable will only be modified inside that function, no where else. This is true for primitive data types (variables not passed by reference).
def foo(z):
z += 1
z = 5
foo(z)
print(z)
In this example, the output would be 5, not 6 as the modified z variable in the function foo has not been returned.
For this reason alone, global variables may seem like the better option, however in general global variables are a bad idea and it is recommended that you stick to using local variables.
More information about Global and Local variables.
With this knowledge, some of your errors may seem more obvious.
For example, in your function roll_die, you define 2 variables random_roll_1 and random_roll_2. However you try to use these variables in other functions, update_position for example.
I realise that you have tried to return each random_roll variable independently from the roll_die function, however you do not store these returned values.
# Original
roll_die (p1_move, p2_move)
# Correctly returned
random_roll = roll_die(p1_move, p2_move)
In the next line, you then try to use both random_roll_1 and random_roll_2 variables, even though you only know 1 of those variables at that stage.
# Original
update_position (random_roll_1, random_roll_2)
# Possible Correction
update_position(random_roll)
You would then have to redefine the update_position function, thinking about each player's go as if it happened one after another, and not both at the same time.
I would also like to emphasize the importance of reducing the amount of duplicate code in your program.
Your opponent function could instead be written as:
def opponent(p1_move, p2_move):
random_roll = roll_die(p1_move, p2_move)
update_position(random_roll)
p1_move = not p1_move
p2_move = not p2_move
return p1_move, p2_move
This refactoring has changed a few details, most importantly, the use of the not. This operator will turn True->False and False->True. For example, if p1_move is false, not p1_move is True.
In addition, the function has parameters p1_move, p2_move, as these variables will be required in other parts of your program, you should define them outside of this functions scope, and pass them as arguments into your other functions. And don't forget to store the return values!
Just to note, this function refactoring is an example of how to reduce duplicate code, and is designed to be used with your modified program.
There are a few more modifications required to make your program run, but I will let you work them out for yourself.

Why changing a function argument reflects to the main value that is I passed to that function?

I have tried to create a BLACKJACK game using python (actually I'm learning python). Currently I have not setup bet command (that is written in my Account class). I only takes name from my Account class.
I have a main file : blackjack.py
and two classes in files : deckofcards.py, account.py
I am only accessing name from account class, so I wont be putting that long mess here.
blackjack.py :
from account import Account
player = Account('kalaLokia')
cards = DeckOfCards()
play = False
playershand = []
dealershand = []
action = ''
blackjack = False
def showCards(items, name):
'''
Shows {name}'s cards and hand value
'''
print(f"{name}'s hand: ")
print(f"\t{' - '.join(items)}")
print(f"Hand value: {cards.handValue(items)}")
def bust(hand):
'''
Whether a someone has busted or not
'''
if(cards.handValue(hand) > 21):
return True
return False
def dealersMove():
'''
Dealers move: executes when player calls "stand"
Dealer perform hit until he gets bust, wins or his hand value becomes >= 17
When hand value is >17 and players has greater value, dealer loses ;-)
'''
global blackjack
if(cards.handValue(dealershand) == 21):
print('Dealer got a BLACKJACK')
print('Dealer WINS')
return
elif(blackjack):
print(f'{player.name} got a BLACKJACK')
print(f'{player.name} WINS')
blackjack=False
return
while(not bust(dealershand)):
if(cards.handValue(dealershand) > cards.handValue(playershand)):
print('Dealer WINS')
showCards(dealershand, 'Dealer')
break
elif(cards.handValue(dealershand) == cards.handValue(playershand)):
print("It's a TIE!!\n Dealer WINS")
break
elif(cards.handValue(dealershand) > 17):
print(f'Dealer loses\n{player.name} has WON.')
print(f'{cards.handValue(playershand)} > {cards.handValue(dealershand)}')
break
dealershand.append(cards.hit())
else:
print(f'Dealer busts! \n{player.name} has WON the game.')
def start():
'''
The actiona that can be performed
'''
global blackjack
if(cards.handValue(playershand) == 21):
blackjack = True
dealersMove()
return
while(not bust(playershand)):
action = input(
f"{player.name}'s turn: Do you want to hit or stand ? ").lower()
if(action == 'hit'):
playershand.append(cards.hit())
showCards(playershand, player.name)
elif(action == 'stand'):
dealersMove()
break
else:
print('Please enter a valid action !')
else:
print(f'{player.name} has been BUSTED')
if __name__ == "__main__":
print(f'Hello {player.name}, Welcome to BlackJack Game')
# Tell game rules here, may be
response = input('Do you want to start the game (Y/n)? ').lower()
if(response != 'y'):
play = False
print('You have been exited the game')
else:
play = True
# Ask for bet amount later
while(play):
cards = DeckOfCards()
cards.shuffle()
print('Cards on the table is now shuffled')
playershand = list(cards.initiate())
dealershand = list(cards.initiate())
print(
f"{player.name}'s hand:\n {playershand[0]} - {playershand[1]}\nHand value: {cards.handValue(playershand)}\n")
print(f"Dealer's hand:\n {dealershand[0]} - ?\n")
start()
if(input('Do you want to play again (Y/n)?').lower() != 'y'):
print('The End')
play = False
deckofcards.py :
import random
class DeckOfCards():
'''
All talks here is about cards
'''
cards = {'A':11,'K':10,'Q':10,'J':10,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9,'10':10}
def __init__(self):
'''
Initialize deck of cards
'''
self.deck = list(self.cards.keys())*4
def shuffle(self):
'''
Simply shuffles the deck of cards
'''
return random.shuffle(self.deck)
def handValue(self, hand):
'''
Calculates and returns the hand value, expecting a string value to be feeded.
'''
result = 0
for element in hand:
result = result + self.cards[element]
while('A' in hand and result > 21):
if(hand[0]=='A'):
result = result - 10
# Somehow this hand.pop is poping out from main value itself. Why ???
hand.pop(0)
if(hand == []):
break
return result
def hit(self):
'''
Pop out and returns the last card in the deck
'''
return self.deck.pop()
def initiate(self):
'''
Pop out 2 cards from the deck and return as a tuple
'''
return (self.deck.pop(), self.deck.pop() )
Issue:
When I have an ACE in my hand and my hand value is greater than 21, the while condition executes in the handValue function (which is in DeckofCards class) as it is. Problem is, after that while condition executes, playershand (declared in main file) I just passed to this handValue function gets empty. That is the hand.pop(0) actually seems popping out value from main object playershand itself (It seems me so).
When I press a hit after that, I get a single new card, all other cards are got popped out. I don't understand why it is so.
On hit(user enter hit) : actually I am passing playershand (cards on the player hand, it's a list) to function showCards (which is also in the main file) where it takes it as argument items and pass it to handValue function in the class DeckOfCards.
So why is it happening? even though I am passing playershand as an argument to other functions, how pop() function affecting playershand which has only access to hand object in the handValue class ?
I have my complete code in github repo to test out, the files in folder blackjack

Changing a local variable in multiple functions in Python?

background: I'm currently writing a text-based adventure and each enemy has a certain amount of turns you can attack it before it attacks back.
So to handle this the code sets an argument in the function for the fight dictating how many times you can attack.
def fight_sequence(rounds):
while rounds > 0:
attack = input()
if attack == magic:
magic("you teleport away to safety. Congratulations you have stayed alive through your journey and found a few souvenoirs. nice job!", 1, "you muster up all of your energy, chant the spell.... and nothing happens.Cthulu... seems unimpressed", 1, "")
elif attack == sword:
sword(1)
def magic(teleportmessage, teleportsuccess, firemessage, firefail, winmessage):
x = 0
while x == 0:
fightorflight = input("""you open the book to cast a spell
Do you want to try teleporting or use a fireball?""").lower()
if "teleport" in fightorflight:
if teleportsuccess = 1:
print(teleportmessage)
x = 1
else:
choice = input("You can't teleport out of this battle. Would you like to try a fireball?")
if choice == yes:
fightorflight = "fireball"
else:
x = 1
elif "fire" in fightorflight:
print(firemessage)
if firefail == 1:
choice = input("do you want to try to teleport instead?").lower()
if "yes" in choice:
fightorflight = "teleport"
else:
x = 1
else:
print(winmessage)
else:
print("Sorry not sure what you mean")
def sword(attacksuccess):
if attacksuccess == 1:
print("You pull out the sword and swing at the monster damaging it severely.")
else:
print("You pull out the sword and swing at the monster, but its immune to blunt objects.")
fight_sequence(3)
both magic() and sword() need to be able to decrease rounds by 1, originally i just did that before entering the magic or sword function. however some items to attack with allow you to attack more than once if you want so that won't work for them. Such as magic if they also choose to teleport. Is there a way to allow me to change the variable rounds while inside of another function?
I think using a return value might help but I'm not sure how to go about it
You can simply add a new argument to the magic function, and pass the 'rounds' variable through when you call it.
e.g.
def fight_sequence(rounds):
...
magic("some message", false, "fired", false, "you won", rounds)
def magic(teleportmessage, teleportsuccess, firemessage, firefail, winmessage, rounds):
Your passing through the variable (not just the value) so it will change in every context where rounds can be seen.
HTH.
I would recommend using classes to create this game rather than lots of functions, an example of a class in a hero game below.
class Hero:
def __init__(self):
self.health = 10
def eatApple(self):
self.health += 1
def takeDamage(self):
self.health -= 1
init function runs as class is initialized.
player = Hero()
print(player.health) # will print 10
player.takeDamage()
print(player.health) # will print 9
This way you can have global variables for you functions which can be changed in each function and is much more organised.

Need help writing algorithm in Python/Sage

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?

Categories