def MakeMap(filepath, targetRes): """ rtype: array, tuple returns: array """ data = ParseMap(filepath) if data == -1: return #import circles here to avoid circular import from .circle import Circle circles = [] for element in data: try: posX = float(element[0]) posY = float(element[1]) time = int(element[2]) tposX, tposY = TranslateCoord((posX, posY), targetRes, TranslationMode.Decode) obj = Circle((tposX, tposY), time) circles.append(obj) except IndexError: print( 'Cannot make object {}.\n Maybe map has outdated or invalid format.' .format(str(obj))) return Log("Map '{}' loaded succesfully.".format(filepath), LogLevel.Info, __name__) return circles
def LoadTexture(self, filename, type): try: if type == TextureType.JPG: tex = pygame.image.load(filename).convert() elif type == TextureType.PNG: tex = pygame.image.load(filename).convert_alpha() else: raise RuntimeError("Invalid texture type.") except Exception: Log("Cannot load texture from file '{}'.".format(filename), LogLevel.Error, __name__) raise return tex
def __init__(self, win, menu): self.win = win self.menu = menu self.width = win.get_width() self.height = win.get_height() self.isRunning = True self.clickCount = [0, 0] #[0] stands for left key, [1] for right self.cursorPos = (0, 0) self.map = None self.playfield = GetPlayfield(self.width, self.height, CS) self.points = 0 self.combo = 0 self.maxHealth = 100 self.health = self.maxHealth self.buttonClicked = False self.drawInterface = True self.backgroundName = 'bg_' + str(random.randint(0, 6)) self.events = pygame.event.get() self.renderStats = RenderStats() self.clock = pygame.time.Clock() #GUI elements if prefs.useNewFpsCounter: self.fpsCounter = NewStyleFpsCounter(mainResManager.GetFont("comicsansms_10"), (self.width - 2, 27), (113, 110)) Log("Using new style fps counter. This may decrease performance.", LogLevel.Warning, __name__) else: self.fpsCounter = FpsCounter(mainResManager.GetFont("comicsansms_12"), (self.width - 2, self.height - 2)) self.healthBar = HealthBar(mainResManager.GetFont("comicsansms_22"), (self.width / 10, 0), (self.width - (2 * self.width / 10), 25)) self.pointsText = PointsCounter(mainResManager.GetFont("comicsansms_48"), (self.width - 2, self.height - 14)) self.comboText = ComboCounter(mainResManager.GetFont("comicsansms_48"), (2, self.height - 14)) self.clicksText = ClicksCounter(mainResManager.GetFont("comicsansms_21"), (self.width - 2, self.height / 2)) self.time = 0.0 self.time_ms = 0 self.renderThread = threading.Thread(target=self.Render, name="ossRender") #at the end of initialization trigger garbage collection FreeMem('Started after-init garbage collection.')
def Run(self): while self.isRunning: start = timer() for event in pygame.event.get(): if event.type == pygame.MOUSEMOTION: self.cursorPos = pygame.mouse.get_pos() if event.type == pygame.QUIT: self.isRunning = False if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: self.isRunning = False if event.key == prefs.keyBinds["savePreferencies"]: prefs.ExportToFile(prefs.PREFS_FILE) Log("Saved user settings.", LogLevel.Info, __name__) self.AddMessage("Saved user settings") self.startButton.Update() self.exitButton.Update() self.editorButton.Update() self.settingsButton.Update() if len(self.messages) != 0: self.messages[0].Update(self.frameTime) if self.messages[0].dispose: self.messages.remove(self.messages[0]) if self.game: self.startButton.text = 'Game is currently running' self.startButton.activeColor = Color.Red self.startButton.inactiveColor = Color.Red self.DrawBackground() self.DrawButtons() self.DrawMessageBox() self.DrawCursor() pygame.display.flip() self.frameTime = timer() - start self.time += self.frameTime
def Click(self): Log("Last registered: {}, {}".format(self.time, self.cursorPos), LogLevel.Info, __name__) if Editor.regMode == RegisterMode.Time: TIME_FILE.write("{}. object at time: {}\n".format( self.objCount, self.time)) self.objCount += 1 elif Editor.regMode == RegisterMode.Position: tPos = TranslateCoord(self.cursorPos, (self.width, self.height), TranslationMode.Encode) POS_FILE.write("{}. object at position: {}, {}\n".format( self.objCount, tPos[0], tPos[1])) lastReg = self.cursorPos self.lastRegs[0], self.lastRegs[1] = self.lastRegs[1], lastReg self.objCount += 1 else: print('Wrong register mode! Changing register mode to "time".') Editor.regMode = RegisterMode.Time
def Run(self): if not prefs.autoGenerate: Map.resolution = (self.width, self.height) self.map = Map('Resources/maps/test.txt') else: self.map = EmptyMap() self.GenerateRandomCircle() if self.map.loadSuccess == -1: Log("An error appeared during map loading.", LogLevel.Error, __name__) self.menu.AddMessage("An error appeared during map loading.") self.isRunning = False #free memory after map loading FreeMem('Started after map loading garbage collection.') self.renderThread.start() while self.isRunning: self.Update() self.renderThread.join() self.Close()
def ParseMap(filepath): data = [] lineCount = 0 try: with open(filepath, "r") as f: for line in f.readlines(): lineCount += 1 if line[0] == '#' or line[0] == "[": continue lineData = line.split(",") newLineData = [] for x in lineData: x = x.replace("\n", "") x = x.replace(" ", "") try: x = float(x) except ValueError: #if even a single fragment of any line failed to parse stop loading rest of map Log("Invalid map format at line {}".format(lineCount), LogLevel.Error, __name__) return -1 newLineData.append(x) data.append(newLineData) except IOError: print("Error cannot load map: File {} didn't found.".format(filepath)) return -1 return data
def Update(self): updateStart = timer() eventStart = timer() self.events = pygame.event.get() for event in self.events: if event.type == pygame.MOUSEMOTION: self.cursorPos = pygame.mouse.get_pos() if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: self.isRunning = False Log("User interruption by closing window.", LogLevel.Info, __name__) if event.key == prefs.keyBinds['hideInterface']: self.drawInterface = not self.drawInterface Log("Interface hidden.", LogLevel.Info, __name__) if event.key == prefs.keyBinds['kl']: self.clickCount[0] += 1 self.buttonClicked = True if event.key == prefs.keyBinds['kr']: self.clickCount[1] += 1 self.buttonClicked = True if event.key != prefs.keyBinds['kl'] and event.key != prefs.keyBinds['kr']: self.buttonClicked = False if event.type == pygame.MOUSEBUTTONDOWN and not prefs.mouseButtonsDisable: if event.button == 1: self.clickCount[0] += 1 elif event.button == 3: self.clickCount[1] += 1 if event.type == pygame.QUIT: self.isRunning = False Log("User interruption by closing window.", LogLevel.Info, __name__) self.renderStats.eventHandlingTime = timer() - eventStart if self.health <= 0: Log("Health reached below zero.", LogLevel.Info, __name__) self.isRunning = False if self.health >= self.maxHealth: self.health = self.maxHealth if self.time_ms >= self.map.length: self.map.shouldPlay = False if not self.map.shouldPlay: Log("Map has ended.", LogLevel.Info, __name__) self.isRunning = False self.__UpdateCircles() self.renderStats.blitCount = self.pointsText.blitsRequired + self.comboText.blitsRequired + self.fpsCounter.blitsRequired + self.healthBar.blitsRequired + self.clicksText.blitsRequired for circle in self.map.objectsLeft: if circle.shouldDraw: self.renderStats.blitCount += 1 self.renderStats.updateTime = timer() - updateStart self.renderStats.frameTime = self.renderStats.updateTime + self.renderStats.renderTime self.health -= HP * self.renderStats.updateTime * 79.2