Loops incorrectly then crashes - python

I've got a piece of code I'm working on for a school project and the basic idea is that there's a battle between two characters where the user can input 2 attributes to each character: Strength and Skill. Now there are also modifiers for skill and strength which is the difference of the player's skill and strength attributes, divided by 5 and then rounded down respectively. Then each player has a dice roll, depending on who got the higher roll, that player gets the skill and strength modifiers added to their given attributes whilst the one that lost gets the modifiers deducted from their score. This then repeats until the strength attribute of one of them reaches 0 where that player then dies and the game ends.
In my code, the dice rolling function runs twice, and then crashes for an unknown reason I cannot identify.
import random
import time
import math
import sys
strength_mod = 0
skill_mod = 0
def delay_print(s):
for c in s:
sys.stdout.write( '%s' % c )
sys.stdout.flush()
time.sleep(0.05)
def str_mod(charone_str,chartwo_str):
if charone_str > chartwo_str:
top = charone_str
bottom = chartwo_str
calc = top - bottom
calc = calc / 5
calc = math.floor(calc)
return calc
elif chartwo_str > charone_str:
top = chartwo_str
bottom = charone_str
calc = top - bottom
calc = calc / 5
calc = math.floor(calc)
return calc
elif charone_str == chartwo_str:
top = charone_str
bottom = chartwo_str
calc = top - bottom
calc = calc / 5
calc = math.floor(calc)
return calc
def skl_mod(charone_skl, chartwo_skl):
if charone_skl > chartwo_skl:
top = charone_skl
bottom = chartwo_skl;
calc = top - bottom
calc = calc / 5
calc = math.floor(calc)
return calc
elif chartwo_skl > charone_skl:
top = chartwo_skl
bottom = charone_skl
calc = top - bottom
calc = calc / 5
calc = math.floor(calc)
return calc
elif charone_skl == chartwo_skl:
top = charone_skl
bottom = chartwo_skl
calc = top - bottom
calc = calc / 5
calc = math.floor(calc)
return calc
def mods():
global strength_mod
global skill_mod
strength_mod = str_mod(charone_strength, chartwo_strength)
skill_mod = skl_mod(charone_skill, chartwo_skill)
print "\nFor this battle, the strength modifier is:",strength_mod
time.sleep(0.20)
print "For this battle, the skill modifier is: ",skill_mod
time.sleep(0.20)
diceroll(charone, chartwo)
print "\n"+str(charone)+"'s","dice roll is:",player1
time.sleep(1)
print "\n"+str(chartwo)+"'s","dice roll is:",player2
def diceroll(charone, chartwo):
print "\n"+str(charone)+" will roll the 6 sided dice first!"
time.sleep(0.5)
global player1
player1 = random.randint(1,6)
delay_print("\nRolling dice!")
global player2
player2 = random.randint(1,6)
time.sleep(0.5)
print "\nNow",chartwo,"will roll the 6 sided dice!"
time.sleep(0.5)
delay_print("\nRolling dice!")
def battle(charone_str, chartwo_str, charone_skl, chartwo_skl, str_mod, skl_mod):
global charone_strength
global charone_skill
global chartwo_strength
global chartwo_skill
if player1 == player2:
print "\nThis round is a draw! No damage done"
elif player1 > player2:
charone_strength = charone_str + str_mod
charone_skill = charone_skl + skl_mod
chartwo_strength = charwo_skl - str_mod
chartwo_skill = chartwo_skl - skl_mod
print "\n"+charone+" won this round"
print "\n"+"Character 1:",charone
print "Strength:",charone_strength
print "Skill:",charone_skill
time.sleep(1)
print "\nCharacter 2:",chartwo
print "Strength:",chartwo_strength
print "Skill:",chartwo_skill
elif player2 > player1:
chartwo_strength = chartwo_str + str_mod
chartwo_skill = chartwo_skl + skl_mod
charone_strength = charone_str - str_mod
charone_skill = charone_skl - skl_mod
print "\n"+chartwo+" won this round"
print "\nCharacter 2:",chartwo
print "Strength:",chartwo_strength
print "Skill:",chartwo_skilll
time.sleep(1)
print "\n"+"Character 1:",charone
print "Strength:",charone_strength
print "Skill:",charone_skill
if charone_skill >= 0:
charone_skill = 0
elif chartwo_skill >= 0:
chartwo_skill = 0
if charone_strength <= 0:
print charone,"has died!",chartwo,"wins!"
elif chartwo_strength <= 0:
print chartwo,"has died!",charone,"wins!"
charone = raw_input("Enter the name of character one: ")
chartwo = raw_input("Enter the name of character two: ")
time.sleep(1.5)
print "\n",charone,"encounters",chartwo
delay_print("\nBattle Initiated!")
charone_strength = int(raw_input("\nEnter the strength score for "+str(charone)+" (between 50 and 100): "))
while charone_strength > 100 or charone_strength < 50:
print "That number is not between 50-100"
charone_strength = int(raw_input("\nEnter the strength score for "+str(charone)+" (between 50 and 100): "))
else:
pass
charone_skill = int(raw_input("Enter the skill score for "+str(charone)+" (between 50 and 100): "))
while charone_skill > 100 or charone_skill < 50:
print "That number is not between 50-100"
charone_skill = int(raw_input("Enter the skill score for "+str(charone)+" (between 50 and 100): "))
else:
pass
time.sleep(1.0)
chartwo_strength = int(raw_input("\nEnter the strength score for "+str(chartwo)+" (between 50 and 100): "))
while chartwo_strength > 100 or chartwo_strength < 50:
print "That number is not between 50-100"
chartwo_strength = int(raw_input("\n Enter the strength score for "+str(chartwo)+" (between 50 and 100): "))
else:
pass
chartwo_skill = int(raw_input("Enter the skill score for "+str(chartwo)+" (between 50 and 100): "))
while chartwo_skill > 100 or chartwo_skill < 50:
print "That number is not between 50-100"
chartwo_skill = int(raw_input("Enter the skill score for "+str(chartwo)+" (between 50 and 100): "))
else:
pass
time.sleep(2)
print "\nCharacter 1:",charone
print "Strength:",charone_strength
print "Skill:",charone_skill
time.sleep(1)
print "\nCharacter 2:",chartwo
print "Strength:",chartwo_strength
print "Skill:",chartwo_skill
time.sleep(1)
while charone_strength != 0 or chartwo_strength != 0:
ent = raw_input("Press Enter to roll! ")
mods()
diceroll(charone,chartwo)
battle(charone_strength, chartwo_strength, charone_skill, chartwo_skill, str_mod, skl_mod)
else:
play = raw_input("\nWould you like to play again?")
if play in ["yes","y","Yes","Y"]:
execfile("gcse.py")
else:
print "Goodbye"

