Last active
February 7, 2019 18:34
-
-
Save adamgotterer/292d595790d271bd2bacc26e039fde12 to your computer and use it in GitHub Desktop.
Python Elevator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# elevator.py | |
from random import randint | |
# from SimpleXMLRPCServer import SimpleXMLRPCServer # Python 2 | |
from xmlrpc.server import SimpleXMLRPCServer # Python 3 | |
MAX_FLOOR = 10 | |
current_floor = 0 | |
server = SimpleXMLRPCServer(("localhost", 8000), logRequests=False) | |
def elevator_request(): | |
from_floor = randint(1, MAX_FLOOR) | |
to_floor = randint(1, MAX_FLOOR) | |
if randint(0, 10) > 8 and from_floor != to_floor: | |
print("Someone on floor #%i requested to go to floor #%i" % (from_floor, to_floor)) | |
return (from_floor, to_floor) | |
return False | |
server.register_function(elevator_request) | |
def validate(floor): | |
global current_floor | |
if (current_floor == floor or floor == current_floor + 1 or floor == current_floor - 1) and (floor >= 0 or floor <= MAX_FLOOR): | |
print('\x1b[5;30;42m' + 'Elevator moved from ' + str(current_floor) + ' to ' + str(floor) + '\x1b[0m') | |
current_floor = floor | |
return True | |
else: | |
print('\x1b[6;37;41m' + 'Invalid move to ' + str(floor) + ', elevator is currently on ' + str(current_floor) + '\x1b[0m') | |
return False | |
server.register_function(validate) | |
def reset(): | |
global current_floor | |
current_floor = 0 | |
return True | |
server.register_function(reset) | |
print('\x1b[5;30;47m' + 'People are ready to use the elevator!' + '\x1b[0m') | |
server.serve_forever() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import time | |
# import xmlrpclib # Python 2 | |
from xmlrpc import client # Python 3 | |
#client = xmlrpclib.ServerProxy('http://localhost:8000') # Python 2 | |
elevator_client = client.ServerProxy('http://localhost:8000') # Python 3 | |
requests = [] | |
tick = 0 | |
while True: | |
print("Tick %i" % tick) | |
req = elevator_client.elevator_request() | |
if req: | |
print("Someone on floor #%i requested to go to floor #%i" % (req[0], req[1])) | |
requests.append(req) | |
tick = tick + 1 | |
time.sleep(1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment