Python Simple American Football Simulator Not Running - python

Simple football simulation for my class project. I simplified a lot of the rules and aspects of the game, so everything isn't very accurate compared to an actual football game. However, When I try running my function, only the line of code which prints the name of the QB throwing to the receiver prints. For example when I run it only, "Jared Goff throws to Brandin Cooks for 33 yards!" shows up in the display. How can I get the whole function to run/print? Not sure where I went wrong.
import random
rams_qb = ["Jared Goff"]
patriots_qb = ["Tom Brady"]
rams_receivers = ["Cooper Kupp", "Brandin Cooks"]
patriots_receivers = ["Julian Edelman", "Josh Gordon"]
rams_score = 0
patriots_score = 0
quarter_time = 900
def remaining_time():
global quarter_time
global rams_score
global patriots_score
if quarter_time > 0:
if random.randint(0,100) < 50:
return rams_possesion()
else:
return patriots_possesion()
elif quarter_time == 0:
if rams_score > patriots_score:
print ("Rams Win!")
else:
print ("Patriots Win!")
def rams_possesion():
global quarter_time
global rams_score
rams_ball_position = 50
rams_downs = 1
if rams_ball_position == rams_ball_position + 10:
rams_downs = 1
else:
rams_downs += 1
if rams_ball_position == 100:
rams_score == rams_score + 6
print ("RAMS TOUCHDOWN!")
return rams_fieldgoal
if rams_downs <= 4:
rams_yardage_gained = random.randint(0,50)
print ((random.choice(rams_qb)),("throws to"),
(random.choice(rams_receivers)),("for"),(str(rams_yardage_gained)),
("yards!"))
rams_ball_position == rams_ball_position + rams_yardage_gained
quarter_time -= random.randint(0,30)
if rams_downs >= 5:
return patriots_possesion
def rams_fieldgoal():
global rams_score
if random.randint(0,100) < 83:
rams_score == rams_score + 1
print ("RAMS SCORE FIELDGOAL!")
else:
print ("RAMS MISS FIELDGOAL")
return patriots_possesion
def patriots_possesion():
global patriots_score
patriots_ball_position = 50
patriots_downs = 1
if patriots_ball_position == patriots_ball_position + 10:
patriots_downs = 1
else:
patriots_downs += 1
if patriots_ball_position == 100:
patriots_score == patriots_score + 6
print ("PATRIOTS TOUCHDOWN!")
return patriots_fieldgoal
if patriots_downs <= 4:
patriots_yardage_gained = random.randint(0,50)
print ((random.choice(patriots_qb)),("throws to"),
(random.choice(patriots_receivers)),("for"),(str(patriots_yardage_gained)),
("yards!"))
patriots_ball_position == patriots_ball_position +
patriots_yardage_gained
if patriots_downs >= 5:
return rams_possesion()
def patriots_fieldgoal():
global patriots_score
if random.randint(0,100) < 87:
patriots_score == patriots_score + 1
print ("PATRIOTS SCORE FIELDGOAL!")
else:
print ("PATRIOTS MISS FIELDGOAL")
return rams_possesion()
remaining_time()

My best guess here is that your comparisons are not taking into account the fact that the values can go over the target. For example, when checking yardage, you're checking for equality to 100, but you aren't guaranteeing that the value won't go over 100. You have a similar bug with checking if the quarter_time == 0 when it should be <= 0 to make sure it triggers.
I can't tell you if changing these comparisons will fix your program, but try these changes and comment how the behavior changes.

Related

How do I compare two integers

limit_speed = 50
current_speed = int(input("speed now :"))
def displayPenalty(limit_speed, current_speed):
if current_speed - limit_speed == 0:
print("no charge")
elif current_speed - limit_speed == 20:
print("charge 20 dollars")
elif current_speed - limit_speed == 40:
print("charge 40 dollars")
How do I make this function work so that it will check the difference between the 2 integers and print out based on it?
I think this is what you are looking for:
limit_speed = 50
current_speed = int(input("speed now :"))
def displayPenalty(limit_speed, current_speed):
if current_speed <= limit_speed:
print("no charge")
else:
print(f'charge: {current_speed - limit_speed}')
You can simply check if one value is greater than the other. (I think you would want this)...
def displayPenalty(limit_speed, current_speed):
if current_speed>limit_speed: print(f"Charge {current_speed-limit_speed} dollars")
else: print("no charge")
see below (I think this is what you are looking for)
limit_speed = 50
def displayPenalty(limit_speed, current_speed):
delta = current_speed - limit_speed
if delta == 0:
print("no charge")
elif 0 < delta <= 20:
print("charge 20 dollars")
elif 20 < delta:
print("charge 40 dollars")
current_speed = int(input("speed now :"))
displayPenalty(limit_speed, current_speed)