This code is an excellent example of how not to program:
heavy use of global variables
multiple variables with very similar names (ie charone_strength, charone_str)
reuse of names in different contexts (in global scope, str_mod is a function, but in function battle it is supposed to be an integer
Your immediate problem: in line 182, you call
battle(charone_strength, chartwo_strength, charone_skill, chartwo_skill, str_mod, skl_mod)
which should be
battle(charone_strength, chartwo_strength, charone_skill, chartwo_skill, strength_mod, skill_mod)
but is confused because in the function strength_mod is referred to as str_mod.
Here is a greatly cleaned-up version. (Further suggestions for improvement are welcome).
from __future__ import division, print_function
from random import randint
import sys
from time import sleep
# Python 2/3 compatibility shim
if sys.hexversion < 0x3000000:
# Python 2.x
inp = raw_input
rng = xrange
else:
# Python 3.x
inp = input
rng = range
PRINT_DELAY = 0.02
PAUSE_DELAY = 0.2
TF_VALUES = {
'y': True, 'yes': True, 't': True, '': True,
'n': False, 'no': False, 'f': False
}
def get_int(prompt="Enter an integer: ", lo=None, hi=None):
while True:
try:
i = int(inp(prompt))
if (lo is None or lo <= i) and (hi is None or i <= hi):
return i
except ValueError:
pass
def get_tf(prompt="Yes or no? ", tf_values=TF_VALUES):
while True:
s = inp(prompt).strip().lower()
tf = tf_values.get(s, None)
if tf is not None:
return tf
def pause(delay=PAUSE_DELAY):
sleep(delay)
def roll(die_sides=6):
return randint(1, die_sides)
def slow_print(s, delay=PRINT_DELAY):
for ch in s:
print(ch, end='', flush=True)
sleep(delay)
print('') # end of line
def wait_for_enter(prompt):
inp(prompt)
class Fighter:
#classmethod
def get_fighter(cls, prompt):
print(prompt)
name = inp ("Name: ")
health = get_int("Health: (50-100) ", 50, 100)
skill = get_int("Skill: (50-100) ", 50, 100)
return cls(name, health, skill)
def __init__(self, name, health, skill):
self.name = name
self.health = health
self.skill = skill
def is_alive(self):
return self.health > 0
def health_mod(self, other_fighter):
delta = abs(self.health - other_fighter.health)
return int(delta / 5)
def skill_mod(self, other_fighter):
delta = abs(self.skill - other_fighter.skill)
return int(delta / 5)
def attack(self, other_fighter):
wait_for_enter("Hit Enter to fight!")
# figure out mod values
health_mod = self.health_mod(other_fighter)
skill_mod = self.skill_mod (other_fighter)
self_roll = roll()
other_roll = roll()
slow_print(
"Health mod: {} Skill mod: {} {} rolls {} {} rolls {}"
.format(
health_mod, skill_mod,
self.name, self_roll,
other_fighter.name, other_roll
)
)
# figure out who won this round
if self_roll == other_roll:
print("Draw! No damage done.")
else:
winner, loser = (self, other_fighter) if self_roll > other_roll else (other_fighter, self)
print("{} hits {}!".format(winner.name, loser.name))
winner.health += health_mod
winner.skill += skill_mod
loser.health -= health_mod
loser.skill -= skill_mod
# show results
print('')
print(self)
print(other_fighter)
print('')
def __str__(self):
return "{}: health {}, skill {}".format(self.name, max(self.health, 0), max(self.skill, 0))
def fight():
f1 = Fighter.get_fighter("\nFirst fighter:")
pause()
f2 = Fighter.get_fighter("\nSecond fighter:")
pause()
slow_print("\n{} encounters {}\nBattle Initiated!".format(f1.name, f2.name))
while f1.is_alive() and f2.is_alive():
f1.attack(f2)
winner, loser = (f1, f2) if f1.is_alive() else (f2, f1)
print("{} has died; {} wins!".format(loser.name, winner.name))
def main():
while True:
fight()
if not get_tf("Would you like to play again? (Y/n)"):
print("Goodbye!")
break
if __name__=="__main__":
main()

Related

Why does my movement system randomly break?

Here is the full code:
import random
import numpy as np
world = {}
class Player():
def __init__(self, health, maxHealth, baseDmg, dmg, name, weapons, items, isAlive, previousRoom, roomName):
self.health = health
self.maxHealth = maxHealth
self.baseDmg = baseDmg
self.dmg = dmg
self.name = name
self.weapons = weapons
self.items = items
self.isAlive = isAlive
self.previousRoom = previousRoom
self.room = world[roomName]
def Move(self, direction):
if direction not in self.room.exits:
print("Cannot Move In That Direction!")
return
newRoomName = self.room.exits[direction]
self.previousRoom = world[self.room.name]
print("Moving to", newRoomName)
self.room = world[newRoomName]
def MoveBack(self):
self.room = world[self.previousRoom.name]
print("Moving to", self.room.name)
class Enemy():
def __init__(self, health, dmg, hasLoot, lootItem, isAlive):
self.health = health
self.dmg = dmg
self.hasLoot = hasLoot
self.lootItem = lootItem
self.isAlive = isAlive
class Weapon():
def __init__(self, name, dmg, description):
self.name = name
self.dmg = dmg
self.description = description
class Item():
def __init__(self, name, amt, description):
self.name = name
self.amt = amt
self.description = description
class Room():
def __init__(self, name, description, exits, hasWeapon, weapon, hasItem, item, hasEnemy, enemy, isFirstVisit, coords):
self.name = name
self.description = description
self.exits = exits
self.hasWeapon = hasWeapon
self.weapon = weapon
self.hasItem = hasItem
self.item = item
self.hasEnemy = hasEnemy
self.enemy = enemy
self.isFirstVisit = isFirstVisit
self.coords = coords
#######################Dungeon Generation###################
rooms = np.zeros((11, 11))
maxRooms = 7
possibleNextRoom = []
def startLevel():
for r in range(len(rooms[0])):
for c in range(len(rooms[1])):
rooms[r][c] = 0
possibleNextRoom.clear()
halfHeight = int(len(rooms[1]) / 2)
halfWidth = int(len(rooms[0]) / 2)
rooms[halfWidth][halfHeight] = 1
def resetLevel():
for r in range(len(rooms[0])):
for c in range(len(rooms[1])):
rooms[r][c] = 0
possibleNextRoom.clear()
def countRooms():
roomCount = 0
for r in range(len(rooms)):
for c in range(len(rooms)):
if rooms[r][c] == 1:
roomCount += 1
return roomCount
def findPossibleRooms():
for r in range(len(rooms) - 1):
for c in range(len(rooms) - 1):
if rooms[r][c] == 1:
if rooms[r][c+1] != 1:
possibleNextRoom.append((r, c+1))
if rooms[r][c-1] != 1:
possibleNextRoom.append((r, c-1))
if rooms[r-1][c] != 1:
possibleNextRoom.append((r-1, c))
if rooms[r+1][c] != 1:
possibleNextRoom.append((r+1, c))
def addRoom():
x = random.randrange(0, len(possibleNextRoom))
rooms[possibleNextRoom[x][0]][possibleNextRoom[x][1]] = 1
possibleNextRoom.pop(x)
def generateLevel():
global x, possibleNextRoom
startLevel()
while countRooms() < maxRooms:
countRooms()
findPossibleRooms()
addRoom()
def makeRoomsForLevel():
counter = 1
for r in range(len(rooms)):
for c in range(len(rooms)):
if rooms[c][r] == 1:
world[f"room{counter}"] = Room(
f"room{counter}",
"",
{},
False,
None,
False,
None,
False,
None,
True,
(r, c)
)
counter += 1
def findRoom(x, y):
for i in range(len(world)):
if world[f"room{i+1}"].coords == (x, y):
return f"room{i+1}"
return None
def findExits():
for i in range(len(world)):
x, y = world[f"room{i+1}"].coords
exits = dict()
#east
if rooms[x, y+1] == 1:
exits["E"] = findRoom(x, y+1)
#south
if rooms[x+1, y] == 1:
exits["S"] = findRoom(x+1, y)
#west
if rooms[x, y-1] == 1:
exits["W"] = findRoom(x, y-1)
#north
if rooms[x-1, y] == 1:
exits["N"] = findRoom(x-1, y)
world[f"room{i+1}"].exits = exits
############################################################
generateLevel()
makeRoomsForLevel()
findExits()
WoodenSword = Weapon("Wooden Sword", 5, "A wooden sword. Looks like a kid's toy.")
IronDagger = Weapon("Iron Dagger", 8, "Small, sharp, and pointy. Good for fighting monsters!")
HealthPot = Item("Health Potion", 1, "A Potion of Instant Health. Restores 10 Health.")
goblin1 = Enemy(25, 2, True, [HealthPot, IronDagger], True)
player = Player(10, 10, 5, 5, "", [], [], True, "room1", "room1")
def ShowInv():
print("*******************************")
print("Name:", player.name)
print("Health:", player.health)
print("Weapons:")
for i in player.weapons:
print(" ===============================")
print(" Weapon:", i.name)
print(" Description:", i.description)
print(" Damage:", i.dmg)
print(" ===============================")
print("Items:")
for i in player.items:
print(" ===============================")
print(" Item:", i.name)
print(" Amount:", i.amt)
print(" Description:", i.description)
print(" ===============================")
print("*******************************")
def testItems(item):
exists = item in player.items
return exists
def fight(enemy):
print("Your Health:", player.health)
print("Enemy Health:", enemy.health)
ans = input("What would you like to do?\n>>")
if ans == "attack":
chance = random.randrange(1, 20)
if chance >= 10:
enemy.health -= player.dmg
else:
print("You did not roll high enough...\nYour turn has been passed...")
if ans == "heal":
chance = random.randrange(1, 20)
if testItems(HealthPot):
if chance >= 10:
x = 0
for item in player.items:
if item == HealthPot:
player.health += 10
if player.health > player.maxHealth:
player.health = player.maxHealth
item.amt -= 1
if item.amt <= 0:
player.items.pop(x)
break
x += 1
else:
print("You did not roll high enough...\nYour turn has been passed...")
if ans == "run":
chance = random.randrange(1, 20)
if chance >= 10:
player.MoveBack()
else:
print("You did not roll high enough...\nYour turn has been passed...")
if enemy.health > 0 and player.health > 0:
chance = random.randrange(1, 20)
if chance >= 10:
player.health -= enemy.dmg
else:
if enemy.health <= 0:
enemy.isAvile = False;
def testRoom():
if player.room.hasWeapon:
if player.room.isFirstVisit:
player.weapons.append(player.room.weapon)
if player.room.hasItem:
if player.room.isFirstVisit:
player.items.append(player.room.item)
if player.room.hasEnemy:
if player.room.isFirstVisit:
while player.room.enemy.health > 0:
fight(player.room.enemy)
player.room.isFirstVisit = False
while True:
command = input(">>")
if command in {"N", "S", "E", "W"}:
player.Move(command)
testRoom()
elif command == "look":
print(player.room.description)
print("Exits:", *','.join(list(player.room.exits.keys())))
elif command == "inv":
ShowInv()
elif command == "heal":
if testItems(HealthPot):
player.health += 10
if player.health > player.maxHealth:
player.health = player.maxHealth
else:
print("You don't have any", HealthPot.name, "\bs")
else:
print("Invalid Command")
And here is the problem:
Everything seems to work fine, until a couple moves in when it breaks and gives me a "KeyError: None" for the room I just walked in. I have no idea what could be causing this, and I am fairly new, so please simplify the explanations for me. I think it has something to do with the findExits() function and findRoom() function, but idk.
Here is the TraceBackError:
Traceback (most recent call last):
File "main.py", line 287, in <module>
player.Move(command)
File "main.py", line 26, in Move
self.room = world[newRoomName]
KeyError: None
I've tried fiddling with the function, but nothing i've tried worked. Here is the repl.it link:
https://replit.com/#samsonsbrother0/Dungeon-Crawler#main.py
your code is accessing a key before it exists, thus the error. to fix it, you need to assign the newroomname to the world dict as you move, like so:
print("Moving to", newRoomName)
world[newRoomName] = newRoomName
self.room = world[newRoomName]

TypeErr: Object "int" is not callable

I tried to make a "typing game" and at first, it worked out pretty nice. But when I translated my code to English (variable names, class names, function names etc.) it gave me the warning "Object int is not callable". How can I solve this?
Here's my code:
import time
import random
import sys
class Player():
def __init__(self, name, health = 5, energy = 10):
self.name = name
self.health = health
self.energy = energy
self.hit = 0
def inf(self):
print("Health: ", self.health, "\nEnergy: ", self.energy, "\nName: ", self.name)
def attack(self, opponent):
print("Attacking")
time.sleep(.300)
for i in range(3):
print(".", end=" ", flush=True)
x = self.randomAttack()
if x == 0:
print("Nobody attacks.")
elif x == 1:
print("{} hits {} !".format(name, opponentName))
self.hit(opponent)
opponent.health -= 1
elif x == 2:
print("{} hits {}!".format(opponentName, name))
opponent.hit(self)
self.health -= 1
def randomAttack(self):
return random.randint(0, 2)
def hit(self, hit):
hit.hitVariable += 1
hit.energy -= 1
if (hit.hitVariable % 5) == 0:
hit.health -= 1
if hit.health < 1:
hit.energy = 0
print('{} won the game!'.format(self.name))
self.exit()
#classmethod
def exit(cls):
sys.exit()
def run(self):
print("Running...")
time.sleep(.300)
print("Opponent catch you!")
#######################################################
print("Welcome!\n----------")
name = input("What's your name?\n>>>")
opponentName = input("What's your opponent's name?\n>>>")
you = Player(name)
opponent = Player(opponentName)
print("Commands: \nAttack: a\nRun: r\nInformation: i\nExit: e")
while True:
x = input(">>>")
if x == "a":
you.attack(opponent)
elif x == "r":
you.run()
elif x == "i":
you.inf()
elif x == "e":
Player.exit()
break
else:
print("Command not found!")
continue
It gives me the error at line 24 (self.hit(opponent)).
Your hit function is the problem. You have member and a function with the same name. Change one of them.
Also rename the hit argument of the hit(). You call it via self.hit(opponent) so I would rename it to def hit(self, opponent):.
def __init__(self, name, health = 5, energy = 10):
self.hit = 0
def hit(self, hit):
hit.hitVariable += 1
hit.energy -= 1
if (hit.hitVariable % 5) == 0:
hit.health -= 1
if hit.health < 1:
hit.energy = 0
print('{} won the game!'.format(self.name))
self.exit()

Python Elevator Code Simulation Error

I'm really new to this, and am always stuck by basic issues. Please can you show and explain my errors in this chunk of code. Right now the problem is that self is not defined, but I don't understand why.
It would be amazing if someone could clear this up.
import random
import time
class Building:
number_of_floors = 0
customer_list = []
elevator = 0
def __init__(self, floors, customers):
self.number_of_floors = floors
for customerID in range(1, customers + 1):
new = Customer(customerID,self.number_of_floors)
self.customer_list.append(new)
self.customer_list.sort(key = lambda x: x.current_floor)
self.elevator = Elevator(floors,self.customer_list)
self.run()
def run(self):
print('++++++++++++++++++++++++++ELEVATOR IS NOW STARTING+++++++++++++++')
print('Ther are %d customers in the building' % (len(self.customer_list)))
number_of_customers = len(self.customer_list)
self.output()
def output(self):
for customer in self.customer_list:
print("Customer",customer.customerID,"is on floor",customer.current_floor,"and wants to go",customer.destination_floor)
# ELEVATOR MOVING UP
while (self.elevator.current_floor <= self.number_of_floors) & (self.elevator.current_floor > 1):
self.elevator.current_floor -= 1
print(len(self.customer_list),'Customers in lift.')
print('ELEVATOR MOVING DOWN')
print('++++++++++++++++++++++++++++++++++++++++++++++++++++')
print('FLOOR',self.elevator.current_floor)
for customer in self.customer_list:
if (customer.in_elevator == True):
customer.current_floor = self.elevator.current_floor
if (slef.elevator.current_floor == customer.destination_floor) & (customer.in_elevator == True) & (customer.customer_direction == -1):
customer.in_elevator = False
self.customer_list.remove(customer)
print('Customer',customer.customerID,'has reached their destination')
print('There are',len(self.customer_list),'trapped in the elevator')
print('There are',len(Elevator.register_list),'people left on the register')
print('Elevator run is done!!!')
print('CUSTOMERS STUCK IN LIFT ARE BELOW')
for stuck in self.customer_list:
print('Cust. ID:',stuck.customerID,'Dest. Floor:',stuck.destination_floor,'Curr. Floor:',stuck.current_floor,'In Elevator',stuck.in_elevator,'Direction',stuck.customer_direction)
class Elevator:
number_of_floors = 0
register_list = []
current_floor = 0
up = 1
down = -1
def __init__(self, number_of_floors, register_list):
self.number_of_floors = number_of_floors
self.register_list = register_list
def move(self):
pass;
def register_customer(self, customers):
for reg in customers:
self.register_list.append(reg)
def cancel_customer(self, customers):
pass;
class Customer:
current_floor = 0
destination_floor = 0
customerID = 0
in_elevator = False
finished = False
customer_direction = 0
def __init__(self, customerID, floors):
self.customerID = customerID
self.current_floor = random.randint(1, floors)
self.destination_floor = random.randint(1, floors)
while self.destination_floor == self.current_floor:
self.desination_floor = random.randint(1, floors)
if self.current_floor < self.destination_floor:
self.customer_direction = 1
else:
self.customer_direction = -1
def header(): # elevator animation at beginning of program
print(" ELEVATOR OPENING ")
time.sleep(.2)
print("+++++++++++++++++++++++++++++||+++++++++++++++++++++++++++++++++++")
time.sleep(.2)
print("+++++++++++++++++++++++++| |++++++++++++++++++++++++++++++++")
time.sleep(.2)
print("++++++++++++++++| |+++++++++++++++++++")
time.sleep(.2)
print("++++++| |+++++++++")
time.sleep(.2)
print(" ")
time.sleep(.2)
print(" ELEVATOR CLOSING ")
time.sleep(.2)
print("++++++| |+++++++++")
time.sleep(.2)
print("++++++++++++++++| |+++++++++++++++++++")
time.sleep(.2)
print("+++++++++++++++++++++++++| |++++++++++++++++++++++++++++++++")
time.sleep(.2)
print("+++++++++++++++++++++++++++++||+++++++++++++++++++++++++++++++++++")
def main():
try:
floors = int(input('Enter the number of floors: '))
customers = int(input('Enter number of customers: '))
building = Building(floors, customers)
except ValueError:
print('YOU DIDNT ENTER A NUMBER. START AGAIN.')
main()
if __name__ == "__main__":
main()
You haven't indented the functions in your Building class.

Dice Poker Scoring System (Function producing NoneType)

So in my coding class we are required to make a "Dice Poker" game. We need to implement a scoring system, however, mine keeps returning a "None", therefore causing issues when I want to add the accumulated score to the base score of 100, since NoneTypes and integers can not be added. I'm aware that I need to fix whatever is causing the None, but I'm not sure how. I believe the problem could be in the "scoring" function, but perhaps it is more lurking in the later parts (After the #Choosing Last Roll or #Scoring output comments) of the function "diceGame". I'm very new to coding, and after hours of looking at this thing I'm not really sure what I'm looking at anymore. Thank you so much for your help!
Text-based dice game
from random import randint
def rollFiveDie():
allDie = []
for x in range(5):
allDie.append(randint(1,6))
return allDie
def outputUpdate(P, F):
print(P)
print(F)
def rollSelect():
rollSelected = input("Which die would you like to re-roll? (Choose 1, 2, 3, 4 and/or 5 from the list) ")
print(" ")
selectList = rollSelected.split()
return selectList
def rollPicked(toRollList, diceList):
for i in toRollList:
diceList[int(i) - 1] = randint(1,6)
def scoring(dList):
counts = [0] * 7
for value in dList:
counts[value] = counts[value] + 1
if 5 in counts:
score = "Five of a Kind", 30
elif 4 in counts:
score = "Four of a Kind", 25
elif (3 in counts) and (2 in counts):
score = "Full House", 15
elif 3 in counts:
score = "Three of a Kind", 10
elif not (2 in counts) and (counts[1] == 0 or counts[6] == 0):
score = "Straight", 20
elif counts.count(2) == 2:
score = "Two Pair", 5
else:
score = "Lose", 0
return score
def numScore(diList):
counts = [0] * 7
for v in diList:
counts[v] = counts[v] + 1
if 5 in counts:
finScore = 30
elif 4 in counts:
finScore = 25
elif (3 in counts) and (2 in counts):
finScore = 15
elif 3 in counts:
finScore = 10
elif not (2 in counts) and (counts[1] == 0 or counts[6] == 0):
finScore = 20
elif counts.count(2) == 2:
finScore = 5
else:
finScore = 0
return finScore
def printScore(fscore):
print(fscore)
print(" ")
def diceGame():
contPlaying = True
while contPlaying:
playPoints = 30
if playPoints > 9:
playPoints -= 10
else:
print("No more points to spend. Game Over.")
contPlaying = False
playing = input("Would you like to play the Dice Game? (Answer 'y' or 'n'): ")
print(' ')
if playing == 'y':
#First Roll
fiveDie = rollFiveDie()
outputUpdate("Your roll is...", fiveDie)
#Choosing Second Roll/Second Roll execution
pickDie = input("Which die would you like to re-roll? (Choose 1, 2, 3, 4 and/or 5 from the list) ")
print(" ")
pickDie = pickDie.split()
rollPicked(pickDie, fiveDie)
outputUpdate("Your next roll is...", fiveDie)
#Choosing Last Roll
pickDie = rollSelect()
rollPicked(pickDie, fiveDie)
outputUpdate("Your final roll is...", fiveDie)
#Scoring output
scoring(fiveDie)
finalScore = numScore(fiveDie)
playPoints += finalScore
print(playPoints)
else:
contPlaying = False
def main():
diceGame()
main()

List object occurrence checker python

I was working on a small project, and I've run across a little error in my programming. It's a basic battleship game, and so far I have two "ships" set, and I have the game to end when both on either my side or the enemy side is hit.
def enemy_board():
global enemy_grid
enemy_grid = []
for i in range (0,10):
enemy_grid.append(["="] * 10)
def random_row_one(enemy_grid):
return randint(0, len(enemy_grid) - 1)
def random_col_one(enemy_grid):
return randint(0, len(enemy_grid) - 1)
def random_row_two(enemy_grid):
return randint(0, len(enemy_grid) - 1)
def random_col_two(enemy_grid):
return randint(0, len(enemy_grid) - 1)
global x_one
x_one = random_row_one(enemy_grid)
global y_one
y_one = random_col_one(enemy_grid)
global x_two
x_two = random_row_two(enemy_grid)
global y_two
y_two = random_col_two(enemy_grid)
print(x_one)
print(y_one)
print(x_two)
print(y_two)
So that's the basis of my list, but later on in the code is where it's giving me a little trouble.
elif enemy_grid.count("H") == 2:
print("\nYou got them all!\n")
break
Update
Sorry I was a little unclear about what I meant.
def my_board():
global my_grid
my_grid = []
for i in range (0,10):
my_grid.append(["O"] * 10)
def my_row_one(my_grid):
int(input("Where do you wish to position your first ship on the x-axis? "))
def my_col_one(my_grid):
int(input("Where do you wish to position your first ship on the y-axis? "))
global x_mio
x_mio = my_row_one(my_grid)
global y_mio
y_mio = my_col_one(my_grid)
def my_row_two(my_grid):
int(input("\nWhere do you wish to position your other ship on the x-axis? "))
def my_col_two(my_grid):
int(input("Where do you wish to position your other ship on the y-axis? "))
global x_mit
x_mit = my_row_two(my_grid)
global y_mit
y_mit = my_col_two(my_grid)
def enemy_board():
global enemy_grid
enemy_grid = []
for i in range (0,10):
enemy_grid.append(["="] * 10)
def random_row_one(enemy_grid):
return randint(0, len(enemy_grid) - 1)
def random_col_one(enemy_grid):
return randint(0, len(enemy_grid) - 1)
def random_row_two(enemy_grid):
return randint(0, len(enemy_grid) - 1)
def random_col_two(enemy_grid):
return randint(0, len(enemy_grid) - 1)
global x_one
x_one = random_row_one(enemy_grid)
global y_one
y_one = random_col_one(enemy_grid)
global x_two
x_two = random_row_two(enemy_grid)
global y_two
y_two = random_col_two(enemy_grid)
print(x_one)
print(y_one)
print(x_two)
print(y_two)
title()
my_board()
enemy_board()
m = 20
guesses = m
while guesses > 0:
def printmi_board(my_grid):
for row in my_grid:
print(" ".join(row))
def printyu_board(enemy_grid):
for row in enemy_grid:
print (" ".join(row))
print(printmi_board(my_grid))
print(printyu_board(enemy_grid))
try:
guess_x = int(input("Take aim at the x-xalue: "))
except ValueError:
print("\nI SAID TAKE AIM!\n")
guess_x = int(input("Take aim at the x-xalue: "))
try:
guess_y = int(input("Take aim at the y-value: "))
except ValueError:
print("\nDo you have wax in your ears?? AIM!\n")
guess_y = int(input("Take aim at the y-value: "))
comp_x = randint(0, len(my_grid) - 1)
comp_y = randint(0, len(my_grid) - 1)
if x_one == guess_x and y_one == guess_y:
print("\nYou hit one! \n")
enemy_grid[guess_x - 1][guess_y - 1] = "H"
continue
elif x_two == guess_x and y_two == guess_y:
enemy_grid[guess_x - 1][guess_y - 1] = "H"
print("\nYou hit one! \n")
continue
elif enemy_grid[guess_x - 1][guess_y - 1] == "O":
print("\nYou've tried there before! Here's another round.\n")
print("You have " + str(guesses) + " rounds left, cadet.\n\n")
continue
elif enemy_grid.count("H") == 2:
print("\nYou got them all!\n")
break
else:
if guess_x not in range(10) or guess_y not in range(10):
print("\nThat's not even in the OCEAN!! Take another free round then.\n")
print("You have " + str(guesses) + " rounds left, cadet.\n\n")
continue
elif enemy_grid[guess_x][guess_y] == "O":
print("\nYou've tried there before! Here's another round.\n")
print("You have " + str(guesses) + " rounds left, cadet.\n\n")
continue
else:
print("\nYou missed, soldier!\n")
guesses = guesses - 1
print("You have " + str(guesses) + " rounds left, cadet.\n\n")
enemy_grid[guess_x - 1][guess_y - 1] = "O"
if comp_x == x_mio and comp_y == y_mio:
my_grid[comp_x - 1][comp_y - 1] = "H"
print("\nThe enemy hit you! \n")
continue
elif comp_x == x_mit and comp_y == y_mit:
my_grid[comp_x - 1][comp_y - 1] = "H"
print("\nThe enemy hit you! \n")
continue
elif my_grid.count("H") == 2:
print("We have to retreat! They've sunken all of your ships...")
break
else:
my_grid[comp_x - 1][comp_y - 1] = "="
continue
I'm using python 3 if that makes any difference. So it's that if the player hits the correct spot on the grid, then it'll show as "H" and not as "=" or "O". So I was just wondering about if I could count those "H"'s to use to end the IF loop.
You haven't really explained the problem, and so much of the code is missing that it's very hard to tell you what's wrong, I'm going to guess at it though.
My guess is that you create an '=' grid to represent a player's board, and then if their ship is 'hit' you replace the '=' in that position with an 'H'.
The structure you create (enemy_grid) seems to look something like:
[[====]
[====]
[====]
[....]]
in which case your test, enemy_grid.count("H") doesn't make sense as enemy_grid is a list that contains other lists (so the count of Hs will always be 0 - they're deeper down in the 2nd layer of lists).
You probably want a test more along the lines of:
[cell for row in enemy_grid for cell in row].count('H')

Categories

Resources