def __init__(self,**kwargs): super().__init__(**kwargs) self.fig, self.ax1 = plt.subplots() self.ax1.plot([],[],'bo') self.mpl_canvas = self.fig.canvas self.add_widget(self.mpl_canvas) Clock.schedule_interval(self.update,1)
def _update(self): """Updates the main window, causing a single new frame to be drawn.""" # Handle events self._handleEvents() # If we're minimized or hidden, don't bother doing anything if not pygame.display.get_active(): time.sleep(1.0 / 60.0) return # Call the FPS clock if self._limitFPS: Clock.get().tick(60) else: Clock.get().tick() timeElapsed = Clock.get().getTimeElapsed() self._input.update(timeElapsed) if self._delegate != None: self._delegate.update(timeElapsed) # Draw FPS on top, if enabled self._fpsDisplayer.draw() # Swap buffers pygame.display.flip()
class Timer: def __init__(self, aKernel): self.quantum = aKernel.shortScheduler.quamtum() self.currentQuantum = self.quantum self.clock = Clock(self) self.kernel = aKernel def initializeThread(self): self.clock.start() def decreasedQuamtum(self): self.currentQuantum = self.currentQuantum - 1 return self.currentQuantum def reset(self): self.currentQuantum = self.quantum def timeOut(self): return (self.currentQuantum == 0) def timeOutInterrupt(self): self.kernel.manageIRQ.timeOutInterrupt() def run(self): if not self.kernel.isModeKernel(): if self.timeOut(): self.timeOutInterrupt() else: self.decreasedQuamtum() self.kernel.cpu.fetchInstruction()
def addAccessRight(self, weekday, startTime=[0, 0], endTime=[0, 0], openRooms=["Complete"]): """ Fuege eine neue Zugangsberechtigung hinzu. Wenn diese sich ganz oder teilweise mit einer bestehenden Zugangsberechtigung ueberschneidet, wird die alte Berechtigung im Zeitraum der neuen Berechtigung ueberschrieben. @param weekday: Wochentag fuer die Zugangsberechtigung (String) @param startTime: Beginn des Berechtigungszeitraums in Stunde und Minute [int, int] @param endTime: Ende des Berechtigungszeitraums in Stunde und Minute [int, int] @param openRooms: Liste der Raeume, fuer die diese Berechtigung gelten soll @return: Wahrheitswert, der angibt ob die neue Berechtigung erfolgreich erstellt wurde """ if weekday not in Clock.days or \ startTime[0] not in range(24) or startTime[1] not in range(60) or \ endTime[0] not in range(24) or endTime[1] not in range(60): print "Invalid input. Please try again." return False startTimeStamp = Clock.timeStamp(weekday, startTime[0], startTime[1]) endTimeStamp = Clock.timeStamp(weekday, endTime[0], endTime[1]) if startTimeStamp >= endTimeStamp: print "Start time after end time. Please try again." return False openDoorList = [] for door in openRooms: accessList = roomAccess[door] for item in accessList: if doors[item] not in openDoorList: openDoorList.append(doors[item]) # Check if another accessRight already exists in the given timeframe # if so, overwrite it for i in reversed(range(len(self.accessRights) - 1)): access = self.accessRights[i] if startTimeStamp <= access[0] and endTimeStamp >= access[1]: # new access right STARTS BEFORE start of old one and ENDS AFTER end of old one self.accessRights.pop(i) elif startTimeStamp <= access[0] and endTimeStamp > access[0]: # new access right STARTS BEFORE start of old one and ENDS BEFORE end of old one self.accessRights[i][0] = endTimeStamp elif startTimeStamp < access[1] and endTimeStamp >= access[1]: # new access right STARTS AFTER start of old one and ENDS AFTER end of old one self.accessRights[i][1] = startTimeStamp elif startTime > access[0] and endTimeStamp < access[1]: # new access right STARTS AFTER start of old one and ENDS BEFORE end of old one self.accessRights.append([endTimeStamp, access[1], access[2]]) self.accessRights[i][1] = startTimeStamp self.accessRights.append([startTimeStamp, endTimeStamp, openDoorList]) return True
def change_mode(pin): if pin.value() == 0: if Dial.mode == 'game': Dial.mode = 'clock' Game.stop() Clock.show_clock() else: if Dial.mode == 'clock': Dial.mode = 'game' Game.start()
def process_body(data): time = data['time'] if not time: return return Clock.Alarm( hour=int(time.split(':')[0]), minute=int(time.split(':')[1]), day_of_week=data['daysOfWeek'], enabled=data['enabled'], duration_minutes=int(data['durationMinutes']), type=Clock.AlarmType(data['type']) )
def getUWImageAt(self, time): Clock.update(time) scene = self.uwSceneGenerator.getScene() imSize = scene.shape distX, distY = self.uwDistSimulator.getDistortions() mappingR = np.clip(-(-self.R + distY), 0, imSize[0] - 1) mappingC = np.clip(self.C + distX, 0, imSize[1] - 1) uwScene = self.getBiLinearInterPImage(scene, mappingR, mappingC) return uwScene
def __init__(self): self.coord_x = -10 # x coordinate self.coord_y = -10 # y coordinate self.age = 0 # возраст куска травы self.state = Fruit.st_growing self.color = Light_green # цвет куска травы, зависит от возраста self.health = 100 # прочность травы, в общем то, требуемое время на её поедание self.saturability = 100 # насыщаемость, как сильно животное наедается куском травы self.size = 0 # коэф размера куска травы self.id = canv.create_rectangle(self.coord_x - 2 * self.size, self.coord_y + 2 * self.size, self.coord_x + 2 * self.size, self.coord_y + 2 * self.size, fill=self.color, outline="#5c1841") self.clock = Clock()
def displayNumbers(self): screen = Tk() screen.geometry("900x125+510+50") screen.title( "These are your numbers! You need to try and get as close as possible to the number on the very right!" ) screen.resizable(False, False) pos = 0 for i in self.unchangedNumberList: Label(screen, text=i, bg="black", foreground="white", font=("Comic Sans", 12, "bold")).place(x=pos * 100, y=0, width=100, height=125) pos += 1 Label(screen, text=self.total, bg="white", foreground="red", font=("Comic Sans", 16, "bold")).place(x=600, y=0, width=300, height=125) clock = Clock.Clock() #display the clock self.numbers_screen.destroy() self.numbers_screen.after( 30000, lambda: [self.timesUp(clock), screen.destroy()])
def setUpCamera(self): m = self.m glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT) glLoadIdentity() glTranslate(0.0, 0.0, -self.camera.height()) glRotatef(self.camera.pitch(), 1.0, 0.0, 0.0) glRotatef(self.camera.mapRotation(), 0.0, 0.0, 1.0) glTranslate(self.camera.offset().x, self.camera.offset().y, -self.camera.offset().z) lightIndex = GL_LIGHT0 for l in self.lightEnv.lights(): if lightIndex > GL_LIGHT7: break glLightfv(lightIndex, GL_POSITION, l.position()) lightIndex += 1 # glLightf(GL_LIGHT0, GL_SPOT_CUTOFF, 90.0) # glLightf(GL_LIGHT0, GL_SPOT_EXPONENT, 0.0) # glLightfv(GL_LIGHT0, GL_SPOT_DIRECTION, [0.0, 0.4, -1.0, 1.0]) # glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, [1.0, 0.0, 0.0, 1.0]) # glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 64.0) # modify the highlights by an alpha value dependent on time # set to the range (0.0, 1.0) self._highlightAlpha = (math.sin(Clock.get().getTime() * 2.0) + 1.0) / 2.0 # now scale to the range (0.5, 0.8) self._highlightAlpha = self._highlightAlpha * 0.3 + 0.5
def SetupClockWindowControls(Window): # time button Button = Window.GetControl(0) Clock.CreateClockButton(Button) # 41627 - Return to the Game World Button = Window.GetControl(2) Button.SetEvent(IE_GUI_BUTTON_ON_PRESS, GUICommonWindows.CloseTopWindow) Button.SetTooltip(41627) # Select all characters Button = Window.GetControl(1) Button.SetTooltip(41659) Button.SetEvent(IE_GUI_BUTTON_ON_PRESS, GUICommon.SelectAllOnPress) # Abort current action Button = Window.GetControl(3) Button.SetTooltip(41655) Button.SetEvent(IE_GUI_BUTTON_ON_PRESS, GUICommonWindows.ActionStopPressed) # Formations import GUIWORLD Button = Window.GetControl(4) Button.SetTooltip(44945) Button.SetEvent(IE_GUI_BUTTON_ON_PRESS, GUIWORLD.OpenFormationWindow) return
def __init__(self): Animal.__init__(self) self.color = 'red' self.notice_radius = 300 # radius where predator notices objects self.state = Predator.st_idle # basic state is wandering around self.kills = 0 self.nearest_cattle = None self.nearest_predator = None self.health = 40000 self.velocity = 50 # predator basic speed self.id = canv.create_oval(self.coord_x - self.radius, self.coord_y - self.radius, self.coord_x + self.radius, self.coord_y + self.radius, fill=self.color) self.clock = Clock()
def stop_alarm(): try: if Clock.stop_alarm(): return json.dumps({'status': 'OK'}) return json.dumps({'status': 'ALARM_NOT_SOUNDING'}), 400 finally: broadcast_state()
def setUpCamera(self): m = self.m glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glLoadIdentity() glTranslate(0.0, 0.0, -self.camera.height()) glRotatef(self.camera.pitch(), 1.0, 0.0, 0.0) glRotatef(self.camera.mapRotation(), 0.0, 0.0, 1.0) glTranslate(self.camera.offset().x, self.camera.offset().y, -self.camera.offset().z) lightIndex = GL_LIGHT0 for l in self.lightEnv.lights(): if lightIndex > GL_LIGHT7: break glLightfv(lightIndex, GL_POSITION, l.position()) lightIndex += 1 # glLightf(GL_LIGHT0, GL_SPOT_CUTOFF, 90.0) # glLightf(GL_LIGHT0, GL_SPOT_EXPONENT, 0.0) # glLightfv(GL_LIGHT0, GL_SPOT_DIRECTION, [0.0, 0.4, -1.0, 1.0]) # glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, [1.0, 0.0, 0.0, 1.0]) # glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 64.0) # modify the highlights by an alpha value dependent on time # set to the range (0.0, 1.0) self._highlightAlpha = (math.sin(Clock.get().getTime() * 2.0) + 1.0) / 2.0 # now scale to the range (0.5, 0.8) self._highlightAlpha = self._highlightAlpha * 0.3 + 0.5
def set_alarm(): def process_body(data): time = data['time'] if not time: return return Clock.Alarm( hour=int(time.split(':')[0]), minute=int(time.split(':')[1]), day_of_week=data['daysOfWeek'], enabled=data['enabled'], duration_minutes=int(data['durationMinutes']), type=Clock.AlarmType(data['type']) ) alarm = process_body(request.json) Clock.set_alarm(alarm) broadcast_state() return json.dumps({'status': 'OK'})
def getBounds(self): time = Clock.read() centreR, centreC = self.path.getLocation(time) rT = centreR - self.length/2 rB = centreR + self.length/2 cL = centreC - self.length/2 cR = centreC + self.length/2 return int(rT), int(cL), int(rB), int(cR)
def __init__(self): Animal.__init__(self) self.anxiety = 0 # represents how anxious the animal is self.state = Cattle.st_idle self.nearest_predator = None # if cattle could identify predator near it self.nearest_fruit = None # if cattle could identify predator near it self.nearest_cattle = None self.velocity = 35 # cattle basic speed self.color = 'green' self.birfability = 0 self.eaten = 0 self.count = 0 self.under_attack = False self.notice_radius = 80 # radius where cattle notices objects self.id = canv.create_oval(self.coord_x - self.radius, self.coord_y - self.radius, self.coord_x + self.radius, self.coord_y + self.radius, fill=self.color) self.clock = Clock()
def broadcast_state(): alarm = Clock.get_alarm() state = { 'time': Clock.get_datetime(), 'alarm': { 'time': f'{str(alarm.hour).zfill(2)}:{str(alarm.minute).zfill(2)}', 'daysOfWeek': alarm.day_of_week, 'enabled': alarm.enabled, 'durationMinutes': alarm.duration_minutes, 'isSounding': Clock.alarm_is_on(), 'type': alarm.type.value }, 'radio': { 'on': Radio.is_playing(), 'stations': [{'name': s.name, 'url': s.url} for s in Radio.get_stations()], 'currentStation': Radio.state.current_station.url, 'volume': Radio.get_volume() } } socketio.emit('state_update', json.dumps(state))
def menue_prev(): global mode if mode == 0: print("Stoppe Uhr") mode = 4 update_lcd(1) return if mode == 1: mylcd.lcd_clear() print("Starte Uhr") amplifier_off() #Relais schaltet verstärker aus Clock.write_big_time() mode = 0 return if mode in [2, 3, 4]: mode = mode - 1 update_lcd(0) return
def main(): kbd = Kbd2.Kbd2() clk = Clock.clock(kbd) clk.menu.load("menu.csv") kbd.sethanddle('k3', clk.nextbk) kbd.sethanddle('k2', clk.sinfo) kbd.sethanddle('k1', clk.sysexit) kbd.sethanddle('left', clk.menu.start) #kbd.sethanddle( 'right', clk.menu.stop ) kbd.sethanddle('enter', clk.menu.run) kbd.sethanddle('up', clk.menu.previous) kbd.sethanddle('down', clk.menu.next) clk.run()
def displaySelected(self): screen = Tk() screen.geometry("900x125+510+50") for i in range(0, 9): Label(screen, text=self.letterList[i], bg="black", foreground="white", font=("Comic Sans", 12, "bold")).place(x=i * 100, y=0, width=100, height=125) clock = Clock.Clock() #display the clock self.letters_screen.destroy() self.letters_screen.after( 30000, lambda: [self.timesUp(clock), screen.destroy()])
def main(): """Main function to get information for Bar 4. """ getter_battery = Battery.Battery() getter_clock = Clock.Clock() getter_keyboard = Keyboard.Keyboard() getter_os = Os.Os() getter_battery.show_info() sys.stdout.write(" | ") getter_clock.get_uptime() sys.stdout.write(" | ") getter_clock.get_time() sys.stdout.write(" ") getter_clock.get_date() sys.stdout.write(" | ") getter_keyboard.get_layout() getter_keyboard.show_locks() sys.stdout.write(" | ") getter_os.get_os()
def _adjustTranslation(self, timeElapsed): if self._scrollTarget == None: return (x, y, z) = self._scrollTarget if Clock.get().getFPS() <= 10: self.setOffset(x, y, z) self._scrollTarget = None return (offsetX, offsetY, offsetZ) = self._offset.asTuple() dx = x - offsetX dy = y - offsetY dz = 0 if z != None: dz = z - offsetZ speed = 5.0 offsetX += dx * timeElapsed * speed offsetY += dy * timeElapsed * speed offsetZ += dz * timeElapsed * speed cutoff = 0.2 if abs(dx) < cutoff and abs(dy) < cutoff and abs(dz) < cutoff: self._scrollTarget = None else: self.setOffset(offsetX, offsetY, offsetZ)
def getSurfaceAndNormals(self): time = Clock.read() surface = self.getSurface(time) normals = self.getSurfaceNormals(time) return surface, normals
def fps(self): return Clock.get().getFPS()
# Zach Taylor - CINF308 Programming for Informatics import tkinter as tk import Clock clock = Clock.Clock() # Instantiates a clock object screen = tk.Tk() # Instantiates a tkinter object screen.title("Clock") # Window title is 'Clock' screen.geometry("850x550") # Window size is 850x550 screen.configure(bg="steelblue1") # Sets window background color def increaseDay(): # Defines the increaseDay command clock.increaseDay() # Calls the increaseDay function from the Clock class label2.place( relx=.34, rely=.15) # Resets the time label because setClock changes it if error label2.config(text=clock.__str__()) # Displays clock.__str__ in label 2 def decreaseDay(): clock.decreaseDay() # Calls the decreaseDay function from the Clock class label2.place(relx=.34, rely=.15) label2.config(text=clock.__str__()) def increaseSecond(): clock.increaseSecond( ) # Calls the increaseSecond function from the Clock class label2.place(relx=.34, rely=.15) label2.config(text=clock.__str__())
def OpenContainerWindow(): global ContainerWindow, Container if ContainerWindow: return global HideOnClose HideOnClose = IsGameGUIHidden() if HideOnClose: SetGameGUIHidden(False) # must use a timed event because SetGameGUIHidden(False) sets a flag to unhide the gui next frame # AFIK not needed, commented out in case it turns out there are conditions we will need it # GemRB.SetTimedEvent (lambda: GemRB.GetView ("MSGWIN").SetVisible(False), 1) else: GemRB.GetView("MSGWIN").SetVisible(False) ActWin = GemRB.GetView("ACTWIN") if ActWin: ActWin.SetVisible(False) ContainerWindow = Window = GemRB.LoadWindow(8, GUICommon.GetWindowPack(), WINDOW_BOTTOM | WINDOW_HCENTER) # fix wrong height in the guiw10.chu and reposition # that chu is also used as a base for some arbitrary resolutions if GameCheck.IsBG2() and GemRB.GetSystemVariable(SV_HEIGHT) >= 768: Size = Window.GetSize() Pos = Window.GetPos() Window.SetSize(Size[0], 90) Window.SetPos(Pos[0], GemRB.GetSystemVariable(SV_HEIGHT) - 90) if not GameCheck.IsIWD2() and not GameCheck.IsGemRBDemo( ) and not GameCheck.IsPST(): # container window shouldnt be in front GemRB.GetView("OPTWIN").Focus() GemRB.GetView("PORTWIN").Focus() Container = GemRB.GetContainer(0) # Gears (time) when options pane is down if GameCheck.IsBG2(): import Clock Clock.CreateClockButton(Window.GetControl(62)) # 0-5 - Ground Item for i in range(ground_size): Button = Window.GetControl(i) Button.SetVarAssoc("LeftIndex", i) Button.SetEvent(IE_GUI_BUTTON_ON_PRESS, TakeItemContainer) if GameCheck.IsPST(): Button.SetFont("NUMBER") Button.SetFlags( IE_GUI_BUTTON_ALIGN_RIGHT | IE_GUI_BUTTON_ALIGN_BOTTOM, OP_OR) # 10-13 - Personal Item for i in range(4): Button = Window.GetControl(i + 10) Button.SetVarAssoc("RightIndex", i) Button.SetEvent(IE_GUI_BUTTON_ON_PRESS, DropItemContainer) if GameCheck.IsPST(): Button.SetFont("NUMBER") Button.SetFlags( IE_GUI_BUTTON_ALIGN_RIGHT | IE_GUI_BUTTON_ALIGN_BOTTOM, OP_OR) # left scrollbar (container) ScrollBar = Window.GetControl(52) ScrollBar.SetVisible( True) # unhide because in PST it is linked to a TextArea ScrollBar.SetEvent(IE_GUI_SCROLLBAR_ON_CHANGE, RedrawContainerWindow) # right scrollbar (inventory) ScrollBar = Window.GetControl(53) ScrollBar.SetVisible( True) # unhide because in PST it is linked to a TextArea ScrollBar.SetEvent(IE_GUI_SCROLLBAR_ON_CHANGE, RedrawContainerWindow) # encumbrance and inventory icon # iwd has a handy button Button = Window.GetControl(54) if Button: if GameCheck.IsPST(): Button.SetFont("NUMBER") Button.SetFlags(IE_GUI_BUTTON_NO_IMAGE, OP_SET) Button.CreateLabel( 0x10000045, "NUMBER", "", IE_FONT_ALIGN_LEFT | IE_FONT_ALIGN_TOP | IE_FONT_SINGLE_LINE) Button.CreateLabel( 0x10000046, "NUMBER", "", IE_FONT_ALIGN_RIGHT | IE_FONT_ALIGN_BOTTOM | IE_FONT_SINGLE_LINE) else: Window.CreateLabel( 0x10000045, 323, 14, 60, 15, "NUMBER", "0:", IE_FONT_ALIGN_LEFT | IE_FONT_ALIGN_TOP | IE_FONT_SINGLE_LINE) Window.CreateLabel( 0x10000046, 323, 20, 80, 15, "NUMBER", "0:", IE_FONT_ALIGN_RIGHT | IE_FONT_ALIGN_TOP | IE_FONT_SINGLE_LINE) # container icon Button = Window.GetControl(50) if GameCheck.IsPST(): Button.SetFlags(IE_GUI_BUTTON_NO_IMAGE, OP_SET) Button.SetState(IE_GUI_BUTTON_LOCKED) if not GameCheck.IsPST(): Table = GemRB.LoadTable("containr") row = Container['Type'] tmp = Table.GetValue(row, 0) if tmp != '*': GemRB.PlaySound(tmp) tmp = Table.GetValue(row, 1) if tmp != '*': Button.SetSprites(tmp, 0, 0, 0, 0, 0) # Done Button = Window.GetControl(51) if GameCheck.IsPST(): Button.SetText(1403) else: Button.SetText("") Button.MakeEscape() Button.SetEvent(IE_GUI_BUTTON_ON_PRESS, LeaveContainer) GemRB.SetVar("LeftTopIndex", 0) GemRB.SetVar("RightTopIndex", 0) UpdateContainerWindow()
print("Starting market") marketProcess.start() weatherProcess = Weather.Weather(weather, clocker, day) print("Starting weather") weatherProcess.start() houses = [ House.House(i, clocker, weather, lockHouse, houses_pipes[i][1]) for i in range(numberOfHouses) ] print("Starting every Houses") for k in houses: k.start() tickProcess = Clock.Clock(clocker) print("Starting the clock") tickProcess.start() firstTime = True #Used for the first day (the market isn't up) # For the graph dayG = [] priceG = [] communityG = [] while True: if clocker.value == 0: print("--NIGHT--")
def __init__(self, aKernel): self.quantum = aKernel.shortScheduler.quamtum() self.currentQuantum = self.quantum self.clock = Clock(self) self.kernel = aKernel
def sTime(self, time): "Setup level timer" self.startTime = time self.timer = Clock(self.surface, time, 1, 1, self.levelTime)
class Fruit: st_growing = 0 st_ripe = 1 st_rotten = 2 st_dead = 3 Ripe = 500 * 1 Rotten = 1000 * 1 Dead = 1500 * 1 def __init__(self): self.coord_x = -10 # x coordinate self.coord_y = -10 # y coordinate self.age = 0 # возраст куска травы self.state = Fruit.st_growing self.color = Light_green # цвет куска травы, зависит от возраста self.health = 100 # прочность травы, в общем то, требуемое время на её поедание self.saturability = 100 # насыщаемость, как сильно животное наедается куском травы self.size = 0 # коэф размера куска травы self.id = canv.create_rectangle(self.coord_x - 2 * self.size, self.coord_y + 2 * self.size, self.coord_x + 2 * self.size, self.coord_y + 2 * self.size, fill=self.color, outline="#5c1841") self.clock = Clock() # if fruit is eaten we delete it def eaten(self): canv.delete(self.id) return True # defines if lake is nearby def lake_nearby(self): if ((self.coord_x - x_lake) / (a_axle + 3*self.size)) ** 2 +\ ((self.coord_y - y_lake) / (b_axle + 3*self.size)) ** 2 <= 1: return True else: return False # controls states of fruits and changes it def state_machine(self): if (self.health < 0) or self.age >= Fruit.Dead: self.state = Fruit.st_dead else: if self.age < Fruit.Ripe: self.state = Fruit.st_growing if Fruit.Ripe <= self.age < Fruit.Rotten: self.state = Fruit.st_ripe if self.age >= Fruit.Rotten: self.state = Fruit.st_rotten if self.lake_nearby() is True: self.state = Fruit.st_dead # updates states def update(self): self.state_machine() self.clock.update() if self.state == Fruit.st_dead: self.eaten() else: if self.state == Fruit.st_growing: self.size = self.age / Fruit.Ripe * 3 self.color = Light_green elif self.state == Fruit.st_ripe: self.saturability -= (self.age - Fruit.Rotten) * 10 self.color = Ripe_green elif self.state == Fruit.st_rotten: self.saturability -= (self.age - Fruit.Rotten) self.color = Rotten_green self.clock.start(0.1) self.age += 1 canv.coords( self.id, self.coord_x - 1 * self.size, self.coord_y - 1 * self.size, self.coord_x + 1 * self.size, self.coord_y + 1 * self.size, ) canv.itemconfig(self.id, fill=self.color)
def getText(self): return "FPS: %d" % Clock.get().getFPS()
from SceneGenerator import MovingObject import Clock for i in range(1000): O = MovingObject(50, (512, 512), 60, 30) for f in range(1500): t = f / 50 Clock.update(t) rT, cL, rB, cR = O.getBounds() if ((cR - cL != 50) | (rB - rT) != 50): print(cL, cR) rT, cL, rB, cR = O.getBounds() if ((cR < 0) | (cL) < 0 | rT < 0 | rB < 0): print('Negative')
class Game(): def __init__(self,surface): # Setup initial surface and variables #read what level game is supposed to be self.curLevel = int(open("files/selected_level.txt").read()) #dictionary for level maps LevelsMap = { 1 : Levels.level1Map, 2 : Levels.level2Map, 3 : Levels.level3Map, 4 : Levels.level4Map, 5 : Levels.level5Map, 6 : Levels.level6Map, 7 : Levels.level7Map, 8 : Levels.level8Map, 9 : Levels.level9Map, 10 : Levels.level10Map, 11 : Levels.level11Map, 12 : Levels.level12Map, 13 : Levels.level13Map, 14 : Levels.level14Map, 15 : Levels.level15Map, } #dictionary for obstacle cars LevelsCar = { 1 : [], 2 : [], 3 : [Car(surface, "res/car4.png", 430, 450, 20), Car(surface, "res/car13.png", 550, 460, 17)], 4 : [Car(surface, "res/car9.png", 490, 450, -45), Car(surface, "res/car5.png", 700, 330, -45)], 5 : [Car(surface, "res/car17.png", 220, 340, 30), Car(surface, "res/car18.png", 600, 230, 90), Car(surface, "res/car11.png", 400, 430, 12)], 6 : [Car(surface, "res/car15.png", 680, 420, 30)], 7 : [Car(surface, "res/car2.png", 260, 370, 4), Car(surface, "res/car4.png", 350, 370, 349), Car(surface, "res/car6.png", 510, 370, 14), Car(surface, "res/car16.png", 680, 370, 93), Car(surface, "res/car17.png", 260, 575, 18), Car(surface, "res/car17.png", 360, 575, 18), Car(surface, "res/car17.png", 460, 575, 18), Car(surface, "res/car17.png", 560, 575, 18), Car(surface, "res/car17.png", 660, 575, 18), Car(surface, "res/car17.png", 760, 575, 18)], 8 : [Car(surface, "res/car8.png", 560, 520, 11), Car(surface, "res/car9.png", 730, 520, 17), Car(surface, "res/car10.png", 700, 420, 35), Car(surface, "res/car11.png", 530, 420, 60), Car(surface, "res/car3.png", 610, 320, 85), Car(surface, "res/car4.png", 500, 300, 95), Car(surface, "res/car5.png", 420, 420, 104), Car(surface, "res/car18.png", 300, 420, 90), Car(surface, "res/car17.png", 180, 420, 90), Car(surface, "res/car17.png", 400, 310, 90), Car(surface, "res/car18.png", 280, 310, 90), Car(surface, "res/car16.png", 80, 380, 20)], 9 : [], 10 : [Car(surface, "res/car11.png", 450, 350, 4), Car(surface, "res/car12.png", 450, 480, -4), Car(surface, "res/car6.png", 460, 560, 86), Car(surface, "res/car5.png", 500, 240, -39)], 11 : [Car(surface, "res/car6.png", 150, 650, 5)], 12 : [Car(surface, "res/car3.png", 940, 180, -44), Car(surface, "res/car1.png", 200, 450, 89), Car(surface, "res/car2.png", 720, 480, -90), Car(surface, "res/car16.png", 500, 350, 0)], 13 : [Car(surface, "res/car7.png", 300, 450, 90), Car(surface, "res/car10.png", 640, 200, 95)], 14 : [Car(surface, "res/car13.png", 800, 540, 90)], 15 : [Car(surface, "res/car5.png", 760, 450, 34), Car(surface, "res/car6.png", 950, 430, -44)] } #dictionary for parking location with park object ParkLoc = { 1 : Park(surface, 475, 324), 2 : Park(surface, 240, 260), 3 : Park(surface, 459, 230), 4 : Park(surface, 710, 130), 5 : Park(surface, 700, 200), 6 : Park(surface, 50, 150), 7 : Park(surface, 400, 320), 8 : Park(surface, 100, 150), 9 : Park(surface, 310, 280), 10 : Park(surface, 550, 350), 11 : Park(surface, 730, 220), 12 : Park(surface, 700, 550), 13 : Park(surface, 755, 570), 14 : Park(surface, 670, 410), 15 : Park(surface, 810, 510) } #dictionary for level time Times = { 1 : 30, 2 : 60, 3 : 60, 4 : 60, 5 : 60, 6 : 60, 7 : 60, 8 : 75, 9 : 75, 10 : 75, 11 : 75, 12 : 75, 13 : 75, 14 : 75, 15 : 75, } #read car image that is active self.carImg = open("files/car.txt").read().strip() #dictionary for main car location MainCar = { 1 : Car(surface, self.carImg, surface.get_width()//2,surface.get_height()//2+200,0), 2 : Car(surface, self.carImg, surface.get_width()//2-50,surface.get_height()//2+300,0), 3 : Car(surface, self.carImg, 496,surface.get_height()//2+250,0), 4 : Car(surface, self.carImg, surface.get_width()//2-100,surface.get_height()//2+250,0), 5 : Car(surface, self.carImg, surface.get_width()//2-50,surface.get_height()//2+300,0), 6 : Car(surface, self.carImg, 320, 500, 0), 7 : Car(surface, self.carImg, 850, 475, 0), 8 : Car(surface, self.carImg, 650, 630, 0), 9 : Car(surface, self.carImg, 484, 700, 0), 10 : Car(surface, self.carImg, 180, 250, 0), 11 : Car(surface, self.carImg, 900, 650, 0), 12 : Car(surface, self.carImg, 500, 520, 0), 13 : Car(surface, self.carImg, 120, 640, 0), 14 : Car(surface, self.carImg, 120, 620, 0), 15 : Car(surface, self.carImg, 140, 260, 0) } #set variables based on current level self.parkSpot = ParkLoc[self.curLevel] self.levelTime = Times[self.curLevel] self.surface = surface self.mainCar = MainCar[self.curLevel] #engine start sound mixer.music.load("res/audio/start.mp3") mixer.music.play(0) # mixer.music.load("res/audio/engine.mp3") # mixer.music.play(-1) #setup lives self.lifeCount = 5 self.lifeImage = image.load("res/life.png") #load all images, fonts, and setup flags self.coin_count = open("files/coins.txt").read() self.coin_image = image.load("res/coin_small.png") self.coin_font = font.Font("res/fonts/pricedown.ttf", 32) self.logo = image.load("res/logo_main.png") self.startTime = 0 self.timeDelay = False self.gameover = False #set crash variables self.crash = False self.crashImage = image.load("res/crash.png") self.crashX, self.crashY = 0,0 self.crashTime = 0 self.crashObj = Game self.gear = Gear() self.boundRect = Rect(0,100,surface.get_width(),surface.get_height()-100) self.walls = [] self.grasses = [] self.cones = [] self.carObsctacles = LevelsCar[self.curLevel] self.grass = image.load("res/grass.png").convert() self.timer = Clock(surface, cTime, 1, 1, 0) self.pauseButton = image.load("res/pause.png") self.pauseRect = Rect(940,18,64,64) self.isPause = False self.levelComplete = False # Level maps for walls for x in range(len(LevelsMap[self.curLevel])): for y in range(len(LevelsMap[self.curLevel][x])): if LevelsMap[self.curLevel][x][y] == 1: self.walls.append(Wall(y*16,x*16+100,self.surface)) elif LevelsMap[self.curLevel][x][y] == 2: self.grasses.append((y*16,x*16+100)) elif LevelsMap[self.curLevel][x][y] == 3: self.cones.append(Wall(y*16,x*16+100,self.surface, True)) #load images and setup popup for game end self.wall_y = image.load("res/wall_y.png").convert() self.wall_b = image.load("res/wall_b.png").convert() self.wall = image.load("res/wall.png").convert() self.coneImage = image.load("res/cone.png") #popups self.complete = Popup(surface, "Level Complete", ["You completed the level"], False) self.fail = Popup(surface, "Level Failed", ["Please try again"], False) self.completedIn = 0 self.justEnded = False self.stars = 0 self.nextLevel = image.load("res/next_level.png") self.menuButton = image.load("res/menu.png") self.goNextLevel = False self.goMenu = False self.restart = image.load("res/restart.png") def sTime(self, time): "Setup level timer" self.startTime = time self.timer = Clock(self.surface, time, 1, 1, self.levelTime) def run(self): "Main game run function" self.mx, self.my = mouse.get_pos() self.mb = mouse.get_pressed() #end game and engine delay for 2 seconds if self.timer.gameOver(): self.gameover = True if self.lifeCount == 0: self.gameover = True if cTime()-self.startTime > 2: self.timeDelay = True #blit heads up display self.HUD() #get keys pressed pressed = key.get_pressed() #change gear/speed if pressed[K_1]: self.shift(1) if pressed[K_2]: self.shift(2) if pressed[K_3]: self.shift(3) if pressed[K_4]: self.shift(4) if pressed[K_5]: self.shift(5) #get arrow/wasd keys for driving arrows = [pressed[K_UP], pressed[K_DOWN], pressed[K_RIGHT], pressed[K_LEFT]] if pressed[K_DOWN] and not self.gameover: self.gear.gearImage = image.load("res/gear_r.png") elif not self.gameover: self.gear.gearImage = image.load("res/gear_"+str(self.mainCar.speed)+".png") wasd = [pressed[K_w],pressed[K_s],pressed[K_d],pressed[K_a]] #if game is not ended, drive if not self.gameover: if pressed[K_e]: self.mainCar.brake() self.mainCar.drive() elif True in arrows and self.timeDelay: self.mainCar.drive(pressed[K_UP], pressed[K_DOWN], pressed[K_RIGHT], pressed[K_LEFT]) self.mainCar.brakeSound.stop() elif True in wasd and self.timeDelay: self.mainCar.drive(pressed[K_w],pressed[K_s],pressed[K_d],pressed[K_a]) self.mainCar.brakeSound.stop() else: self.mainCar.drive() self.mainCar.brakeSound.stop() #blit obstacle cars and check collisoin from main car for car in self.carObsctacles: if Rect((car.x-car.boundingRect[2]/2,car.y-car.boundingRect[3]/2, car.boundingRect[2], car.boundingRect[3])).colliderect(Rect(self.mainCar.x-self.mainCar.boundingRect[2]/2,self.mainCar.y-self.mainCar.boundingRect[3]/2, self.mainCar.carImageRotated.get_rect()[2], self.mainCar.carImageRotated.get_rect()[3])): for pt in self.mainCar.outlineRotated: if (int(pt[0]),int(pt[1])) in car.outlineRotated and self.timeDelay: self.crash = True self.crashX, self.crashY = int(pt[0]),int(pt[1]) self.crashObj = car car.render() #blit walls, cone, and grass yellow = False for wall in self.walls: if yellow: wall.render(self.wall_y) yellow = False else: wall.render(self.wall_b) yellow = True if wall.getBoundRect().colliderect((self.mainCar.x-self.mainCar.boundingRect[2]/2,self.mainCar.y-self.mainCar.boundingRect[3]/2, self.mainCar.carImageRotated.get_rect()[2], self.mainCar.carImageRotated.get_rect()[3])): for pt in self.mainCar.outlineRotated: if wall.getBoundRect().collidepoint(pt) and self.timeDelay: self.crash = True self.crashX, self.crashY = int(pt[0]),int(pt[1]) self.crashObj = wall for gr in self.grasses: self.surface.blit(self.grass, gr) for cone in self.cones: cone.render(self.coneImage) if cone.getBoundRect().colliderect((self.mainCar.x-self.mainCar.boundingRect[2]/2,self.mainCar.y-self.mainCar.boundingRect[3]/2, self.mainCar.carImageRotated.get_rect()[2], self.mainCar.carImageRotated.get_rect()[3])): for pt in self.mainCar.outlineRotated: if cone.getBoundRect().collidepoint(pt) and self.timeDelay: self.crash = True self.crashX, self.crashY = int(pt[0]),int(pt[1]) self.crashObj = wall #render parking spot and main car self.parkSpot.render() self.mainCar.render() #if car crashed restart car, remove life, and blit crash sign if self.crash: self.surface.blit(self.crashImage, (self.crashX-40,self.crashY-34)) self.crash = False self.mainCar.crashed(self.crashObj, (self.crashX, self.crashY)) self.lostLife() self.crashTime = cTime() self.timeDelay = False self.startTime = cTime() if self.lifeCount > 0: mixer.music.load("res/audio/start.mp3") mixer.music.play(0) #end game if gameover and write to files if self.gameover: if self.levelComplete: self.complete.setText(["Level completed in %s seconds" % str(self.timeLeft)]) self.complete.render(self.stars) self.surface.blit(self.nextLevel, (550,500)) self.surface.blit(self.menuButton, (350,470)) newUnlock = open("files/unlocked_levels.txt").read() if int(newUnlock) == self.curLevel: newUnlock = str(int(newUnlock)+1) f1 = open("files/unlocked_levels.txt", "w") f1.write(newUnlock) f1.close() if self.curLevel < 15 and Rect(550,500,162,48).collidepoint(self.mx,self.my) and self.mb[0]: f2 = open("files/selected_level.txt", "w") f2.write(str(self.curLevel+1)) f2.close() self.goNextLevel = True elif Rect(350,470,82,84).collidepoint(self.mx,self.my) and self.mb[0]: self.goMenu = True else: self.fail.render(0) self.surface.blit(self.restart, (480, 384)) if Rect(480,384,64,64).collidepoint(self.mx,self.my) and self.mb[0]: self.goNextLevel = True #check if car is in parking and asign stars based on time and life if self.mainCar.checkPark(self.parkSpot): if not self.justEnded: self.justEnded = True self.timeLeft = int(ceil(self.levelTime - self.timer.end())) if self.timeLeft < self.levelTime/4 and self.lifeCount == 5: self.stars = 3 elif self.timeLeft < self.levelTime/2 and self.lifeCount >= 3: self.stars = 2 else: self.stars = 1 coins = int(open("files/coins.txt").read()) + self.stars open("files/coins.txt", "w").write(str(coins)) starF = open("files/stars.txt").read().split("\n") if int(starF[self.curLevel-1]) < self.stars: starF[self.curLevel-1] = str(self.stars) open("files/stars.txt", "w").write("\n".join(starF)) self.levelComplete = True def HUD(self): "Heads up display that has logo, coins, timer" self.header = draw.rect(self.surface, (51, 153, 255), (0,0,self.surface.get_width(),100)) self.surface.blit(self.gear.gearImage, (0,0)) livesLocation = 750 #blit lives for i in range(self.lifeCount): self.surface.blit(self.lifeImage, (livesLocation, 34)) livesLocation += 37 #blit logo and timer self.surface.blit(self.logo, (self.surface.get_width()//2-(self.logo.get_width()//2),13)) if not self.gameover: self.timer.render() #blit coins self.surface.blit(self.coin_image, (615,34)) self.surface.blit(self.coin_font.render(self.coin_count, 1, (255,255,255)), (650,28)) def lostLife(self): "Remove a life" self.lifeCount -= 1 def shift(self, gear=0, reverse=False): "Takes in gear/speed and if reverse and blits gear respectively and changes speed" self.gear.gear = gear self.gear.reverse = reverse self.gear.gearImage = image.load("res/gear_"+str(gear)+".png") self.mainCar.speed = gear def getWall(self): "Gets all the walls" return self.walls def isNextLevel(self): "Checks if level complete and go to next level" return self.goNextLevel def startMenu(self): "Go back to menu screen" return self.goMenu
instruc = CU.read_instructions('ins4.code') CU.orchestra(instruc, clock_speed[1], REM.RAM) x = input('Continue with file No. 5? (y/n)\n') if x == 'n' or x == 'N': ALU.HALT() else: pass print('\n---------- Executing file No. 5 ----------') instruc = CU.read_instructions('ins5.code') CU.orchestra(instruc, clock_speed[1], REM.RAM) print('\n ---------- End Program ---------- \n') if __name__ == "__main__": REG = Registers(4) REM = RAM(16) read = CU() clock = Clock('clock', 'i5', 'Intel') CU.turn_on(CU, 'bios.yml', 'instructions.code', REM.RAM) # Imprime los valores de la ram en decima clock_speed = (CU.read_instructions('bios.yml')) Brain() #instruc = CU.read_instructions('instructions.code') # Instruc es el arreglo de instrucciones #CU.orchestra(instruc, clock_speed[1], REM.RAM)
def __init__(self,surface): # Setup initial surface and variables #read what level game is supposed to be self.curLevel = int(open("files/selected_level.txt").read()) #dictionary for level maps LevelsMap = { 1 : Levels.level1Map, 2 : Levels.level2Map, 3 : Levels.level3Map, 4 : Levels.level4Map, 5 : Levels.level5Map, 6 : Levels.level6Map, 7 : Levels.level7Map, 8 : Levels.level8Map, 9 : Levels.level9Map, 10 : Levels.level10Map, 11 : Levels.level11Map, 12 : Levels.level12Map, 13 : Levels.level13Map, 14 : Levels.level14Map, 15 : Levels.level15Map, } #dictionary for obstacle cars LevelsCar = { 1 : [], 2 : [], 3 : [Car(surface, "res/car4.png", 430, 450, 20), Car(surface, "res/car13.png", 550, 460, 17)], 4 : [Car(surface, "res/car9.png", 490, 450, -45), Car(surface, "res/car5.png", 700, 330, -45)], 5 : [Car(surface, "res/car17.png", 220, 340, 30), Car(surface, "res/car18.png", 600, 230, 90), Car(surface, "res/car11.png", 400, 430, 12)], 6 : [Car(surface, "res/car15.png", 680, 420, 30)], 7 : [Car(surface, "res/car2.png", 260, 370, 4), Car(surface, "res/car4.png", 350, 370, 349), Car(surface, "res/car6.png", 510, 370, 14), Car(surface, "res/car16.png", 680, 370, 93), Car(surface, "res/car17.png", 260, 575, 18), Car(surface, "res/car17.png", 360, 575, 18), Car(surface, "res/car17.png", 460, 575, 18), Car(surface, "res/car17.png", 560, 575, 18), Car(surface, "res/car17.png", 660, 575, 18), Car(surface, "res/car17.png", 760, 575, 18)], 8 : [Car(surface, "res/car8.png", 560, 520, 11), Car(surface, "res/car9.png", 730, 520, 17), Car(surface, "res/car10.png", 700, 420, 35), Car(surface, "res/car11.png", 530, 420, 60), Car(surface, "res/car3.png", 610, 320, 85), Car(surface, "res/car4.png", 500, 300, 95), Car(surface, "res/car5.png", 420, 420, 104), Car(surface, "res/car18.png", 300, 420, 90), Car(surface, "res/car17.png", 180, 420, 90), Car(surface, "res/car17.png", 400, 310, 90), Car(surface, "res/car18.png", 280, 310, 90), Car(surface, "res/car16.png", 80, 380, 20)], 9 : [], 10 : [Car(surface, "res/car11.png", 450, 350, 4), Car(surface, "res/car12.png", 450, 480, -4), Car(surface, "res/car6.png", 460, 560, 86), Car(surface, "res/car5.png", 500, 240, -39)], 11 : [Car(surface, "res/car6.png", 150, 650, 5)], 12 : [Car(surface, "res/car3.png", 940, 180, -44), Car(surface, "res/car1.png", 200, 450, 89), Car(surface, "res/car2.png", 720, 480, -90), Car(surface, "res/car16.png", 500, 350, 0)], 13 : [Car(surface, "res/car7.png", 300, 450, 90), Car(surface, "res/car10.png", 640, 200, 95)], 14 : [Car(surface, "res/car13.png", 800, 540, 90)], 15 : [Car(surface, "res/car5.png", 760, 450, 34), Car(surface, "res/car6.png", 950, 430, -44)] } #dictionary for parking location with park object ParkLoc = { 1 : Park(surface, 475, 324), 2 : Park(surface, 240, 260), 3 : Park(surface, 459, 230), 4 : Park(surface, 710, 130), 5 : Park(surface, 700, 200), 6 : Park(surface, 50, 150), 7 : Park(surface, 400, 320), 8 : Park(surface, 100, 150), 9 : Park(surface, 310, 280), 10 : Park(surface, 550, 350), 11 : Park(surface, 730, 220), 12 : Park(surface, 700, 550), 13 : Park(surface, 755, 570), 14 : Park(surface, 670, 410), 15 : Park(surface, 810, 510) } #dictionary for level time Times = { 1 : 30, 2 : 60, 3 : 60, 4 : 60, 5 : 60, 6 : 60, 7 : 60, 8 : 75, 9 : 75, 10 : 75, 11 : 75, 12 : 75, 13 : 75, 14 : 75, 15 : 75, } #read car image that is active self.carImg = open("files/car.txt").read().strip() #dictionary for main car location MainCar = { 1 : Car(surface, self.carImg, surface.get_width()//2,surface.get_height()//2+200,0), 2 : Car(surface, self.carImg, surface.get_width()//2-50,surface.get_height()//2+300,0), 3 : Car(surface, self.carImg, 496,surface.get_height()//2+250,0), 4 : Car(surface, self.carImg, surface.get_width()//2-100,surface.get_height()//2+250,0), 5 : Car(surface, self.carImg, surface.get_width()//2-50,surface.get_height()//2+300,0), 6 : Car(surface, self.carImg, 320, 500, 0), 7 : Car(surface, self.carImg, 850, 475, 0), 8 : Car(surface, self.carImg, 650, 630, 0), 9 : Car(surface, self.carImg, 484, 700, 0), 10 : Car(surface, self.carImg, 180, 250, 0), 11 : Car(surface, self.carImg, 900, 650, 0), 12 : Car(surface, self.carImg, 500, 520, 0), 13 : Car(surface, self.carImg, 120, 640, 0), 14 : Car(surface, self.carImg, 120, 620, 0), 15 : Car(surface, self.carImg, 140, 260, 0) } #set variables based on current level self.parkSpot = ParkLoc[self.curLevel] self.levelTime = Times[self.curLevel] self.surface = surface self.mainCar = MainCar[self.curLevel] #engine start sound mixer.music.load("res/audio/start.mp3") mixer.music.play(0) # mixer.music.load("res/audio/engine.mp3") # mixer.music.play(-1) #setup lives self.lifeCount = 5 self.lifeImage = image.load("res/life.png") #load all images, fonts, and setup flags self.coin_count = open("files/coins.txt").read() self.coin_image = image.load("res/coin_small.png") self.coin_font = font.Font("res/fonts/pricedown.ttf", 32) self.logo = image.load("res/logo_main.png") self.startTime = 0 self.timeDelay = False self.gameover = False #set crash variables self.crash = False self.crashImage = image.load("res/crash.png") self.crashX, self.crashY = 0,0 self.crashTime = 0 self.crashObj = Game self.gear = Gear() self.boundRect = Rect(0,100,surface.get_width(),surface.get_height()-100) self.walls = [] self.grasses = [] self.cones = [] self.carObsctacles = LevelsCar[self.curLevel] self.grass = image.load("res/grass.png").convert() self.timer = Clock(surface, cTime, 1, 1, 0) self.pauseButton = image.load("res/pause.png") self.pauseRect = Rect(940,18,64,64) self.isPause = False self.levelComplete = False # Level maps for walls for x in range(len(LevelsMap[self.curLevel])): for y in range(len(LevelsMap[self.curLevel][x])): if LevelsMap[self.curLevel][x][y] == 1: self.walls.append(Wall(y*16,x*16+100,self.surface)) elif LevelsMap[self.curLevel][x][y] == 2: self.grasses.append((y*16,x*16+100)) elif LevelsMap[self.curLevel][x][y] == 3: self.cones.append(Wall(y*16,x*16+100,self.surface, True)) #load images and setup popup for game end self.wall_y = image.load("res/wall_y.png").convert() self.wall_b = image.load("res/wall_b.png").convert() self.wall = image.load("res/wall.png").convert() self.coneImage = image.load("res/cone.png") #popups self.complete = Popup(surface, "Level Complete", ["You completed the level"], False) self.fail = Popup(surface, "Level Failed", ["Please try again"], False) self.completedIn = 0 self.justEnded = False self.stars = 0 self.nextLevel = image.load("res/next_level.png") self.menuButton = image.load("res/menu.png") self.goNextLevel = False self.goMenu = False self.restart = image.load("res/restart.png")