Issue with variable defining

When I execute the following code, I get the error "player_normal_defense is not defined". I get what the issue is but if I had to define the variable inside the Defense function, it would be totally pointless since the variable stores the initial defense value for further usage. How should I solve this?
import random
import sys
import os
import time
from Entity import *
class Battle():
def Attack(self, attacker, defender):
damage = attacker.atk - defender.dif
defender.hp -= damage
def Defense(self, owner, defending, entity_id):
defense_boost = 10
if defending:
owner.dif += defense_boost
elif not defending:
if entity_id == 1:
owner.dif = player_normal_defense
elif entity_id == 2:
owner.dif = enemy_normal_defense
def Turn_Generator(self, pl, en):
turns_list = []
speed_product = pl.speed / en.speed
first_speed_product = speed_product
if speed_product >= 1:
turns_list.append("P")
elif speed_product < 1:
turns_list.append("E")
while len(turns_list) < 100:
if speed_product >= 2:
turns_list.append("P")
turns_list.append("P")
speed_product = 0.6
elif speed_product < 2 and speed_product >= 1:
turns_list.append("P")
if first_speed_product <= 0.5:
speed_product = first_speed_product
else:
speed_product = 0.6
elif speed_product <= 0.5:
turns_list.append("E")
turns_list.append("E")
speed_product = 1
elif speed_product > 0.5 and speed_product < 1:
turns_list.append("E")
if first_speed_product >= 2:
speed_product = first_speed_product
else:
speed_product = 1
return turns_list
def Combat(self, player, enemy):
turn_counter = 1
player_normal_defense = player.dif
enemy_normal_defense = enemy.dif
fighting = True
while fighting:
print(f"Turn {turn_counter}")
turns = self.Turn_Generator(player, enemy)
for current_turn in turns:
print(f"""
======================
YOUR HPs: ENEMY HPs:
{player.hp} {enemy.hp}
======================""")
print(f"""
================
Current turn: {current_turn}
================
===========
Next turns:
{turns[1]}
{turns[2]}
{turns[3]}
{turns[4]}
===========
""")
if current_turn == "P":
choice = input("1. Attack\n2. Defend\n")
if choice == "1":
self.Attack(player, enemy)
self.Defense(player, False, 1)
elif choice == "2":
self.Defense(player, True, 1)
else:
print("Lost your chance!")
elif current_turn == "E":
enemy_choice = random.randint(1, 2)
if enemy_choice == 2:
print("He attacks you!")
self.Attack(enemy, player)
self.Defense(enemy, False, 2)
else:
print("He defends himself.")
self.Defense(enemy, True, 2)
time.sleep(3)
os.system("clear")
turns.pop(0)
if player.hp <= 0:
print("You died!")
sys.exit(0)
elif enemy.hp <= 0:
print("YOU WON!")
fighting = False
break
turn_counter += 1
When entity is defending, instead of running a Defence function to add a bonus to entitys Defence score only if it is true, I would just not run the Defence function when attacking. When entity is defending then you can run the Defense (Bonus) function as;
def Defending():
defence_boost = 10
in the decision check;
if choice == "2":
self.dif += Defending()
One issue I believe you will have with the code is that you are raising the entitys .dif stat with each occurrence of defending. This means that when this has cycled multiple times the base dif may be too high for any attackers damage to do anything to the opponents health.

"while" loop exiting prematurely (python 3)

