def __init__(self, screen, player_list): self.player_list = player_list self.map = Map(player_list, size=3) self.map.create_map() self.map.draw_tiles(screen) self.map.draw_hex_positions(screen) # Make sure initiative order is up to date agenda_order = [] for player in player_list: player.update_initiative_order() agenda_order.append(player.get_initiative_order()) # Reorganizing the player iteration in initiative (absolute bloodbath) iterable = self.player_list.sprites() player_list = pygame.sprite.Group() for i in np.argsort(agenda_order): player_list.add(iterable[i]) # iterable[i].remove(self.player_list) # the sprite is in two groups i dont know what that means self.player_list = player_list self.player_list_cycle = cycle(self.player_list) self.current_player = next(self.player_list_cycle) self.turn_controller = TurnController( current_player=self.current_player) self.user_interface = UserInterface(current_player=self.current_player)
def __init__(self, screen, player_list): """ Initializing the Strategy Cards """ # Generating the cards self.player_list = player_list self.player_list_cycle = cycle(player_list) self.current_player = next(self.player_list_cycle) self.user_interface = UserInterface(self.current_player) self.available_strategy_cards = pygame.sprite.Group() for SC in StrategyCardSet: strategy_card_sprite = StrategyCard(SC) self.available_strategy_cards.add(strategy_card_sprite) # Locating them x_size, y_size = screen.get_size() y_pos = [y_size / 3, 2 * y_size / 3] x_pos = [x_size / 8, 3 * x_size / 8, 5 * x_size / 8, 7 * x_size / 8] locs = iter([(x, y) for x in x_pos for y in y_pos]) for SC in self.available_strategy_cards: x_sc, y_sc = SC.image.get_size() SC.image = pygame.transform.smoothscale( SC.image, (int(x_size / 8), int(x_size / 8 * y_sc / x_sc))) loc = next(locs) SC.update(rect=SC.image.get_rect(center=loc), image=SC.image)
def __init__(self): self.GUI = UserInterface() self.origin_lat = 0 self.origin_lng = 0 self.destination_lat = 0 self.destination_lng = 0 while (True): bar = self.GUI.Interface() if bar == -1: sys.exit() self.origin_lat, self.origin_lng = get_address_code( self.GUI.origin) self.destination_lat, self.destination_lng = get_address_code( self.GUI.destination) if self.origin_lng != None and self.destination_lng != None: break self.distance, self.time = get_distance_info(self.origin_lat, self.origin_lng, self.destination_lat, self.destination_lng) if (self.distance == None): sys.exit()
def browseProducts(self): matchingList = self.store.getProducts() toBeDisplayed = [("Product Id", ("Name, Unit, Source"))] ids = [] for matchingProduct in matchingList: tuple0 = matchingProduct.getId() ids.append(tuple0) theRest = matchingProduct.getName( ) + " " + matchingProduct.getUnit( ) + " " + matchingProduct.getSource() newTuple = (tuple0, theRest) toBeDisplayed.append(newTuple) UserInterface.displayList("The products are: ", toBeDisplayed, "", False) while True: choice = UserInterface.displayList( "View Product? ", [], "Input the product id to view details, Q to quit.") if choice.upper() == "Q": break elif choice in ids: self.viewProductByPrice(choice) break else: UserInterface.writeLine("Incorrect product Id")
class StrategyPhase: """ Handling the Strategy Phase of the game """ def __init__(self, screen, player_list): """ Initializing the Strategy Cards """ # Generating the cards self.player_list = player_list self.player_list_cycle = cycle(player_list) self.current_player = next(self.player_list_cycle) self.user_interface = UserInterface(self.current_player) self.available_strategy_cards = pygame.sprite.Group() for SC in StrategyCardSet: strategy_card_sprite = StrategyCard(SC) self.available_strategy_cards.add(strategy_card_sprite) # Locating them x_size, y_size = screen.get_size() y_pos = [y_size / 3, 2 * y_size / 3] x_pos = [x_size / 8, 3 * x_size / 8, 5 * x_size / 8, 7 * x_size / 8] locs = iter([(x, y) for x in x_pos for y in y_pos]) for SC in self.available_strategy_cards: x_sc, y_sc = SC.image.get_size() SC.image = pygame.transform.smoothscale( SC.image, (int(x_size / 8), int(x_size / 8 * y_sc / x_sc))) loc = next(locs) SC.update(rect=SC.image.get_rect(center=loc), image=SC.image) def handle_event(self, event, screen): # Have we clicked a tile if event.type == pygame.MOUSEBUTTONUP: for SC in self.available_strategy_cards: if SC.rect.collidepoint(event.pos): self.current_player.add_strategy_card(SC) self.move_to_next_player() SC.kill() phase_over = False if NB_OF_STRATEGY_CARD_DISTRIBUTED[len( self.player_list)] == 8 - len( self.available_strategy_cards): phase_over = True return phase_over def move_to_next_player(self): self.current_player = next(self.player_list_cycle) self.user_interface.change_main_color(self.current_player.color) def update(self, screen): self.available_strategy_cards.draw(screen) self.user_interface.draw(screen) def cleaning(self): for SC in self.available_strategy_cards: SC.kill() return self.player_list
class ActionPhase: """ Handling the Action Phase of the game """ def __init__(self, screen, player_list): self.player_list = player_list self.map = Map(player_list, size=3) self.map.create_map() self.map.draw_tiles(screen) self.map.draw_hex_positions(screen) # Make sure initiative order is up to date agenda_order = [] for player in player_list: player.update_initiative_order() agenda_order.append(player.get_initiative_order()) # Reorganizing the player iteration in initiative (absolute bloodbath) iterable = self.player_list.sprites() player_list = pygame.sprite.Group() for i in np.argsort(agenda_order): player_list.add(iterable[i]) # iterable[i].remove(self.player_list) # the sprite is in two groups i dont know what that means self.player_list = player_list self.player_list_cycle = cycle(self.player_list) self.current_player = next(self.player_list_cycle) self.turn_controller = TurnController( current_player=self.current_player) self.user_interface = UserInterface(current_player=self.current_player) def move_to_next_player(self): self.current_player = next(self.player_list_cycle) self.user_interface.change_main_color(self.current_player.color) def handle_event(self, screen, event): pass def update(self, screen): # Updating MAP on hover for tile in self.map.tiles: r_hex = tile.image.get_rect(topleft=tile.pos) if r_hex.collidepoint(pygame.mouse.get_pos()): tile.update(pos=tile.pos, image=tile.image, color=BLACK) else: tile.update(pos=tile.pos, image=tile.image, color=WHITE) self.map.tiles.draw(screen) self.map.draw_players(screen) self.draw_units(screen) self.map.draw_hex_positions(screen) self.user_interface.draw(screen) def erase(self, screen): pass def draw_units(self, screen): for this_player in self.player_list: this_player.draw_units(screen)
def init(host='localhost',server=None): """ Most of this code is copied from init() function in client.py Game initialization function. 1. Creates a L{Debugger} (debugger) and L{EventTimer} (eventTimer) and stores references to them in an instance of L{EventManager}. 2. Several listeners are started and registered with eventManager: - Instance of L{Universe} (universe) - Instance of L{UserInterface} (ui) - Instance of L{Window} (gameWindow) 3. We send the eventManager a message to start the game - This message is interpreted by the gameWindow """ #Creates a Debugger that posts events to the terminal for debugging purposes debugger = Debugger() eventTimer = EventTimer() #Create the event manager for low-level events eventManager = Manager(eventTimer,debugger) #FIXME: more specific manager\ Entity.manager = eventManager # World w is set to the activeWorld of the universe universe = Universe(eventManager) ui = UserInterface(eventManager,universe.activeWorld,'BROADCASTSERVER') gameWindow = Window(eventManager,width=1024,height=768) gameWindow.fullscreenMode = False gameWindow.updateScreenMode() w = World(universe) s.world=w networked = True client = GameClient(eventManager,host=s.host,port=1567) #wait until the client is assigned an ID before proceeding while client.ID == None: import time time.sleep(.02) print 'Got an ID',client.ID clientID = client.ID ui.setClientID(clientID) wManipulator = WorldManipulator(eventManager,w,networked,gameClientID = clientID) #generate the resources in the server, the existance of these #resources will propogate through to every client when they connect w._generateResources() #Notify the manager that the window should start to accept input: eventManager.post(Event.StartEvent()) return eventManager.eventTypesToListeners
def addProduct(self): inputs = UserInterface.displayForm( "Please give the details of the new product", [('Name', 'nstring'), ('Unit of Measure', 'nstring'), ('Price per unit', 'money'), ('Source/Origin', 'nstring'), ('shelfLife', 'int')]) self.store.addProduct(inputs[0], inputs[1], float(inputs[2]), inputs[3], int(inputs[4])) self.store.writeStore() UserInterface.writeLine("Product added.")
def removeCustomer(self): idlist = self.viewAllCustomerID() validInput = False while not validInput: customerId = input("Please input customer id, x to quit") if customerId in idlist: if self.store.getCustomer(customerId).getBalance() > 0: hasconfirmed = False while not hasconfirmed: confirm = UserInterface.displayConfirm( "The customer still has some balance, are you sure? ", "y or n ") if confirm.lower() == 'y': self.store.removeCustomer(customerId) UserInterface.writeLine("Customer removed.") validInput = True hasconfirmed = True elif confirm.lower() == 'n': UserInterface.writeLine("Cancelled.") hasconfirmed = True validInput = True else: UserInterface.writeLine("Invalid input.") else: self.store.removeCustomer(customerId) UserInterface.writeLine("Customer removed.") validInput = True elif customerId.upper() == "X": validInput = True else: pass
def logout(self): # ask for confirm from user if self.loginDetail is None: pass elif self.loginDetail == 'owner': self.store.owner.setLoggedIn(False) else: customer = self.store.getCustomer(self.loginDetail) customer.setLoggedIn(False) self.loginDetail = None UserInterface.writeLine("Logged out successfully.")
def viewAllProductID(self): toBeDisplayed = [] productIds = [] for product in self.store.getProducts(): id = product.getId() nameUnitSource = product.getName() + " " + product.getUnit( ) + " " + product.getSource() toBeDisplayed.append((id, nameUnitSource)) productIds.append(id) UserInterface.displayList("All product and their IDs: ", toBeDisplayed, "", False) return productIds
def viewAllCustomerID(self): toBeDisplayed = [] customerIds = [] for customer in self.store.getCustomers(): id = customer.getId() namePhoneAddressBalance = str(customer.getPhoneNumber()) + " " + \ customer.getAddress() + " " + str(customer.getBalance()) toBeDisplayed.append((id, namePhoneAddressBalance)) customerIds.append(id) UserInterface.displayList("All customers and their IDs: ", toBeDisplayed, "", False) return customerIds
def viewProductByBatch(self, productId): product = self.store.getProduct(productId) batches = product.getBatches() tuples = [("BatchId", "Price, Quantity, Expiry Date")] batchIds = [] for batch in batches: batchId = batch.getBatchID() batchIds.append(batchId) theRest = str(batch.getActualPrice()) + " " + str( batch.getQuantity()) + " " + str(batch.getExpiryDate()) tuples.append((batchId, theRest)) UserInterface.displayList("Batch details: ", tuples, "", False) confirm = UserInterface.displayConfirm("Edit batch ", "Do you wish to edit Batch?") if confirm.lower() == 'y' and len(batchIds) > 0: while True: batchId = UserInterface.displayForm( "Batch Id", [("Please input the batchID you would like to edit.", "number")])[0] #print(batchIds) if batchId in batchIds: self.editBatch(productId, batchId) break else: UserInterface.writeLine("Batch Id incorrect. Try again.") else: # ML added else condition so user doesn't get stuck when no batch exists. UserInterface.writeLine("No batches to edit.")
def unregisterSelf(self): confirm = UserInterface.displayConfirm( "Please confirm", "This action will remove your account. Are you sure?") if confirm == 'y': if self.store.getCustomer(self.loginDetail).getBalance() > 0: c2 = UserInterface.displayConfirm( "Balance remaining", "You still have balance remaining. Are you sure you want to unregister?" ) if c2 == 'y': self.store.removeCustomer(self.loginDetail) self.loginDetail = None UserInterface.writeLine( "Your account has been logged out and unregisted. Thanks for shopping with us!" ) return else: self.store.removeCustomer(self.loginDetail) self.loginDetail = None UserInterface.writeLine( "Your account has been logged out and unregisted. Thanks for shopping with us!" ) return UserInterface.writeLine("Cancelled.")
def removeProduct(self): idlist = self.viewAllProductID() validInput = False while not validInput: productIdInput = input("Please input id, x to quit") # productIdInput = UserInterface.displayForm("Id of the product to be removed: ", "please input Id, X to cancel ") if productIdInput in idlist: self.store.removeProduct(productIdInput) validInput = True UserInterface.writeLine("Product removed.") elif productIdInput.upper() == "X": validInput = True else: pass
def start(): logging.basicConfig( level=_LOG_LEVEL, format='%(asctime)s %(levelname)s %(name)s %(message)s', datefmt='%Y/%m/%d %I:%M:%S%p') global error_led error_led = LED(_ERROR_LED) error_led.off() logo = Image.open("Images/moon-icon.jpg") lcd_display.display(logo) # TODO: init the GPS # TODO: init the compass # TODO: zero out the azimuth using the compass # TODO: zero out the altitude using the limit switch # TODO: build a list of objects that are currently visible, and add them to the menu # initialize the user-interface state machine global _ui _ui = UserInterface("Moon Finder", lcd_display, top_menu, error_led, _UP_BUTTON, _CENTER_BUTTON, _DOWN_BUTTON, _LEFT_BUTTON, _RIGHT_BUTTON)
def editBatch(self, productId, batchId): valid = False while not valid: choice = UserInterface.displayList( "Edit options", [], "A. Edit Batch Price B. Edit Batch Quantity Q. Quit") if choice.upper() == 'A': self.editBatchPrice(productId, batchId) valid = True elif choice.upper() == 'B': self.editBatchQuantity(productId, batchId) valid = True elif choice.upper() == 'Q': valid = True else: UserInterface.writeLine("Invalid input.")
class Alfredo: def __init__(self): self.ui = UserInterface() def atender(self): questao = self.ui.ask("Olá, eu sou Alfredo. Em que posso ajudar?") self.ui.say("Você disse: " + questao) ie = InferenceEngine() fatos = ie.answer(questao) self.ui.say("".join(fatos)) while (True): questao = self.ui.ask("Posso ajudar em mais alguma coisa?") if ("não" in questao.lower()): break self.ui.say(ie.answer(questao)) self.ui.say("Obrigado e até logo")
class Common(): initialized = 0 # comment in these for user interface app = QtGui.QApplication(sys.argv) ui = UserInterface() def __init__(self): self.initialized = 0 def Init(self): self.iMower = IntelliMower() # comment in these for user interface self.ui.Init(800, 800) self.initialized = 1 def Frame(self): #self.iMower.Reset() #self.iMower.LoadMap() #self.iMower.SetState(0) #self.iMower.Calculate() # # #self.iMower.PlaceMower(685, 417) # #self.iMower.SetState(0) # #self.iMower.CalculatePath() # Comment in for user interface sys.exit(self.app.exec_())
def login(self): inputs = UserInterface.displayForm("Please enter your login details", [('Customer ID', 'nstring'), ('Password', 'nstring')]) try: if inputs[0] == 'owner': self.store.owner.logIn(inputs[1]) self.loginDetail = self.store.owner.getId() else: customer = self.store.getCustomer(inputs[0]) customer.logIn(inputs[1]) self.loginDetail = customer.getId() UserInterface.writeLine("Successfully logged in!") except Exception: UserInterface.writeLine( "Invalid Customer ID and password combination")
def modifyShoppingCart(self): while True: choice = UserInterface.displayConfirm("Continue? ", "") if choice.upper().strip() == 'Y': idPrice = UserInterface.displayForm( "Please input the product ", [("id", "nstring"), ("price", "money")]) sc = self.store.getCustomer(self.loginDetail).getShoppingCart() # print(idPrice[0]) acStock = sc.getListByIdPrice(idPrice[0], float(idPrice[1])) print(type(idPrice[0])) if acStock is not None: newQuan = UserInterface.displayForm( "New quantity", [("", "money")])[0] print(type(newQuan), float(newQuan)) if float(newQuan) == 0.0: sc.deleteFromShoppingCart(idPrice[0], float(idPrice[1])) UserInterface.writeLine( "Item deleted from shopping Cart. :\'(") else: acStock[2] = float(newQuan) break else: UserInterface.writeLine( "Try again. Id and price does not match.") else: break
def displayOrderHistory(self, uid): decision = '' if uid == 'owner': itemised = [(c.getId(), "Name: {}".format(c.getName())) for c in self.store.getCustomers()] decision = UserInterface.displayList( "Customers", itemised, "Please enter the number of the customer whose orders you would like to see, or leave blank to see all" ) decision = decision.lower().strip() if decision == '': orders = self.store.getOrderHistoryAsList() else: if decision in [i[0] for i in itemised]: orders = self.store.getCustomerOrders(decision) else: UserInterface.writeLine("Invalid customer ID") return else: decision = uid orders = self.store.getCustomerOrders(uid) if len(orders) > 0: displayOrders = [ ("Order ID: {}.{} -- {}".format(o.getCustomerId(), o.getOrderId(), str(o.transactionDate)), str(o.getShoppingCart()) + "Total price: {}".format(str(o.getTotalPrice()))) for o in orders ] UserInterface.displayList("Orders", displayOrders, "", False) else: UserInterface.writeLine( "No orders to display for customer {}".format(decision))
def __init__(self): """ctor""" self.frame = None self.timer = None self.player = Player( 1, (CANVAS_WIDTH // 2 - STARTING_OFFSET, FLOOR_HEIGHT + 10), FLOOR_HEIGHT) self.enemy = Player( 2, (CANVAS_WIDTH // 2 + STARTING_OFFSET, FLOOR_HEIGHT + 10), FLOOR_HEIGHT) self.environment = Environment( "assets/background" + str(random.choice(range(3)) + 1) + ".png", (1600, CANVAS_HEIGHT), 1.0) self.states = States(self) self.interface = UserInterface(self, self.states) self.keys = GENERAL_CONTROLS self.damage_done = [False, False] self.time_remaining = 30
def start(self, runMode=constants.RUN_MODE_DAEMON): self._runMode = runMode if (self._runMode==constants.RUN_MODE_DAEMON): pass else: self._userInterface = UserInterface(self) self._userInterface.start()
class ClientManager: #Attributes JOB_SERVER_ADDRESS_LIST = ["127.0.0.1:4730",] #Main methods def __init__(self): self._userInterface = None self._runMode = constants.RUN_MODE_DAEMON self._parsingRequestQueue = ParsingRequestQueue() def start(self, runMode=constants.RUN_MODE_DAEMON): self._runMode = runMode if (self._runMode==constants.RUN_MODE_DAEMON): pass else: self._userInterface = UserInterface(self) self._userInterface.start() def stop(self): print("clientManager stopping...") exit(0) #Sub - methods def submitParsingRequest(self, parsingRequest): gearmanClient = Client(ClientManager.JOB_SERVER_ADDRESS_LIST, parsingRequest) gearmanClient.run() gearmanClient = None def readStatus(self, requestSequenceNumber="all"): return self._parsingRequestQueue.getStatus(requestSequenceNumber)
def register(self): inputs = UserInterface.displayForm( "Please enter your user details to register.\nYour userID will be generated automatically.", [('Type your password', 'nstring'), ('Type your password again', 'nstring'), ('Enter your name', 'nstring'), ('Enter your phone number', 'nstring'), ('Enter your address', 'nstring')]) while inputs[0] != inputs[1]: inputs[0:2] = UserInterface.displayForm( "Passwords don't match! Please try again", [('Type your password', 'nstring'), ('Type your password again', 'nstring')]) newCustomer = self.store.addCustomer(inputs[0], inputs[2], inputs[3], inputs[4]) self.store.writeStore() UserInterface.writeLine( "Successfully registered! Your ID is {}. You will be automatically logged in." .format(newCustomer.getId())) self.loginDetail = newCustomer.getId()
def start_user_interface(self): """ For starting UserInterface thread. :return: """ if not has_GUI: self.user_interface = UserInterface(self.server_address) t_run_ui = threading.Thread(target=self.user_interface.run, args=()) t_run_ui.start()
def main(): main_proc_enable = True data_handler = None input_filename = input("Input file: ") file_handler = fileOps(input_filename) if (file_handler.status): data_handler = dataHandl(file_handler.data) else: main_proc_enable = False user_if = UI(LINE_STARTER) while (main_proc_enable): has_valid_command = user_if.get_command() if (has_valid_command and not user_if.is_quit()): command = user_if.pass_command() main_proc_enable = data_handler.process_command(command) else: main_proc_enable = False
def searchProduct(self): keyword = UserInterface.displayForm( "Search Product: Please input the product you would like to search: ", [('name', 'string')]) # here keyword is a list, so the "real" keyword is keyword[0] matchingList = self.store.searchProductByName(keyword[0]) toBeDisplayed = [] displayNumber = 0 for matchingProduct in matchingList: tuple0 = displayNumber theRest = matchingProduct.getName( ) + " " + matchingProduct.getUnit( ) + " " + matchingProduct.getSource() newTuple = (tuple0, theRest) toBeDisplayed.append(newTuple) displayNumber += 1 choice = UserInterface.displayList( "The matching products are: ", toBeDisplayed, "Which product to choose? X to go back.") validInput = False while not validInput: if choice == "x" or choice == "X": validInput = True return None # The end of this method else: matchIndex = 0 stop = False while not stop and matchIndex < len(matchingList): if choice == str(matchIndex): stop = True else: matchIndex += 1 if stop is False: choice = input("Please enter a valid input.") else: validInput = True return matchingList[matchIndex].getId()
def displayMenuReturnOption(self): while True: menuItems = OrderedDict() #stays in input order menuItems['B'] = ('Browse Products', 'Enter B to browse the list of products') menuItems['S'] = ('Search Products', 'Enter S to search products by keyword') if not self.loginDetail: #nobody logged in menuItems['R'] = ('Register', 'Enter R to register an account') menuItems['L'] = ('Login', 'Enter L to login to your account') else: menuItems['O'] = ('View Order History', 'Enter O to view order history') menuItems['T'] = ('Logout', 'Enter T to logout') if self.loginDetail == 'owner': menuItems['EX'] = ('View Expiring Products', 'Enter EX to view expiring products') menuItems['A'] = ('Add Product', 'Enter A to add a product') menuItems['RC'] = ('Remove Customer', 'Enter RC to remove a customer') menuItems['RP'] = ('Remove Product', 'Enter RP to remove a product') else: menuItems['M'] = ('Manage Account', 'Enter M to manage your account') menuItems['UR'] = ('Unregister Account', 'Enter UR to unregister your account') menuItems['SC'] = ('View Shopping Cart', 'Enter SC to view shopping cart') menuItems['X'] = ("Exit", 'Enter X to exit') request = UserInterface.displayList( "Monash Fruit and Vegetable Store", list(menuItems.values()), "Please enter one of the above options to continue").upper( ).strip() if request not in menuItems.keys(): UserInterface.writeLine("Invalid input, please try again") else: return request
def editBatchPrice(self, productId, batchId): currentPrice = self.store.getProduct(productId).getBatch( batchId).getActualPrice() UserInterface.writeLine("The current quantity is " + str(currentPrice)) results = UserInterface.displayForm("Please enter the new price", [('Price', 'money')]) #input newPrice = float(results[0]) confirmMsg = UserInterface.displayConfirm( "Your new price is " + results[0], "Are you sure?") if confirmMsg == 'y' or confirmMsg == 'Y': self.store.getProduct(productId).getBatch(batchId).setActualPrice( newPrice) UserInterface.writeLine("The new price is: " + str(newPrice)) else: UserInterface.writeLine("The action is abandoned.")
def __init__(self): super().__init__() self.infoObject = pygame.display.Info() self.CAM_HEIGHT = self.infoObject.current_h - 80 self.CAM_WIDTH = int(self.infoObject.current_w-100) self.num_of_creatures = 180 self.num_of_food = 100 self.game_bounds = (-5000, 5000) self.running = True # self.camera = Camera(self.CAM_WIDTH, self.CAM_HEIGHT, x=-(self.CAM_WIDTH / 2), y=-(self.CAM_HEIGHT / 2)) self.camera = Camera(self.CAM_WIDTH, self.CAM_HEIGHT, x=0, y=0, zoom=1.0) self.screen = pygame.display.set_mode((self.CAM_WIDTH, self.CAM_HEIGHT)) self.fullscreen = False # QuadTree for collision detection self.quadtree = QuadTree( bounds=( -self.WORLD_WIDTH/2, -self.WORLD_HEIGHT/2, self.WORLD_WIDTH, self.WORLD_HEIGHT), depth=9) self.ui = UserInterface(self.screen) self.dt = 0 # Will draw the quadtree overlay if true self.draw_quadtree = False self.paused = False # When the user clicks on the screen it's position will be stored here self.mouse_screen_position = None self.mouse_real_position = None # How fast everything moves self.game_speed = 1.0 self.selected_creature = None self.follow_creature = False self.breeder = Breeder() self.population_stats = StatsTracker() self.spinner = Background()
def editBatchQuantity(self, productId, batchId): currentQuantity = self.store.getProduct(productId).getBatch( batchId).getQuantity() UserInterface.writeLine("The current quantity is " + str(currentQuantity)) results = UserInterface.displayForm("Please enter the new quantity", [('Quantity', 'number')]) #input newQuantity = float(results[0]) confirmMsg = UserInterface.displayConfirm( "Your new quantity is " + results[0], "Are you sure?") if confirmMsg == 'y' or confirmMsg == 'Y': self.store.getProduct(productId).getBatch(batchId).setQuantity( newQuantity) UserInterface.writeLine("The new quantity is: " + str(newQuantity)) else: UserInterface.writeLine("The action is abandoned.")
def viewExpiringProducts(self): products = self.store.getProducts() paired = [] expIds = [] for p in products: for b in p.getExpiringBatches(): paired.append(("Name: {}, Product ID: {}, Batch ID: {}".format( p.getName(), p.getId(), b.getBatchID()), "Expiring: {}".format(b.getExpiryDate()))) if p.getId() not in expIds: expIds.append(p.getId()) if len(paired) > 0: UserInterface.displayList("Expiring product batches", paired, "", False) toDiscount = UserInterface.displayConfirm( "Do you wish to discount these products and delete expired batches? ", "") if toDiscount in ['y', 'Y']: for pid in expIds: self.store.getProduct(pid).updateDiscount() self.store.getProduct(pid).deleteExpiredProducts() else: UserInterface.writeLine( "Good news! There are no expiring products")
def _reload_init(self): self.quadtree = QuadTree( bounds=( -self.WORLD_WIDTH/2, -self.WORLD_HEIGHT/2, self.WORLD_WIDTH, self.WORLD_HEIGHT), depth=9) self.ui = UserInterface(self.screen) self.dt = 0 # When the user clicks on the screen it's position will be stored here self.mouse_screen_position = None self.mouse_real_position = None # How fast everything moves self.game_speed = 1.0 self.selected_creature = None self.follow_creature = False self.population_stats = StatsTracker()
class CreatureSim(PyGameBase): """Runs the creature sim game""" CAMERA_MOVE_SPEED = .5 GAME_SPEED_INCREMENT = .1 MAX_GAME_SPEED = 2.0 MIN_GAME_SPEED = .1 WORLD_WIDTH = 100000 WORLD_HEIGHT = 100000 SELECTED_COLOR = GREEN def __init__(self): super().__init__() self.infoObject = pygame.display.Info() self.CAM_HEIGHT = self.infoObject.current_h - 80 self.CAM_WIDTH = int(self.infoObject.current_w-100) self.num_of_creatures = 180 self.num_of_food = 100 self.game_bounds = (-5000, 5000) self.running = True # self.camera = Camera(self.CAM_WIDTH, self.CAM_HEIGHT, x=-(self.CAM_WIDTH / 2), y=-(self.CAM_HEIGHT / 2)) self.camera = Camera(self.CAM_WIDTH, self.CAM_HEIGHT, x=0, y=0, zoom=1.0) self.screen = pygame.display.set_mode((self.CAM_WIDTH, self.CAM_HEIGHT)) self.fullscreen = False # QuadTree for collision detection self.quadtree = QuadTree( bounds=( -self.WORLD_WIDTH/2, -self.WORLD_HEIGHT/2, self.WORLD_WIDTH, self.WORLD_HEIGHT), depth=9) self.ui = UserInterface(self.screen) self.dt = 0 # Will draw the quadtree overlay if true self.draw_quadtree = False self.paused = False # When the user clicks on the screen it's position will be stored here self.mouse_screen_position = None self.mouse_real_position = None # How fast everything moves self.game_speed = 1.0 self.selected_creature = None self.follow_creature = False self.breeder = Breeder() self.population_stats = StatsTracker() self.spinner = Background() def run(self): self.load() self.setup_keys() self.game_loop() def game_loop(self): while self.running: self.dt = self.clock.tick() self.screen.fill(BLACK) self.handle_events() self.handle_key_presses() self.update_creature_positions() self.scene_graph.update() self.center_camera() self.quadtree.update_objects(self.entities) self.handle_collisions() self.do_obj_events() self.render_frame() def render_frame(self): pygame.display.set_caption(str(self.clock.get_fps())) # Find all objects in nodes intersecting the screen objects_to_draw = self.quadtree.get_objects_at_bounds(self.camera.get_bounds()) for scene_object in objects_to_draw: scene_object.draw(self.screen, self.camera) if self.draw_quadtree: self.quadtree.draw_tree(self.screen, self.camera) self.draw_ui() pygame.display.flip() def center_camera(self): if self.selected_creature and self.follow_creature: self.camera.position[0] = self.selected_creature.position[0] self.camera.position[1] = self.selected_creature.position[1] def do_obj_events(self): if not self.paused: self.check_healths() def remove_creature(self, creature): if creature.selected: self.unfollow_creature() self.quadtree.remove(creature) self.entities.remove(creature) self.entities.remove(creature.vision_cone) self.scene_graph.remove(creature) def check_healths(self): for creature in self.get_creatures(): if creature.health <= 0: self.remove_creature(creature) self._breed_creature() for food in self.get_foods(): if food.eaten == True: self.quadtree.remove(food) self.entities.remove(food) self._insert_new_food() def _insert_new_creature(self): new_creature = Creature( x=randrange(*self.game_bounds), y=randrange(*self.game_bounds), color=WHITE ) new_creature.vision_cone = VisionCone(parent=new_creature, x=265, color=RED) self.entities.append(new_creature.vision_cone) self._insert_creature(new_creature) return new_creature def _insert_creature(self, creature): self.entities.append(creature) creature.calc_absolute_position() self.scene_graph.add(creature) self.scene_graph.add_to_parent(creature.vision_cone, creature, transformer=OldStyleTransformer) self.quadtree.insert(creature) def _insert_new_food(self): new_food = Food( x=randrange(*self.game_bounds), y=randrange(*self.game_bounds), color=DARKGREEN ) self._insert_food(new_food) return new_food def _insert_food(self, food): self.entities.append(food) food.calc_absolute_position() self.quadtree.insert(food) def _breed_creature(self): new_weights = self.breeder.breed(list(self.get_creatures())) new_creature = Creature( x=randrange(*self.game_bounds), y=randrange(*self.game_bounds), nn_weights=new_weights ) new_creature.vision_cone = VisionCone(parent=new_creature, x=265, color=RED) self.entities.append(new_creature.vision_cone) self._insert_creature(new_creature) return new_creature def handle_collisions(self): # Handle collisions for each creature's vision cone for creature in self.get_creatures(): # Get rough idea of what things could be colliding first_pass = self.quadtree.get_objects_at_bounds(creature.get_bounds()) if first_pass: for entity in first_pass: creature.vision_cone.check_collision(entity) creature.check_collision(entity) for entity in self.entities: entity.finish_collisions() def handle_key_presses(self): # Camera Zoom if self.key_presses["zoom-in"]: self.camera.zoom_in(self.dt) if self.key_presses["zoom-out"]: self.camera.zoom_out(self.dt) # Camera movement if not self.follow_creature: if self.key_presses["cam-up"]: self.camera.move(y_change=-self.dt * self.CAMERA_MOVE_SPEED) if self.key_presses["cam-down"]: self.camera.move(y_change=self.dt * self.CAMERA_MOVE_SPEED) if self.key_presses["cam-left"]: self.camera.move(x_change=-self.dt * self.CAMERA_MOVE_SPEED) if self.key_presses["cam-right"]: self.camera.move(x_change=self.dt * self.CAMERA_MOVE_SPEED) def handle_events(self): for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() self.register_key_presses(event) def register_key_presses(self, event): # Key Down ######################## if event.type == KEYDOWN: if event.key == K_ESCAPE: raise SystemExit() try: self.key_presses[self.key_map[event.key]] = True except KeyError: pass if event.key == K_t: self.draw_quadtree = not self.draw_quadtree if event.key == K_b: self.select_best() if event.key == K_F5: self.save_state() if event.key == K_F9: self.load_state() if event.key == K_p: self.paused = not self.paused if event.key == K_F11: self.toggle_fullscreen() if event.key == K_f: self.toggle_follow_creature() if event.key == K_RIGHTBRACKET: self.speedup_game() if event.key == K_LEFTBRACKET: self.slowdown_game() # Key Up ######################## if event.type == KEYUP: try: self.key_presses[self.key_map[event.key]] = False except KeyError: pass # Mouse Down ######################## if event.type == pygame.MOUSEBUTTONDOWN: self.handle_click() def toggle_fullscreen(self): self.fullscreen = not self.fullscreen if self.fullscreen: pygame.display.set_mode((self.CAM_WIDTH, self.CAM_HEIGHT), pygame.FULLSCREEN) else: pygame.display.set_mode((self.CAM_WIDTH, self.CAM_HEIGHT)) def save_state(self): def export_items(items): with open('weight_data.pickle', 'wb+') as f: pickle.dump(items, f) # dump the creatures and food stuffs # let's get all the creatures first x = list(self.get_creatures()) y = list(self.get_foods()) export_items([x, y]) self.ui.toast("Saved Simulation") def load_state(self): def retrieve_items(): with open('weight_data.pickle', 'rb+') as f: return pickle.load(f) try: creatures, foods = retrieve_items() except: return self.reload(creatures, foods) self.ui.toast("Loaded Simulation") def toggle_follow_creature(self): if self.selected_creature: self.follow_creature = not self.follow_creature def unfollow_creature(self): self.follow_creature = False def select_best(self): self.unselect_creature() self.unfollow_creature() best = self._find_best() self.select_creature(best) self.toggle_follow_creature() def _find_best(self): return max(self.get_creatures(), key=lambda c: c.total_food_eaten) def select_creature(self, creature): self.selected_creature = creature creature.selected = True def unselect_creature(self): if self.selected_creature: self.selected_creature.selected = False self.selected_creature = None self.unfollow_creature() def handle_click(self): self.mouse_screen_position = pygame.mouse.get_pos() self.mouse_real_position = self.camera.real_position(self.mouse_screen_position) hit = self.quadtree.ray_cast(self.mouse_real_position) if hit: # If our hit is a Creature if issubclass(type(hit), Creature): self.unselect_creature() self.select_creature(hit) def _reload_init(self): self.quadtree = QuadTree( bounds=( -self.WORLD_WIDTH/2, -self.WORLD_HEIGHT/2, self.WORLD_WIDTH, self.WORLD_HEIGHT), depth=9) self.ui = UserInterface(self.screen) self.dt = 0 # When the user clicks on the screen it's position will be stored here self.mouse_screen_position = None self.mouse_real_position = None # How fast everything moves self.game_speed = 1.0 self.selected_creature = None self.follow_creature = False self.population_stats = StatsTracker() def reload(self, creatures, foods): self._reload_init() self.load(creatures, foods) def load(self, creatures=None, foods=None): """Sets up various game world objects""" self.entities = [] self.scene_graph = SceneGraph() self.scene_graph.add(self.spinner) if creatures and foods: for creature in creatures: self._insert_creature(creature) for food in foods: self._insert_food(food) else: # Create creatures for x in range(self.num_of_creatures): self._insert_new_creature() # Create foods for x in range(self.num_of_food): self._insert_new_food() # Setup text boxes self.speed_textbox = TextBox("", (10, self.CAM_HEIGHT - 40)) self.creature_stats_textbox = MultilineTextBox([""], (10, 10)) self.population_stats_textbox = MultilineTextBox([""], (self.CAM_WIDTH-300, 10)) num_creatures_text = "{} Creatures, {} Food".format(self.num_of_creatures, self.num_of_food) self.num_creatures_textbox = TextBox(num_creatures_text, (10, self.CAM_HEIGHT - 70)) self.ui.add(self.speed_textbox) self.ui.add(self.creature_stats_textbox) self.ui.add(self.num_creatures_textbox) self.ui.add(self.population_stats_textbox) def update_creature_positions(self): if not self.paused: for creature in self.get_creatures(): network = creature.nn network.compute_network() creature.rotate((self.dt * creature.rotation_speed) * self.game_speed) creature.move_forward((self.dt * creature.speed) * self.game_speed) creature.do_everyframe_action(self.dt, self.game_speed) creature.update_position() def speedup_game(self): self.game_speed = min(self.MAX_GAME_SPEED, self.game_speed + self.GAME_SPEED_INCREMENT) def slowdown_game(self): self.game_speed = max(self.MIN_GAME_SPEED, self.game_speed - self.GAME_SPEED_INCREMENT) def setup_keys(self): """Sets up key presses""" key_map = { K_w: "cam-up", K_s: "cam-down", K_a: "cam-left", K_d: "cam-right", K_e: "zoom-out", K_q: "zoom-in", } self.register_keys(key_map) def draw_ui(self): ui = self.ui if self.paused: speed_text = "Speed: Paused" else: speed_text = "Speed: {:.2}x".format(self.game_speed) self.speed_textbox.set(speed_text) if self.selected_creature: self.creature_stats_textbox.set(self.selected_creature.get_stats()) else: self.creature_stats_textbox.clear() stats = self.population_stats.update(list(self.get_creatures())) self.population_stats_textbox.set(stats) ui.draw() def get_creatures(self): return (entity for entity in self.entities if issubclass(type(entity), Creature)) def get_foods(self): return (entity for entity in self.entities if issubclass(type(entity), Food))
def init(host='localhost'): """ Game initialization function. 1. Creates a L{Debugger} (debugger) and L{EventTimer} (eventTimer) and stores references to them in an instance of L{EventManager}. 2. Several listeners are started and registered with eventManager: - Instance of L{Universe} (universe) - Instance of L{UserInterface} (ui) - Instance of L{Window} (gameWindow) 3. We send the eventManager a message to start the game - This message is interpreted by the gameWindow """ debugger = Debugger() eventTimer = EventTimer() #Create the event manager for low-level events eventManager = Manager(eventTimer,debugger) #FIXME: more specific manager\ #classes will be needed later? Entity.manager = eventManager #Create the occurence manager for high-level events (same across client and server) #FIXME: NOT YET IMPLEMENTED #THIS WILL BE CHANGED LATER TO ACCOUNT FOR LOADING, ETC. networked = True # World w is set to the activeWorld of the universe universe = Universe(eventManager) ui = UserInterface(eventManager,universe.activeWorld,None) gameWindow = Window(eventManager,width=1024,height=768) gameWindow.fullscreenMode = False gameWindow.updateScreenMode() w = World(universe) #universe.changeWorld(w) try: client = GameClient(eventManager,host=host,port=1567) while client.ID == None: import time time.sleep(.02) print 'Got an ID',client.ID clientID = client.ID # client.sendRequest('GetWorld') except: networked = False if not networked: # Initialize 25 entities in World w # Initialize a TestTownCenter clientID = GameClient.ID = 0 ui.setClientID(clientID) eventManager.post(Event.NewPlayerEvent(clientID)) w._generateResources() else: clientID = client.ID ui.setClientID(clientID) wManipulator = WorldManipulator(eventManager,w,networked,gameClientID = clientID) #Notify the manager that the window should start to accept input: eventManager.post(Event.StartEvent()) return eventManager.eventTypesToListeners