The laughs parking garage contains a single lane that hold up to ten cars. Cars arrive at the south end of the garage and leave from the north end. If a customer arrives to pick up a car
that is not northernmost, all the cars to the north of his car are moved out, his car is driven out,
and the others cars are restored in the same order that they were in originally.
Whenever a car leaves, all the cars to the south are moved forward. So that at all the
times all the empty spaces are in the south part of the garage.
Write python program to reads a group of input lines. Each line contains an “a” arrival or
a “d” departure and a license plate number. Cars are assumed to arrive and depart in the order
specified by the input. The program should print a message each time that a car arrives or
departs. When a car arrives, the massage should specify whether or not there is room for the car
in garage. If there is no room for a car, the car waits until there is room or until a departure line is
read for the car. When room becomes available, another massage should be printed. When a car
departs, the massage should include the number of times the car was moved within the garage
(including the departure itself but not the arrival), this number is 0 if the car departs from the
waiting line.
this is my code. i stuck in middle of the code. i made a queue to park the cars. i don't no how to reassemble the cars when a middle car is departed. and i want a way to print the number of moves before the car depart in park. so anyone can help me?`
class Stack:
def __init__(self):
self.items =[]
def isEmpty(self):
return self.items ==[]
def push(self,item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[len(self.items)-1]
def size(self):
return len(self.items)
class Queue:
def __init__(self,maxSize):
self.items =[]
self._count = 0
self._front = 0
self._back = maxSize - 1
def isEmpty(self):
return self.items ==[]
def enqueue(self, item):
self.items.insert(0,item)
def dequeue(self):
return self.items.pop()
def size(self):
return len(self.items)
def index(self,item):
return self.items.index(item)
q1park = Queue(maxSize=10)
q2wait= Queue()
q3assemble= Queue()
x =raw_input("Car number: ")
def cararrival():
if x[0]=="a":
while q1park.size ==10:
q1park.enqueue(x[1:len(x)])
print(x + "car is arrived")
if q1park.size ==10:
print("No room available in the garage")
x1=raw_input("do you want to wait: ")
if x1=="yes":
q2wait.enqueue(x[1:len(x)])
elif x1=="no":
print("see you next time")
else:
print("Enter yes or no")
def cardepart():
if x[0]=="d":
if x[1:len(x)] in q1park:
while not q1park.index(x[1:len(x)])==0:
q3assemble.enqueue(q1park.dequeue())
q3assemble.dequeue()
while not q3assemble.isEmpty:
My answer for above question is here.
#creating a class for car
class Car:
#initialization and creating properties
def __init__(self, licenseNum):
self.licenseNum = licenseNum
self.moveCount = 0
#increase the moveCount by 1
def move(self):
self.moveCount += 1
#get information to a string
def toString(self):
return "Car {0}\tmoves:{1}".format(self.licenseNum, self.moveCount)
#creating queue class for cars
class CarQueue:
#initialization
def __init__(self):
self.carList = []
#add car to the queue
def enqueue(self, car):
self.carList.append(car)
#remove car from the queue
def dequeue(self):
return self.carList.pop(0)
#return the car by license plate number
def getCar(self, licenseNum):
for car in self.carList:
if car.licenseNum == licenseNum:
return car
#check whether license plate number is in the car list or not
def contains(self, licenseNum):
return self.getCar(licenseNum)!=None
#remove car from the list
def remove(self, car):
if self.contains(car.licenseNum):
self.carList.remove(car)
#return the number of cars in the list
def size(self):
return len(self.carList)
#check whether list is empty of not
def isEmpty(self):
return self.size()==0
#return the index of the car in the list
def positionOf(self, car):
return self.carList.index(car)
#move forward all the cars in southern side of the position.
def moveCarsFrom(self, position):
for c in self.carList[position:]:
c.move()
#get information to a string
def toString(self):
carNameList = []
for car in self.carList:
carNameList.append(car.licenseNum)
return "[{0}]".format(" ".join(carNameList))
#creating class for the garage
class Garage:
#initialization with the given number of rooms in the garage
def __init__(self, maxSize):
self.carQueue = CarQueue()
self.maxSize = maxSize
#add car to the list, when arrive
def arrive(self, car):
self.carQueue.enqueue(car)
#remove car from the list and record movements of other cars to the southern side, when depart
def depart(self, car):
position = self.carQueue.positionOf(car)
self.carQueue.remove(car)
self.carQueue.moveCarsFrom(position)
#check whether the garage is full or not
def isFull(self):
return self.carQueue.size()==self.maxSize
#create new garage which can hold up to 10 cars
garage = Garage(10)
#create new CarQueue to store waiting cars
waiting = CarQueue()
header = """
##############################################
PARKING GARAGE
##############################################
Welcome!
"""
help = """
you have to input your command and press enter.
[a/d] [LICENSE PLATE NUMBER], for car arrival or departure
a, arrival
d, departure
help, show instructions
exit, quit the programme
show, show the queues in the garage and the waiting line
"""
#display the header
print("{0}Instructions:{1}\nPlease enter the command...".format(header, help))
#infinity loop to get user inputs again and again
while True:
#get user command
command = raw_input("\nlaughs> ")
#excecuting general commands
if command=="exit":
print("Good bye!\n")
break
elif command=="help":
print(help)
continue
elif command=="show":
print("Garage {0}: {1}".format(garage.carQueue.size(), garage.carQueue.toString()))
print("Waiting line {0}: {1}".format(waiting.size(), waiting.toString()))
continue
#get seperately the action character ('a' or 'd') and the license plate number from the command
action = ""
licenseNum = ""
try:
action,licenseNum = command.split()
except:
#show error message for invalid inputs
print("Invalid input! Try again. Enter 'help' for instructions")
Related
What is the best way to provide a string representation of everyone in the queue. A person with a value 0 or less will have infinite number of turns. When a person is removed from the queue, they are re-added to the queue if they still have turns left. My queue stays empty. The goal is to follow FIFO rules when it comes to queue.
class Queue:
# implementation of a Queue
def __init__(self):
# empty queue.
self.queue = []
def enqueue(self, value):
# Add an item to the queue - run code queue is empty
self.queue.insert(0, value)
def dequeue(self):
# Remove the next item from the queue.
value = self.queue[0]
del self.queue[0]
return value
def is_empty(self):
# check to see if queue is empty
return len(self.queue) == 0
def __len__(self):
return len(self.queue)
def __str__(self):
result = "["
for item in self.queue:
result += str(item) + ", "
result += ", "
result += "]"
return result
class Taking_Turns_Queue:
class Person:
# define name and turns
def __init__(self, name, turns):
self.name = name
self.turns = turns
def __str__(self):
# display a person
if self.turns <= 0:
result = "({}:Forever)".format(self.name)
else:
# Add zero and 1 below. THe orginal code had zero.
result = "({}:{})".format(self.name, self.turns)
return result
def __init__(self):
"""
Start with an empty queue
"""
self.people = Queue()
def add_person(self, name, turns):
"""
Add new people to the queue with a name and number of turns
"""
person = Taking_Turns_Queue.Person(name, turns)
self.people.enqueue(person)
def get_next_person(self):
if self.people.is_empty():
print("No one in the queue.")
else:
person = self.people.dequeue()
if person.turns > 1:
person.turns -= 1
self.people.enqueue(person)
print(person.name)
def __len__(self):
"""
Support the len() function
"""
return len(self.people)
def __str__(self):
"""
Provide a string representation of everyone in the queue
"""
return str(self.people)
# Test Cases
# Test 1
# Scenario: Create a queue with the following people and turns: Bob (2), Tim (5), Sue (3) and
# run until the queue is empty
# Exepcted Result: Bob, Tim, Sue, Bob, Tim, Sue, Tim, Sue, Tim, Tim
print("Test 1")
players = Taking_Turns_Queue()
players.add_person("Bob", 2)
players.add_person("Tim", 5)
players.add_person("Sue", 3)
print(players)
while len(players) > 0:
players.get_next_person()
# Defect(s) Found:
print("=================")
# Test 2
# Scenario: Create a queue with the following people and turns: Bob (2), Tim (5), Sue (3)
# After running 5 times, add George with 3 turns. Run until the queue is empty.
# Exepcted Result: Bob, Tim, Sue, Bob, Tim, Sue, Tim, George, Sue, Tim, George, Tim, George
print("Test 2")
players = Taking_Turns_Queue()
players.add_person("Bob", 2)
players.add_person("Tim", 5)
players.add_person("Sue", 3)
for i in range(5):
players.get_next_person()
print(players)
players.add_person("George", 3)
print(players)
while len(players) > 0:
players.get_next_person()
# Defect(s) Found:
print("=================")
# Test 3
# Scenario: Create a queue with the following people and turns: Bob (2), Tim (Forever), Sue (3)
# Run 10 times.
# Exepcted Result: Bob, Tim, Sue, Bob, Tim, Sue, Tim, Sue, Tim, Tim
print("Test 3")
players = Taking_Turns_Queue()
players.add_person("Bob", 2)
players.add_person("Tim", 0)
players.add_person("Sue", 3)
print(players)
for i in range(10):
players.get_next_person()
print(players)
# Defect(s) Found:
print("=================")
# Test 4
# Scenario: Try to get the next person from an empty queue
# Exepcted Result: Error message should be displayed
print("Test 4")
players = Taking_Turns_Queue()
players.get_next_person()
# Defect(s) Found:
Your FIFO isn't a FIFO. Start with something like this before complicating things with people and turn counts.
class FIFO:
def __init__(self):
self.buffer = []
def add(self,item):
self.buffer.insert(0,item)
def get(self):
return self.buffer.pop()
def __str__(self):
if len(self.buffer) == 0:
return "[]"
out = "[" + ''.join([f'{item},' for item in self.buffer])
return out[:-1]+"]"
mybuf = FIFO()
mybuf.add("one")
mybuf.add("two")
mybuf.add("three")
assert mybuf.buffer == ["three", "two", "one"]
_item = mybuf.get()
mybuf.add(_item)
assert mybuf.buffer == ["one", "three", "two"]
print("All tests passed.")
# All tests passed.
Once that's working, then you can take baby steps toward your goal.
class FIFO:
def __init__(self):
self.buffer = []
def add(self,item):
if item["Turns"] > 0:
self.buffer.insert(0,item)
def get(self):
person = self.buffer.pop()
person["Turns"] -= 1
return person
def __str__(self):
if len(self.buffer) == 0:
return "[]"
out = "[" + ''.join([f'{item},' for item in self.buffer])
return out[:-1]+"]"
def items(self):
return len(self.buffer)
# Test 1
# Expected result: Bob Tim Sue Bob Tim Sue Tim Sue Tim Tim
mybuf = FIFO()
mybuf.add({"Name":"Bob","Turns":2})
mybuf.add({"Name":"Tim","Turns":5})
mybuf.add({"Name":"Sue","Turns":3})
debug = False # Set this to true for more information
output = []
while mybuf.items() > 0:
person = mybuf.get()
if debug:
print(f"Got: {person['Name']}, Remaining turns: {person['Turns']}")
output.append(person["Name"])
mybuf.add(person)
if debug:
print(f"Buffer is: {mybuf}\n")
print(' '.join(output))
# Bob Tim Sue Bob Tim Sue Tim Sue Tim Tim
I am trying to create a Python program which has the details of power grids and the houses connected to each of those power grids.
I have mainly two tasks to handle, one to add houses to the connection list of each power grid and remove them.
Following is the class for my house:
class House:
def __init__(self, number, power):
self.house_no = number
self.power_required = power
self.assigned_propagator_no = -1
def assign_propagtor(self, number):
self.assigned_propagator_no = number
def __str__(self):
return f"house_no: {self.house_no} power_required: {self.power_required}"
I have a propagator class which is basically used to store all the details and connect between the houses and the power grids:
class Propagator:
def __init__(self, number, max_power):
self.propagator_no = number
self.maximum_power = max_power
self.power_remaining = max_power
self.houses_connected = list()
def __str__(self):
return f"no : {self.propagator_no} max_power: {self.maximum_power} power_remaining: {self.power_remaining}"
def connected_houses_info(self):
for house,_ in self.houses_connected:
print(house)
# check if the house is connected part of the list or not.
def is_house_present(self, house_no):
if house_no in self.houses_connected:
return self.houses_connected.index(house_no)
else:
return -1
# Add the house in the list.
# Before adding check if the house is already connected
def add_house(self, house:House):
if house.assigned_propagator_no != -1:
print('Already exists!')
else:
self.houses_connected.append(house.house_no)
# Remove the house from the list, before removing need to check
# if the house is in the assigned propoagtor list.
def remove_house(self, house_no:int):
pass
Similarly I have created the class for my power grid:
class PowerGrid:
def __init__(self):
self.propagators = dict()
# Adding the propagtor into in the dictionary.
# Check if the propagator is not part of the dictioary already
# It will not posess any value in the beginning.
def add_propagator(self, propagator:Propagator):
pass
# Removing the propagtor into in the dictionary.
# Check if the propagator is part of the dictioary or not
def remove_propagator(self, propagator_no):
pass
def add_house(self, house:House, propagator_no:int):
if propagator_no in self.propagators:
return self.propagators[propagator_no].add_house(house)
else:
return False
def remove_house(self, house_no:int, propagator_no:int):
if propagator_no in self.propagators:
return self.propagators[propagator_no].remove_house(house_no)
else:
return False
class Propagator:
def __init__(self, number, max_power):
self.propagator_no = number
self.maximum_power = max_power
self.power_remaining = max_power
self.houses_connected = list()
def __str__(self):
return f"no : {self.propagator_no} max_power: {self.maximum_power} power_remaining: {self.power_remaining}"
def connected_houses_info(self):
for house,_ in self.houses_connected:
print(house)
# check if the house is connected part of the list or not.
def is_house_present(self, house_no):
if house_no in self.houses_connected:
return self.houses_connected.index(house_no)
else:
return -1
# Add the house in the list.
# Before adding check if the house is already connected
def add_house(self, house:House):
pass
# Remove the house from the list, before removing need to check
# if the house is in the assigned propoagtor list.
def remove_house(self, house_no:int):
pass
The main function to create the power grid is as follows:
def create_power_grid():
power_grid = PowerGrid()
with open('app.csv', newline='') as csvfile: # app.csv image provided later
reader = csv.DictReader(csvfile)
for row in reader:
entity_type = row['Type']
if entity_type == "propagator":
propagator = Propagator(int(row['Entity_Number']), int(row['Power']))
power_grid.add_propagator(propagator)
elif entity_type == "house":
house = House(int(row['Entity_Number']), int(row['Power']))
house.assigned_propagator_no = int(row['Assigned_Propagator'])
power_grid.add_house(house, int(row['Assigned_Propagator']))
return power_grid
if __name__ == "__main__":
power_grid = create_power_grid()
for _, propagator in power_grid.propagators.items():
#Printing the propagator information
print(f"Propagator No : {propagator.propagator_no}")
print("------------Propagator Information-----------------")
print(propagator)
print("------------Connected Houses Information-----------------")
propagator.connected_houses_info()
print("\n")
print("----Removing House 1014 from Propagator 1002----")
if power_grid.remove_house(1014, 1002):
print("House 1014 is successfully removed from Propagator 1002")
else:
print("House 1014 is not connected with Propagator 1002")
print("\n----Removing House 1024 from Propagator 1003----")
if power_grid.remove_house(1024, 1003):
print("House 1024 is successfully removed from Propagator 1003")
else:
print("House 1024 is not connected with Propagator 1003")
I have made certain changes to the add_propagator function inside class PowerGrid as follows:
def add_propagator(self, propagator:Propagator):
if (propagator.propagator_no not in self.propagators.keys()):
self.propagators[propagator.propagator_no] = {}
self.propagators[propagator.propagator_no]['max_power'] = propagator.maximum_power
self.propagators[propagator.propagator_no]['houses'] = []
But I am getting an error:
AttributeError: 'dict' object has no attribute 'add_house'
for the following part:
def add_house(self, house:House, propagator_no:int):
if propagator_no in self.propagators:
return self.propagators[propagator_no].add_house(house)
else:
return False
I have a CSV file from which the values are fed in. The format of the CSV file looks like the following:
I am unable to understand how to define the addition of a house and removal of a house from this, any kind of help with explanation is appreciated.
To have a key correspond to a list in a dictionary in python, note that d[item] is a list::
d = dict()
for item in items_to_add:
if item not in d:
d[item] = []
d[item].append(the_other_item)
# in your case:
if propagator_no not in self.propagators:
self.propagators[propagator_no] = []
self.propagators[propagator_no].append(house)
Your problem is that self.propogators is a dictionary, and therefore has these functions, not add_house.
I'm trying to create a Parking Lot in OOP.
I got stuck in payment calculated.
The payment is only calculated in seconds, how can I make it hourly or part of it?
(Under function “VehicleLeaves” I calculated secondsDiff.seconds because if I change it to secondsDiff.hour the program will crash.)
My Code:
import datetime
class Cars:
def __init__(self, phone, car_type, plate):
self.__phone = phone
self.__car_type = car_type
self.__plate = plate
def __str__(self):
return f"Plate: {self.__plate}, Phone: {self.__phone}, Car Type: {self.__car_type}."
class ParkingLot:
def __init__(self, name, capacity=1):
''' return a ParkingLot object with name "name" '''
self.name = name
self.capacity = capacity
self.earnings = 0
self.rate = 15
self.carsAndEnterTime = {}
def SetCapacity(self, newCap):
''' change the capacity from the default 1 '''
if newCap < 1:
raise RuntimeError("Error: parking lot size cannot be less than 1")
self.capacity = newCap
def GetCapacity(self):
''' return parking lot capacity '''
return self.capacity
def GetEarnings(self):
''' return how much much parking has made '''
return self.earnings
def VehicleEnters(self, vehicle):
''' vehicle enters parking lot'''
# put car and its enter time in a dictionary
self.carsAndEnterTime[vehicle] = datetime.datetime.now()
if self.capacity == 0:
raise RuntimeError("Error: Parking lot full!")
self.capacity -= 1
def VehicleLeaves(self, vehicle):
''' vehicle leaves parking lot. when it leaves, charges money '''
secondsDiff = datetime.datetime.now() - self.carsAndEnterTime[vehicle]
self.earnings += self.rate * secondsDiff.seconds
# after earned money, delete vehicle from dictionary
del self.carsAndEnterTime[vehicle]
self.capacity += 1
def __str__(self):
''' prints basic information of parking lot '''
return f"Parking lot: {self.name} \nSpots open: {self.capacity} \nHourly rate:{self.rate}\n {self.carsAndEnterTime}\nEarnings: $ {self.earnings} "
Focus on the area in the code of time calculation:
def VehicleEnters(self, vehicle):
''' vehicle enters parking lot'''
# put car and its enter time in a dictionary
self.carsAndEnterTime[vehicle] = datetime.datetime.now()
def VehicleLeaves(self, vehicle):
''' vehicle leaves parking lot. when it leaves, charges money '''
secondsDiff = datetime.datetime.now() - self.carsAndEnterTime[vehicle]
self.earnings += self.rate * secondsDiff.seconds
# after earned money, delete vehicle from dictionary
del self.carsAndEnterTime[vehicle]
self.capacity += 1
result in seconds, for this example is 10 seconds:
Earnings: $ 150
How can I calculate instead of seconds in hours or part of an hour rate of 15$.
For example, an hour and a half equals to 30$
what i did worng?
You can do a roundup withceil of math module:
import math
secondsDiff = datetime.datetime.now() - self.carsAndEnterTime[vehicle]
hour_roundup = math.ceil(secondsDiff.seconds/3600)
I am aware that there is another post asking about simulated printers but I didn't find any actual answers to my own question there.
class LinkedQueue :
class _Node :
__slots__ = '_element', '_next'
def __init__(self, element, next = None):
self._element = element
self._next = next
def __init__(self) :
self._head = None
self._tail = None
self._size = 0
def __len__(self) :
return self._size
def is_empty(self) :
return self._size == 0
def first(self) :
if self.is_empty() :
raise Empty('Queue is empty')
return self._head._element
def dequeue(self) :
if self.is_empty():
raise Empty('Queue is empty')
answer = self._head._element
self._head = self._head._next
self._size -= 1
if self.is_empty() :
self._tail = None
return answer
def enqueue(self, e) :
newest = self._Node(e,None)
if self.is_empty() :
self._head = newest
else :
self._tail._next = newest
self._tail = newest
self._size += 1
class Printer:
def __init__(self, name, job_queue):
self._name = name
self._job_queue
self._current_job = None
class Empty(Exception) :
pass
def main():
p_jobs = LinkedQueue()
red = Printer("Red", p_jobs) # Creates Printer Red
green = Printer("Green", p_jobs) # Creates Printer Green
print("\nOptions:\n 1. Add Job \n 2. Print Pages \n 3. Status \
\n 4. Quit")
i = 0
while True:
n = str(input("\nChoice (Type the number): "))
if n == '1': # Add Job
i += 1
p = int(input("\nHow many pages? "))
j = p_jobs.job_list(i,p,next)
p_jobs.enqueue(j)
if n == '2': # Print Job
print()
p_jobs.dequeue()
i -= 1
if n == '3': # Status
print()
if n == '4': # Quit
print("\nGoodbye!")
break
This is the provided code for us. We are supposed to simulate two printers that print out pages from jobs using LinkedQueue and Node.
I have the main function barebones w/c consists of 4 options:
Add Job, Print Jobs, Status, and Quit
I have trouble understanding how to use (refer) to the enqueue and dequeue methods. Can somebody break down each part of this program so I can at least understand where to start. I also would appreciate any hints that tell me where to go from here. Thank you.
EDIT: I added my main function w/c is basically just a UI
While this is by no means a complete answer, it shows how to print out what's currently in a LinkedQueue instance.
First, add the following method to the class. It will allow the contents to be iterated.
class LinkedQueue:
def __iter__(self):
if self.is_empty():
return None # No jobs in print queue.
cur = self._head
while cur:
yield cur._element
cur = cur._next
Here's something demonstrating how to use it:
def test():
q = LinkedQueue() # Create a queue.
# Add some jobs to the LinkedQueue.
for j in range(3):
pages = randint(1, 10)
q.enqueue(('job #{}'.format(j), pages))
# Show what's currently in the LinkedQueue.
for v in q:
print(v)
# Modify the LinkedQueue and then show what's left in it.
j = q.dequeue()
print('\nafter removing one job')
for v in q:
print(v)
I'm trying to simulate a game of Counter Strike. Basically I have two teams with different players (all the players are identical for now) and I want them to "fight" and when all the players on one team are dead, the simulation should end.
I'm trying to understand why the simulation I'm running never ends. I feel like I'm misunderstanding some core element of simpy but I don't really know what.
All of the process and simpy related code are in main.py and player.py.
I'm trying to get my simulation to end once every player has "died".
Basically I want every player to be a process that constantly checks their surrounding area (the node they are in which is represented by the Hotspot class) to see if there are any enemies. If there are any enemies they will choose one at random and "attack" them. Once all of the players from any team have health below 0 the simulation should end and the team that won should increment their win count by 1.
EDIT: Also of note, when I ran it through pdb it seemed like none of the player's health were decreasing and that the play method wasn't being run.
EDIT 2: I don't think all of the code needs to be read to find the problem, I think it's mostly in the main and player files but I'm not 100% sure because the code loops infinitely without error
Here is my code
main.py
from player import Player
from game_map import Game_Map
from team import Team
from sides import Sides
import simpy
import pdb
def main():
team_a = Team("Team_A", Sides.CT)
team_b = Team("Team_B", Sides.T)
gmap = Game_Map()
gmap.spawn_team(team_a)
gmap.spawn_team(team_b)
env = simpy.Environment()
for team in (team_a, team_b):
for player in team.players:
env.process(player.play(env))
env.run(until=round(team_a, team_b, env))
def round(team_a, team_b, env):
while True:
if team_a.all_dead():
team_b.round_wins += 1
print team_b
env.exit()
if team_b.all_dead():
team_a.round_wins += 1
print team_a
env.exit()
if __name__ == "__main__":
main()
player.py
import simpy
from sides import Sides
import numpy as np
import pdb
class Player(object):
""" Class that represents a CSGO player"""
def __init__(self, steam_id, team, acc, hs_percentage):
# the player's id
self.steam_id = steam_id
# percentage of shots that hit, accuracy
self.acc = acc
# percentage of hits that hit the head
self.hs_percentage = hs_percentage
# the team
self.team = team
# the player's health, this changes when the teams "fight"
self.health = 100
# the current hotspot that the player is in
self.current_location = 0
# if the player is alive or dead
self.is_alive = True
def play(self, env):
"""Process that simulates the player's actions. This is run once every round until
the round is over"""
while(self.is_alive):
target = self.choose_target()
if target == -1:
continue
yield env.timeout(5)
else:
target.inflict_self(self.determine_damage())
yield env.timeout(5)
def determine_damage(self):
"""The amount of damage the player will inflict on the enemy"""
return 27
def choose_target(self):
"""Choose a target to attack from the enemies in the hotspot"""
# 1 - side converts 0 to 1 and 1 to 0
enemy_list = self.current_location.players[1 - self.team.side]
num_enemies = len(enemy_list)
# if there are no enemies currently in the same location of the player
# simply return 0
if num_enemies == 0:
return -1
# pick an enemy randomly from the list of enemies and return their object
return enemy_list[np.random.random_integers(0, num_enemies - 1)]
def get_side(self):
return self.team.side
def inflict_self(self, damage):
"""Inflict damage onto own class. If damage moves health below 0, mark the
player as "Dead" and remove them from the map"""
self.health = self.health - damage
if self.health <= 0:
self.current_location.players[self.team.side].remove(self)
self.is_alive = False
def __str__(self):
return "Steam id: {0}\tIs Alive: {1}\tCurrent Location: {2}".format(self.steam_id, self.is_alive, self.current_location)
def tests():
return
if __name__ == "__main__":
tests()
game_map.py
import networkx as nx
from hotspot import Hotspot
import matplotlib.pyplot as plt
class Game_Map(object):
""" Generic map that represents general outline of all counter strike maps"""
def __init__(self):
self.graph = nx.Graph()
self.spawns = [Hotspot()]
self.graph.add_node(self.spawns[0])
def add_team(team):
#side = team.side
# side is 0 because for testing the simulation
# we are only using one node
side = 0
for player in team.players:
self.spawns[side].move_into(player)
def spawn_team(self, team):
for player in team.players:
self.spawns[0].move_into(player)
def draw(self):
nx.draw(self.graph)
plt.show()
def tests():
"""Tests to see that Game_Map class works properly"""
# initialize the map
gmap = Game_Map()
gmap.draw()
# if this module is being run explicitly from the command line
# run tests to assure that this module is working properly
if __name__ == "__main__":
tests()
hotspot.py
import simpy
from player import Player
from team import Team
from sides import Sides
class Hotspot(object):
"""Hotspots are the representation for different areas of the map. This is where players 'fight'."""
def __init__(self):
self.players = [[], []]
def move_into(self, player):
side = player.get_side()
self.players[side].append(player)
player.current_location = self
return 1
def __eq__(self, other):
return id(self) == id(other)
def __hash__(self):
return id(self)
def tests():
"""Tests to see that hotspot works properly"""
hotspot_list = []
for i in range(5):
hotspot_list.append(Hotspot())
for spot in hotspot_list:
team_a = Team("team_a", Sides.CT)
team_b = Team("team_b", Sides.T)
spot.move_into(Player(1, team_a, .5, .5))
spot.move_into(Player(1, team_b, .5, .5))
print "Hotspot id = {0}".format(id(spot))
for team in spot.players:
for player in team:
print "player = {0} in team {1}".format(player, player.team)
if __name__ == "__main__":
tests()
sides.py
class Sides(object):
"""Enum object, simply represents CT (Counter Terrorists) as 0 and
T (Terrorists) as 1"""
CT, T = range(2)
team.py
from player import Player
class Team(object):
"""Class that holds critical team information"""
def __init__(self, name, side):
self.round_wins = 0
self.players = []
self.name = name
self.side = side
self.generate_team()
def all_dead(self):
count = 0
for player in self.players:
if player.is_alive == False:
count += 1
if count == 5:
return True
else:
return False
def __str__(self):
rep = "Team: {0}, Round Wins: {1}\n".format(self.name, self.round_wins)
for player in self.players:
rep += player.__str__() + '\n'
return rep
def generate_team(self):
for i in range(5):
self.players.append(Player(1, self, .5, .2))
__rep__ = __str__
requirements.txt
decorator==3.4.2
matplotlib==1.4.3
mock==1.0.1
networkx==1.9.1
nose==1.3.6
numpy==1.9.2
pyparsing==2.0.3
python-dateutil==2.4.2
pytz==2015.2
scipy==0.15.1
simpy==3.0.7
six==1.9.0
Your round() function is the culprit:
env.run(until=round(team_a, team_b, env))
def round(team_a, team_b, env):
while True:
if team_a.all_dead():
team_b.round_wins += 1
print team_b
env.exit()
if team_b.all_dead():
team_a.round_wins += 1
print team_a
env.exit()
The function contains an infinite loop without any yields. This means it never returns and env.run() isn’t even executed.
I have a feeling this might be an infinite loop:
while(self.is_alive):
target = self.choose_target()
if target == -1:
continue
yield env.timeout(5)
You probably want to yield before the continue (which is unneeded anyway).