The while loop only runs once and exits as though the condition has been met, however, when debugging for whether the condition has been met externally (after the loop) it has not.
Here is my code:
iFile = open("snakein.txt")
line = iFile.readline()
finXStr,finYStr = line.split()
finX = int(finXStr)
finY = int(finYStr)
moves = []
snkX = 0
snkY = 0
while snkX != finX and snkY != finY:
if finX > 0 and finX != snkX:
moves.append("R")
snkX += 1
print("x moves")
elif finX < 0 and finX != snkX:
moves.append("L")
snkX -= 1
print("x moves")
elif finX == snkX:
moves.append("L")
snkX -= 1
print("x moves")
if finY < 0 and moves[-1] == "R":
moves.append("R")
snkY -= 1
print("y moves")
elif finY < 0 and moves[-1] == "L":
moves.append("L")
snkY -= 1
print("y moves")
elif finY > 0 and moves[-1] == "R":
moves.append("L")
snkY += 1
print("y moves")
elif finY > 0 and moves[-1] == "L":
moves.append("R")
snkY += 1
print("y moves")
elif finY == snkY:
moves.appebd("L")
snakeY -= 1
print("y moves")
output = moves
oFile = open("snakeout.txt", "w")
oFile.write(str(output))
The program is trying to make a "snake" move in the most efficient way to a specific target via certain moves, on a "cartesian plane" like setting.
It looks like while snkX != finX or snkY != finY: might make more sense in your context...

Python Class Setters Not Changing Variables

The closest thread I could find to my problem was this: Python setter does not change variable
It didn't really help, the volume and the channels are not changing at all. The first fucntion which is to "watch TV" works perfectly fine.
class TV(object):
def __init__(self, channel, volume):
self.__channel = channel
self.__volume = volume
def __str__(self):
out = ""
out += "You're on channel #" + str(self.__channel) + ", " + self.channelNetwork()
out += "\nVolume is currently at: " + str(self.__volume) + "/20"
return out
# a method that determines the name for each channel from 1-10
def channelNetwork(self):
c = self.__channel
if c == 1:
return "CBS"
elif c==2:
return "NBC"
elif c==3:
return "ABC"
elif c==4:
return "Fox"
elif c==5:
return "ESPN"
elif c==6:
return "PBS"
elif c==7:
return "CNN"
elif c==8:
return "Comedy Central"
elif c==9:
return "Cartoon Network"
elif c==10:
return "Nicklodeon"
# a volume slider that has a range from 0-20
def volumeSlider(self, newVolume):
v = self.__volume
if newVolume == "+":
v += 1
else:
v -= 1
if v < 0:
v = 0
if v > 20:
v = 20
def channelChanger(self, newChannel):
c = self.__channel
if newChannel == "+":
c += 1
else:
c -= 1
if c < 0:
c = 0
if c > 10:
c = 10
def main():
import random
randomChannel = random.randint(1,10)
randomVolume = random.randrange(21)
televsion = TV(randomChannel, randomVolume)
choice = None
while choice != "0":
print \
("""
TV Simulator
0 - Turn off TV
1 - Watch TV
2 - Change channel
3 - Change volume
""")
choice = input("Choice: ")
print()
# exit
if choice == "0":
print("Have a good day! :)")
elif choice == "1":
print("You relax on your couch and watch some TV")
print(televsion)
elif choice == "2":
newChannel = None
while newChannel not in ('+', '-'):
newChannel = input("\nPress '+' to go up a channel and press '-' to go down a channel: ")
televsion.channelChanger(newChannel)
elif choice == "3":
newVolume = None
while newVolume not in ('+', '-'):
newVolume = input("\nPress '+' to increase volume and press '-' to decrease volume: ")
televsion.volumeSlider(newVolume)
else:
print("\nSorry, but", choice, "isn't a valid choice.")
main()
input("\n\nPress enter to exit.")
The problem is, that when you do:
v = self.__volume
In:
def volumeSlider(self, newVolume):
v = self.__volume
if newVolume == "+":
v += 1
else:
v -= 1
if v < 0:
v = 0
if v > 20:
v = 20
Assigning to v won't affect self.__volume. You need to use self.__volume = 20 or whatever.
As an aside, don't use double-underscore name-mangling unless you actually need it. E.g. self.volume is fine.

Why doesn't the main while loop finish executing? It just hangs up somewhere

We are making this Black Jack program to test card counting methods. We are trying to get the auto play function working, and it does, but when we run it in a while loop the loop never finishes and exits.
"""
Eli Byers
Josh Rondash
Black_Jack.py
"""
import random
#---------- CLASSES -----------------------------------------------------------
class Card(object):
def __init__(self, rank, suit):
self.rank = rank
self.suit = suit
self.value = 0
if self.rank is "Ace":
self.value = 11
if self.rank.isdigit():
self.value = int(self.rank)
if self.rank in ["Jack", "Queen", "King"]:
self.value = 10
def __str__(self):
return "["+str(self.rank)+" "+str(self.suit)+"]"
class Deck(object):
def __init__(self, numofdecks):
self.deck = []
self.suit = [" Clubs", " Hearts", " Spades", " Diamonds"]
self.rank = ["Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"]
self.numofdecks = numofdecks
for i in range(self.numofdecks):
for r in self.rank:
for s in self.suit:
self.deck.append(Card(r,s))
def __str__(self):
deck_str = ""
for card in self.deck:
deck_str += str(card)+" "
deck_str = deck_str[:-1]
return deck_str
def __len__(self):
return len(self.deck)
def __getitem__(self,i):
return self.deck[i]
def __delitem__(self, i):
del self.deck[i]
def draw(self):
top_card = self.deck[0]
del self.deck[0]
return top_card
def addcard(self,card):
self.deck.append(card)
def shuffle(self): #Random shuffle function
a = len(self.deck)
b = a-1
for d in range(b,0,-1):
e = random.randint(0,d)
if e == d:
continue
self.deck[d],self.deck[e] = self.deck[e],self.deck[d]
return self.deck
class Player(object):
def __init__(self, bankroll):
self.hand = []
self.bankroll = bankroll
self.score = 0
self.bet = 0
self.count = 0
self.aces = 0
self.dealer_hand = []
def __str__(self):
hand = ""
for card in self.hand:
hand += str(card)+" "
return "Hand: "+hand+" Bank: "+str(self.bankroll)+" Bet: "+str(self.bet)+" Ct: "+str(self.count)+" A: "+str(self.aces)
def __getitem__(self, i):
return self.hand[i]
def getcard(self,Card):
self.hand.append(Card)
self.score = 0
ace = 0
for card in self.hand:
if card.rank == "Ace":
ace += 1
self.score += 1
else:
self.score += card.value
for a in range(ace):
if (self.score + 10) <= 21:
self.score += 10
self.updateCount(Card,"P")
def placebet(self, b=0):
if b != 0:
self.bankroll -= b
self.bet += b
else:
self.bet += input("Bankroll: "+str(self.bankroll)+" Ct: "+str(self.count)+" A: "+str(self.aces)+" Place bet: ")
self.bankroll -= self.bet
def updateCount(self, card, player):
if card.value in range(2,6):
self.count += 1
elif card.value is 10:
self.count -= 1
elif card.rank is "Ace":
self.aces += 1
if player == "D":
self.dealer_hand.append(card)
def makeBet(self):
bet = 0.1*self.bankroll
if self.count > 3:
c = 0
for i in range(self.count):
c += 1
if c == 3:
bet += 0.5 * bet
c = 0
elif self.count < -3:
bet -= 0.5 * bet
return bet
def Play(self):
if self.score < 17:
choice = 1 #hit
else:
choice = 2 #stand
return choice
class Dealer(object):
def __init__(self, Deck, discardpile, Player):
self.deck = Deck
self.discardpile = discardpile
self.player = Player
self.hand = []
self.score = 0
def __str__(self):
hand = ""
for card in self.hand:
hand += str(card)+" "
return "Dealer Hand: "+hand
def __getitem__(self, i):
return self.deck[i]
def draw(self):
cardval = self.deck.draw()
self.hand.append(cardval)
self.score = 0
ace = 0
for card in self.hand:
if card.rank == "Ace":
ace += 1
self.score += 1
else:
self.score += card.value
for a in range(ace):
if (self.score + 10) <= 21:
self.score += 10
player.updateCount(cardval,"D")
def deal(self, Player):
for i in range(2):
self.player.getcard(self.deck.draw())
self.draw()
def burn(self):
self.discardpile.addcard(self.deck.draw())
def blackjack(self):
if self.score == 21:
return True
else:
return False
class Table(Dealer, Player):
def __init__(self, Dealer, Player, Deck , discardpile):
self.dealer = Dealer
self.player = Player
self.deck = Deck
self.discardpile = discardpile
self.betplaced = 0
def initGame(self):
self.clearTable()
Deck.shuffle(self.deck)
self.dealer.burn()
def clearTable(self):
for card in self.player.hand:
self.discardpile.addcard(card)
for card in self.dealer.hand:
self.discardpile.addcard(card)
self.player.hand = []
self.dealer.hand = []
def playGame(self):
self.betplaced = self.player.placebet()
self.dealer.deal(self.player)
print self.player
print self.dealer
if self.dealer.blackjack():
print("Dealer Black Jack!")
elif self.player.score <= 21:
stand = 0
while self.player.score < 21 and stand == 0:
print("Use number Keys> Hit: 1 Stand: 2")
choice = input()
if choice == 1: # Hit
self.player.getcard(self.deck.draw())
elif choice == 2: # Stand
stand = 1
print self.player
print ("Your score is "+str(self.player.score))
while self.dealer.score <= 17 and self.player.score <= 21:
if self.dealer.score == 17:
for card in self.dealer.hand:
if card.rank == "Ace":
self.dealer.draw()
else:
self.dealer.draw()
print self.dealer
print ("Dealer score is "+str(self.dealer.score))
if self.dealer.score <= 21:
if (self.player.score > self.dealer.score) and (self.player.score <= 21) :
if self.player.score == 21:
self.player.bankroll += self.player.bet*2.5
else:
self.player.bankroll += self.player.bet*2
print ("Win")
elif self.player.score == self.dealer.score:
self.player.bankroll += self.player.bet
print("Push")
else:
print("You Lose")
elif (self.dealer.score > 21) and (self.player.score <= 21):
if self.player.score == 21:
self.player.bankroll += self.player.bet*2.5
else:
self.player.bankroll += self.player.bet*2
print ("Win")
else:
print("You Lose.")
self.player.bet = 0
self.player.dealer_hand = []
print
def autoPlay(self):
self.betplaced = self.player.placebet(int(self.player.makeBet()))
self.dealer.deal(self.player)
if (self.dealer.blackjack() == False) and (self.player.score <= 21):
stand = 0
while self.player.score < 21 and stand == 0:
choice = player.Play()
if choice == 1: # Hit
self.player.getcard(self.deck.draw())
elif choice == 2: # Stand
stand = 1
while self.dealer.score <= 17 and self.player.score <= 21:
if self.dealer.score == 17:
for card in self.dealer.hand:
if card.rank == "Ace":
self.dealer.draw()
else:
self.dealer.draw()
if self.dealer.score <= 21:
if (self.player.score > self.dealer.score) and (self.player.score <= 21):
if self.player.score == 21:
self.player.bankroll += self.player.bet*2.5
else:
self.player.bankroll += self.player.bet*2
print ("Win")
elif self.player.score == self.dealer.score:
self.player.bankroll += self.player.bet
print("Push")
else:
print("Lose")
elif (self.dealer.score > 21) and (self.player.score <= 21):
if self.player.score == 21:
self.player.bankroll += self.player.bet*2.5
else:
self.player.bankroll += self.player.bet*2
print ("Win")
else:
print("Lose")
self.player.bet = 0
self.player.dealer_hand = []
print self.player.bankroll
#----------- MAIN -----------------------------------
deck = Deck(6)
player = Player(500)
discardpile = Deck(0)
dealer = Dealer(deck, discardpile, player)
table = Table(dealer, player, deck, discardpile)
table.initGame()
while (player.bankroll > 0) and (player.bankroll < 1000):
table.autoPlay()
table.clearTable()
print "Game Over."
Just add some debug statements. You have multiple while loops in your methods. I'm sure a simple print statement will catch the errors in your logic.
DUDE, I found the infinite loop within 1 minute. lucky i had python installed on my box.
LINE 251
if (self.dealer.blackjack() == False) and (self.player.score <= 21):
stand = 0
while self.player.score < 21 and stand == 0:
print "in player score"
choice = player.Play()
if choice == 1: # Hit
self.player.getcard(self.deck.draw())
elif choice == 2: # Stand
stand = 1
while self.dealer.score <= 17 and self.player.score <= 21:
print "in dealer score"
print self.dealer.score
if self.dealer.score == 17:
for card in self.dealer.hand:
if card.rank == "Ace":
self.dealer.draw()
else:
self.dealer.draw()

Categories