class Frogger(QWidget): def __init__(self): super().__init__() Config.mainWindow = self #odma se postavi koji objekat je mainWindow da bi tamo u Rectangle.py Qlabeli znali gde treba da se nacrtaju. Lose je resenje, al radi bar za testiranje self.Menu = None # glavni meni self.InitFlagsAndVariables() self.scoreboard = Scoreboard(self) self.highscore = HighScore() self.highscore.readFromFile() ############################################### self.videoWidget = QVideoWidget(self) self.videoWidget.resize(Config.mapSize * Config.gridSize, Config.mapSize * Config.gridSize + 50) self.mediaPlayer = QMediaPlayer(None, QMediaPlayer.VideoSurface) self.mediaPlayer.setVideoOutput(self.videoWidget) self.mediaPlayer.setMedia( QMediaContent(QUrl(Config.spriteLocation + "Intro.wmv"))) ############################################### self.setWindowState(Qt.WindowNoState) self.__init_ui__() self.key_notifier = KeyNotifier() self.key_notifier.key_signal.connect(self.__update_position__) self.key_notifier.start() self.ZevsJavljaVremeQueue = Queue() self.procUKomZiviZevs = Zeus.PokreniZevsa( self.ZevsJavljaVremeQueue ) #pokrece proces koji u kju stavlja kakvo vreme treba da bude (sunce, kisa, sneg) def InitFlagsAndVariables(self): self.Map = [] # lista lejnova self.previousWeather = 'n' self.player1 = None self.player2 = None self.player1RectId = -1 # ovo je potrebno za mrezu self.player2RectId = -1 # ovo je potrebno za mrezu self.gamePaused = False self.GameOverBrojac = 0 # za zivote, ako je 2PlayerMode, kad igrac izgubi sve zivote povecava brojac za 1, kad oba izgube sve zivote, brojac je 2 i tad je gameOver # ako je SinglePlayer mod onda je gameOver ako je brojac 1 self.Level = 1 # za levele Config.p1Score = 0 Config.p2Score = 0 Config.p1Lives = 5 Config.p2Lives = 5 try: self.ShutDownHost() except: pass try: self.ShutDownClient() except: pass self.host = None self.client = None self.isHost = False self.isClient = False def initVideo(self): self.videoWidget.show() self.mediaPlayer.play() def __init_ui__(self): self.setWindowTitle('Frogger') self.setWindowIcon(QtGui.QIcon(Config.spriteLocation + 'iconFrog.png')) #ikonica self.resize(Config.mapSize * Config.gridSize, Config.mapSize * Config.gridSize + 50) self.FixWindowSize() self.show() self.initVideo() q = QTimer() q.singleShot(6000, self.DisplayMainMenu) def HsFunkc(self): self.Menu.HsElementsShow(self.highscore.top3) #obicna funkcija za fiksiranje velicine prozora def FixWindowSize(self): self.setMinimumHeight((Config.mapSize + 1) * Config.gridSize) self.setMinimumWidth(Config.mapSize * Config.gridSize) self.setMaximumHeight((Config.mapSize + 1) * Config.gridSize) self.setMaximumWidth(Config.mapSize * Config.gridSize) def RemoveVideoIntro(self): try: self.mediaPlayer.stop() self.videoWidget.setParent(None) self.videoWidget = None except: pass def DisplayMainMenu(self): self.RemoveVideoIntro() self.Menu = None self.Menu = Meni(self, self.SinglePlayerMode, self.TwoPlayerMode, self.HsFunkc, self.MainMenuHostClick, self.MainMenuJoinClick, self.CloseWindow) def PauseGame(self): self.gamePaused = True self.updaterGameObjekataThread.PauseGame() def ResumeGame(self): self.gamePaused = False self.updaterGameObjekataThread.ResumeGame() def RemoveAllGameUIObjects(self): for lejer, lista in Rectangle.allRectangles.items(): for rect in lista: rect.RemoveFromScreen() GameObject.allGameObjects = [] Rectangle.allRectangles = {} Rectangle.ResetId() def SinglePlayerMode(self): self.ClearZeusQueue() self.Menu.HideMainMenu() self.DisplayMap( ) #u displayMap se kreira objekat self.updaterGameObjekataThread i zato DisplayMap mora ici prvi self.createThreadToUpdateGameObjects() self.startThreadForUpdatingGameObjects() self.scoreboard.ShowScore() self.CreatePlayers() Config.collectLilypadsToAdvanceLevel = 1 def ClearZeusQueue(self): while not self.ZevsJavljaVremeQueue.empty(): self.ZevsJavljaVremeQueue.get() def TwoPlayerMode(self, OverNetworkGame=False): self.ClearZeusQueue() self.Menu.HideMainMenu() if not OverNetworkGame: #kad je preko mreze onda updateovanje krece kad klijent bude spreman self.createThreadToUpdateGameObjects() self.startThreadForUpdatingGameObjects() self.DisplayMap(TwoPlayers=True) self.scoreboard.ShowScores() self.CreatePlayers(TwoPlayers=True) Config.collectLilypadsToAdvanceLevel = 3 def MainMenuHostClick(self): self.HostServer(Config.serverAddress, Config.serverPort) def MainMenuJoinClick(self): #self.Menu.JoinWidgetHide() self.setFocus() #ovde sacuvamo ip adresu i port u fajl. da kad se sledeci put upali igra da odma ucita tu ipadresu i port try: with open(Config.lastIp_filename, "w") as f: f.write(str(self.Menu.ipAddr) + ":" + str(self.Menu.port)) except: pass self.JoinServer(self.Menu.ipAddr, int(self.Menu.port)) def CreatePlayers(self, TwoPlayers=False): self.player1 = Frog(Config.player1StartPosition[0], Config.player1StartPosition[1], self.GameOverCheck, self.updateP1Score, self.createGreenLives) self.player1RectId = self.player1.id if TwoPlayers: self.player2 = Frog(Config.player2StartPosition[0], Config.player2StartPosition[1], self.GameOverCheck, self.updateP2Score, self.createPinkLives, isPlayerTwo=True) self.player2RectId = self.player2.id def updateP1Score(self, newScore): self.scoreboard.updateP1Score(newScore) if self.isHost: self.host.SendToClient(Config.network_updateGameScoreAndLives + ":" + "P1S_" + str(newScore)) #P2L => Player 2 Lives def updateP2Score(self, newScore): self.scoreboard.updateP2Score(newScore) if self.isHost: self.host.SendToClient(Config.network_updateGameScoreAndLives + ":" + "P2S_" + str(newScore)) #P2L => Player 2 Lives def createPinkLives(self, lives): self.scoreboard.CreatePinkLives(lives) if self.isHost: self.host.SendToClient(Config.network_updateGameScoreAndLives + ":" + "P2L_" + str(lives)) #P2L => Player 2 Lives def createGreenLives(self, lives): self.scoreboard.CreateGreenLives(lives) if self.isHost: self.host.SendToClient(Config.network_updateGameScoreAndLives + ":" + "P1L_" + str(lives)) #P1L => Player 2 Lives def DisplayMap(self, TwoPlayers=False): self.Map.append(Lane.GenerateSafetyLane()) #prvi je uvek sejf lejn self.GenerateLanes('Road') #fja da generise lejnove za put #self.Map.append(Lane.GenerateSafetyLane()) ##ovaj ce da bude uvek tu da bi se moglo duze igrati ##lejn sa zivotom self.Map.append(Lane.GenerateSafetyLaneWithDeus()) self.GenerateLanes('Water') #fja da generise lejnove za reku if TwoPlayers: self.Map.append(Lane.GenerateFinalLane( self.LevelPassed)) # zadnji je uvek finalLane else: self.Map.append( Lane.GenerateFinalLane( self.LevelPassed, lilyPadPattern=Config.lilypadPatternBO5Standard) ) # zadnji je uvek finalLane def GameOverCheck(self, isPlayerTwo): #fja koja se poziva kada igrac ima 0 zivota, prosledjuje se igracima kroz konstruktor self.GameOverBrojac += 1 if self.player1 != None and self.player2 != None: if self.GameOverBrojac == 1: if isPlayerTwo: self.highscore.checkIfHighScore(self.player2.playerName, self.player2.score) self.player2.RemoveFromScreen() self.player2 = None Config.p2Lives = 0 else: self.highscore.checkIfHighScore(self.player1.playerName, self.player1.score) self.player1.RemoveFromScreen() self.player1 = None Config.p1Lives = 0 elif self.player1 != None: self.highscore.checkIfHighScore(self.player1.playerName, self.player1.score) self.GameOver() elif self.player2 != None: self.highscore.checkIfHighScore(self.player2.playerName, self.player2.score) self.GameOver() def GameOver(self): # javimo klijentu da bi se vratio na meni if self.isHost: self.host.SendToClient(Config.network_ConnectionError) #fja koja se poziva kad su svi igraci igraci ostali bez zivota self.stopThreadForUpdatingObjects() self.DeleteMap(deleteP1=True, deleteP2=True) self.Menu.ShowMainMenu() Lane.ResetLaneStartingIndex() self.scoreboard.HideScores() self.Menu.kisa.hide() self.Menu.sneg.hide() self.scoreboard.CreateGreenLives(0) self.scoreboard.CreatePinkLives(0) self.InitFlagsAndVariables() def ShutDownHost(self): if self.host != None: print("gasim hosta") self.host.StopHosting() self.isHost = False self.host = None def ShutDownClient(self): if self.client != None: self.client.StopClienting() self.isClient = False self.client = None def LevelPassed(self): #fja koja se poziva kad su svih 5 Lilypada popunjena, prosledjuje se u konstruktoru, prvo finalLejnu pa samim objektima self.Level += 1 Lane.ResetLaneStartingIndex() self.GameOverBrojac = 0 self.DeleteMap() if self.player1 != None and self.player2 != None: Config.p1Score = self.player1.score Config.p2Score = self.player2.score Config.p1Lives = self.player1.lives Config.p2Lives = self.player2.lives self.DisplayMap(TwoPlayers=True) self.CreatePlayers(TwoPlayers=True) elif self.player1 != None: Config.p1Score = self.player1.score Config.p1Lives = self.player1.lives self.DisplayMap() self.CreatePlayers() elif self.player2 != None: Config.p2Score = self.player2.score Config.p2Lives = self.player2.lives self.DisplayMap() self.CreatePlayers(TwoPlayers=True) self.player1.RemoveFromScreen() self.player1 = None if self.isHost and self.player2 != None: self.SendClientToReplicateObjects() def DeleteMap(self, deleteP1=False, deleteP2=False): if deleteP1: try: self.player1.RemoveFromScreen() self.player1 = None except: print('P1 vec postavljen na None') if deleteP2: try: self.player2.RemoveFromScreen() self.player2 = None except: print('P2 vec postavljen na None') for lane in self.Map: for obs in lane.obstacles: obs.RemoveFromScreen() lane.obstacles.clear() lane.RemoveFromScreen() for layer, listOfRectanglesInLayer in Rectangle.allRectangles.items(): for rect in listOfRectanglesInLayer: rect.RemoveFromScreen() listOfRectanglesInLayer.clear() self.Map.clear() def DisplayTestMap(self): Lane.ResetLaneStartingIndex() self.Map.append(Lane.GenerateSafetyLane()) self.Map.append(Lane.GenerateEasyLane()) self.Map.append(Lane.GenerateEasyLane()) self.Map.append(Lane.GenerateEasyLane()) self.Map.append(Lane.GenerateSafetyLane()) self.Map.append(Lane.GenerateFinalLane()) self.Map.append( Lane.GenerateFinalLane(lilyPadPattern=Config.lilypadPatternBO3)) self.Map.append( Lane.GenerateFinalLane(lilyPadPattern=Config.lilypadPatternBO5V2)) self.Map.append(Lane.GenerateFinalLane(randomPatternBO5=True)) def keyPressEvent(self, event): if not event.isAutoRepeat(): self.key_notifier.add_key(event.key()) def __update_position__(self, key): if not self.isClient: if key == Qt.Key_Escape and self.gamePaused: self.ResumeGame() elif key == Qt.Key_Escape and not self.gamePaused: self.PauseGame() if self.isClient: #ako sam klijent onda pored pomeranja zabe, hocu da posaljem INPUT serveru if key == Qt.Key_Right: self.client.SendToServer(Config.network_inputKlijentaPrefix + "DESNO") elif key == Qt.Key_Down: self.client.SendToServer(Config.network_inputKlijentaPrefix + "DOLE") elif key == Qt.Key_Up: self.client.SendToServer(Config.network_inputKlijentaPrefix + "GORE") elif key == Qt.Key_Left: self.client.SendToServer(Config.network_inputKlijentaPrefix + "LEVO") if key == Qt.Key_T: for go in GameObject.allGameObjects: print(str(go.id) + "__" + str(go.loadedSprite)) if self.gamePaused: #sve sto je ispod nece biti odradjeno kad je game pauziran return if self.player1 != None: self.player1.KeyPress(key) if self.player2 != None: self.player2.KeyPress(key) def CloseWindow(self): # OVDE TREBA DA SE POZOVE KOD KOJI CE DA ZAUSTAVI ZEVSA # (ako uopste postoji neko toliko jak da zaustavi zevsa) try: self.procUKomZiviZevs.terminate() except: pass try: self.updaterGameObjekataThread.updaterThreadWork = False # self.updaterGameObjekataThread se kreira samo kad pocne IGRA. Ako budes na meniju i nista ne radis nece se kreirati except: pass self.key_notifier.die() def closeEvent(self, event): self.CloseWindow() def createThreadToUpdateGameObjects(self): self.updaterGameObjekataThread = GOUpdater() self.updaterGameObjekataThread.nekiObjekat.connect( self.updateAllGameObjects) #OVO (thread koji updateuje objekte) SE POKRECE KAD KLIJENT BUDE SPREMAN (nakon sto preuzme sve objekte i nacrta ih na ekranu), ili kad pocne neki od lokalnih game modova #self.updaterGameObjekataThread.start() def startThreadForUpdatingGameObjects(self): self.updaterGameObjekataThread.start() def stopThreadForUpdatingObjects(self): try: #na klijentu ovaj objekat za updateovanje ce biti null self.updaterGameObjekataThread.updaterThreadWork = False except: pass def updateAllGameObjects(self, dummy): #callback funkcija for gameObject in GameObject.allGameObjects: gameObject.update() # ako je instanca server i postoje gameobjekti onda da salje klijentu pozicije tih objekata if self.isHost and len(GameObject.allGameObjects) > 0: self.SendRectPositionUpdateToClient() if not self.ZevsJavljaVremeQueue.empty(): self.updateWeather(self.ZevsJavljaVremeQueue.get()) else: return def updateWeather(self, newWeather): if self.isHost: self.host.SendToClient(Config.network_updateWeatherInfo + ":" + newWeather) if newWeather == 'k': if self.previousWeather == 'k': self.ZaustaviKisu() elif self.previousWeather == 's': self.ZaustaviSneg() self.PokreniKisu() elif newWeather == 's': if self.previousWeather == 'k': self.ZaustaviKisu() elif self.previousWeather == 's': self.ZaustaviSneg() self.PokreniSneg() elif newWeather == 'n': if self.previousWeather == 'k': self.ZaustaviKisu() elif self.previousWeather == 's': self.ZaustaviSneg() self.previousWeather = newWeather def createLanes(self, niz, type): #funkcija koja generise lejnove u zavisnosti od prosledjenog niza i karaktera u njemu if type == 'Road': for letter in niz: if letter == 'e': self.Map.append(Lane.GenerateEasyLane()) elif letter == 'm': self.Map.append(Lane.GenerateMediumLane()) elif letter == 'h': self.Map.append(Lane.GenerateHardLane()) elif type == 'Water': for letter in niz: if letter == 'e': self.Map.append(Lane.GenerateEasyWaterLane()) elif letter == 'm': self.Map.append(Lane.GenerateMediumWaterLane()) elif letter == 'h': self.Map.append(Lane.GenerateHardWaterLane()) elif type == 'Random': for letter in niz: if letter == 's': # safe lane self.Map.append(Lane.GenerateSafetyLane()) elif letter == 'e': # easy lane, if generated -1 -> easyWaterLane if 1 easyTrafficLane, isto vazi za ostale samo se menja tezina s,m,h... if [-1, 1][randrange(2)] == -1: self.Map.append(Lane.GenerateEasyWaterLane()) else: self.Map.append(Lane.GenerateEasyLane()) elif letter == 'm': if [-1, 1][randrange(2)] == -1: self.Map.append(Lane.GenerateMediumWaterLane()) else: self.Map.append(Lane.GenerateMediumLane()) elif letter == 'h': if [-1, 1][randrange(2)] == -1: self.Map.append(Lane.GenerateHardWaterLane()) else: self.Map.append(Lane.GenerateHardLane()) def GenerateLanes(self, type): # 6 lejnova, fja u kojoj se odlucuje tezina po levelima, moze da se menja po volji nizTezine = [] if self.Level <= 2: nizTezine.append('e') nizTezine.append('e') nizTezine.append('e') nizTezine.append('e') nizTezine.append('e') nizTezine.append('e') elif self.Level > 2 and self.Level <= 4: nizTezine.append('e') nizTezine.append('e') nizTezine.append('e') nizTezine.append('e') nizTezine.append('e') nizTezine.append('e') type = 'Random' elif self.Level > 4 and self.Level <= 6: nizTezine.append('e') nizTezine.append('e') nizTezine.append('e') nizTezine.append('m') nizTezine.append('m') nizTezine.append('m') elif self.Level > 6 and self.Level <= 8: nizTezine.append('e') nizTezine.append('e') nizTezine.append('e') nizTezine.append('m') nizTezine.append('m') nizTezine.append('m') type = 'Random' elif self.Level > 8 and self.Level <= 10: nizTezine.append('m') nizTezine.append('m') nizTezine.append('m') nizTezine.append('m') nizTezine.append('m') nizTezine.append('m') elif self.Level > 10 and self.Level <= 12: nizTezine.append('m') nizTezine.append('m') nizTezine.append('m') nizTezine.append('m') nizTezine.append('m') nizTezine.append('m') type = 'Random' elif self.Level > 12 and self.Level <= 14: nizTezine.append('m') nizTezine.append('m') nizTezine.append('m') nizTezine.append('h') nizTezine.append('h') nizTezine.append('h') elif self.Level > 12 and self.Level <= 14: nizTezine.append('m') nizTezine.append('m') nizTezine.append('m') nizTezine.append('h') nizTezine.append('h') nizTezine.append('h') type = 'Random' elif self.Level > 14 and self.Level <= 16: nizTezine.append('h') nizTezine.append('h') nizTezine.append('h') nizTezine.append('h') nizTezine.append('h') nizTezine.append('h') elif self.Level > 16: nizTezine.append('h') nizTezine.append('h') nizTezine.append('h') nizTezine.append('h') nizTezine.append('h') nizTezine.append('h') type = 'Random' shuffle(nizTezine) #permutuj niz da lejnovi budu random self.createLanes(nizTezine, type) def PokreniKisu(self): #Fja da se prikaze kisa self.Menu.PrikaziPadavinu('kisa') for lane in self.Map: if lane.laneType == Config.laneTypeWater: lane.ChangeSpeed( Config.speedChange) #brzina drveca se povecava kad je kisa elif lane.laneType == Config.laneTypeTraffic or lane.laneType == Config.laneTypeTrafficTop or lane.laneType == Config.laneTypeTrafficBottom: lane.ChangeSpeed(-Config.speedChange ) #brzina automobila se smanjuje kad je kisa def PokreniSneg(self): #Fja da se prikaze sneg self.Menu.PrikaziPadavinu('sneg') for lane in self.Map: if lane.laneType == Config.laneTypeWater: lane.ChangeSpeed(-Config.speedChange ) #brzina drveca se smanjuje kad je sneg elif lane.laneType == Config.laneTypeTraffic or lane.laneType == Config.laneTypeTrafficTop or lane.laneType == Config.laneTypeTrafficBottom: lane.ChangeSpeed(Config.speedChange ) #brzina automobila se povecava kad je sneg def ZaustaviKisu(self): #Fja da se zaustavi kisa self.Menu.SakrijPadavinu('kisa') for lane in self.Map: if lane.laneType == Config.laneTypeWater: lane.ChangeSpeed( -Config.speedChange ) #obrnuto, ako smo bili povecali brzinu drveca kad je kisa pocela, sad je smanjujemo, vracamo na default elif lane.laneType == Config.laneTypeTraffic or lane.laneType == Config.laneTypeTrafficTop or lane.laneType == Config.laneTypeTrafficBottom: lane.ChangeSpeed( Config.speedChange ) #obrnuto, ako smo bili smanjili brzinu automobila kad je kisa pocela, sad je povecavamo, vracamo na default def ZaustaviSneg(self): #Fja da se zaustavi sneg self.Menu.SakrijPadavinu('sneg') for lane in self.Map: if lane.laneType == Config.laneTypeWater: lane.ChangeSpeed( Config.speedChange ) #obrnuto, ako smo bili smanjili brzinu drveca kad je poceo sneg, sad je povecavamo, vracamo na default elif lane.laneType == Config.laneTypeTraffic or lane.laneType == Config.laneTypeTrafficTop or lane.laneType == Config.laneTypeTrafficBottom: lane.ChangeSpeed( -Config.speedChange ) #obrnuto, ako smo bili povecali brzinu automobila kad je poceo sneg, sad je smanjujemo, vracamo na default ################################################################################ #FUNKCIJE ISPOD SE KORISTE SAMO ZA MULITPLAYER ################################################################################ def HostServer(self, address, port): self.isHost = True self.host = Host(address, port) self.host.receiveCallBack.connect(self.ReceiveFromClient) self.host.start() def JoinServer(self, address, port): self.isClient = True self.client = Client(address, port) self.client.receiveCallBack.connect(self.ReceiveFromServer) self.client.start() def SendClientToReplicateObjects(self): self.host.SendToClient(Config.network_kreirajSveObjekteNaKlijentu + ":" + self.CreateInitObjectsString()) # ovo ce biti pozvano kad server primi poruku od klijenta def ReceiveFromClient(self, data): # print("Primio od klijenta: " + str(data)) if data == Config.network_clientIsReady: # kad primi ovo znaci da se klijent povezao self.TwoPlayerMode(OverNetworkGame=True) self.player2.keyBoardInputEnabled = False self.SendClientToReplicateObjects( ) #da ne generise updater svaki put kad se predje level, vec samo incijalno kad se uspostavi veza elif data == Config.network_potvrdaKlijentaDaJeNapravioSveObjekte and self.Level == 1: # klijent je potvrdio da je napravio sve objekte i sad pokrecemo igru (pravimo i pokrecemo thread koji updateuje igru) self.createThreadToUpdateGameObjects() self.startThreadForUpdatingGameObjects() elif Config.network_inputKlijentaPrefix in data and self.player2 != None: #ovo da li je igrac razlicit od None je ustvari provera da li je ziv if Config.network_inputKlijentaPrefix + "DESNO" == data: self.player2.GoRight() elif Config.network_inputKlijentaPrefix + "DOLE" == data: self.player2.GoDown() elif Config.network_inputKlijentaPrefix + "GORE" == data: self.player2.GoUp() elif Config.network_inputKlijentaPrefix + "LEVO" == data: self.player2.GoLeft() elif Config.network_ConnectionError == data: print("Klijent je otiso :(") self.ResetGameStateOnError() # ovo ce biti pozvano kad klijent primi poruku od servera def ReceiveFromServer(self, data): #print("Primio od servera: " + str(data)) if data == Config.network_serverWelcomeMsg: # znaci da smo se uspesno povezali sa serverom i inicijalizujemo gejm self.InitNetworkGame() elif Config.network_kreirajSveObjekteNaKlijentu in data: self.GenerateObjects(data.split(":")[1]) self.client.SendToServer( Config.network_potvrdaKlijentaDaJeNapravioSveObjekte) elif Config.network_updateSveObjekteNaKlijentu in data: self.UpdateObjectsPosition(data.split(":")[1]) elif Config.network_updateGameScoreAndLives in data: #ako ovde udje PAYLOAD moze da izgleda ovako: #P2L_3 #P1S_2 #P2S_4 #P1L_1 payload = data.split(":")[1] player, scoreOrLives = payload.split('_') #print(str(payload)) if "P1" in player: if "S" in player: self.updateP1Score(scoreOrLives) elif "L" in player: self.createGreenLives(int(scoreOrLives)) elif "P2" in player: if "S" in player: self.updateP2Score(scoreOrLives) elif "L" in player: self.createPinkLives(int(scoreOrLives)) elif Config.network_updateWeatherInfo in data: self.updateWeather(data.split(":")[1]) elif Config.network_ConnectionError == data: self.ResetGameStateOnError() #ovo se poziva na klijentu. def InitNetworkGame(self): self.TwoPlayerMode( OverNetworkGame=True ) #nije potrebno ovo True, al da se dzabe nebi pravio thread koji se ne koristi :D #sklanjamo sve objekte, jer ce nam server poslati sta je on generisao (velicine, pozicije, sprajtove) for go in GameObject.allGameObjects: go.RemoveFromScreen() GameObject.allGameObjects.clear() #klijent javi serveru da je spreman (spreman da primi podatke o svim objektima) self.client.SendToServer(Config.network_clientIsReady) #poziva se ako dodje do greske prilikom komunikacije sa klijentom def ResetGameStateOnError(self): self.RemoveAllGameUIObjects() self.GameOver() #poziva se samo na serveru def SendRectPositionUpdateToClient(self): self.host.SendToClient(Config.network_updateSveObjekteNaKlijentu + ":" + self.CreateUpdateObjectsString()) #ova metoda moze ici u GameObject Klasu def CreateInitObjectsString(self): objektiUString = [] for go in GameObject.allGameObjects: #saljemo podatke koji su potrebni da bi se napravili objekti na klijentu objektiUString.append( str(go.id) + "%" + go.loadedSprite + "%" + str(go.x) + "%" + str(go.y) + "%" + str(go.w) + "%" + str(go.h)) return "#".join(objektiUString) # ova metoda moze ici u GameObject Klasu def CreateUpdateObjectsString(self): objektiUString = [] for go in GameObject.allGameObjects: #saljemo podatke koji su potrebni da bi se updateovale pozicije objekata na klijentu #optimizovano, ne saljem update za sve gameObjecte vec samo one koji su u lejeru prepreke i imaju neku brzinu if go.layer == Config.layerPrepreke and go.speed != 0: objektiUString.append( str(go.id) + "%" + str(go.x) + "%" + str(go.y)) elif go.layer == Config.layerZabe or go.layer == Config.layerLilypad: #igraci i lokvanji mogu da promene sprite i zato saljem i sprite :D objektiUString.append( str(go.id) + "%" + str(go.x) + "%" + str(go.y) + "%" + str(go.loadedSprite)) # ovo je dodato ako neki od igraca umre da ga klijent skloni sa ekrana (sprite se stavi na prazan string) if self.player1 == None and self.player1RectId != -1: objektiUString.append( str(self.player1RectId) + "%" + str(0) + "%" + str(0) + "%DEAD") self.player1RectId = -1 if self.player2 == None and self.player2RectId != -1: objektiUString.append( str(self.player2RectId) + "%" + str(0) + "%" + str(0) + "%DEAD") self.player2RectId = -1 return "#".join(objektiUString) #ova funkcija se poziva na klijentu, da napravi objekte iste kao sto su na serveru. Pozove se samo na pocetku def GenerateObjects(self, data): for layer, listOfRects in Rectangle.allRectangles.items(): for rect in listOfRects: rect.RemoveFromScreen() listOfRects.clear() objs = data.split("#") Rectangle.ResetId() for obj in objs: objData = obj.split("%") r = Rectangle(float(objData[2]), float(objData[3]), int(objData[4]), int(objData[5]), objData[1], layer=objData[0], forceId=int(objData[0])) r.Show() #ova funkcija se poziva na klijentu, sluzi za updateovanje (samo X i Y kordinate) svih rectanglova na klijentu. #server ce ovo slati klijentu svaki frejm (30 puta u sekundi) def UpdateObjectsPosition(self, data): objs = data.split("#") dictObj = {} for obj in objs: objData = obj.split("%") if len(objData) == 4: dictObj[objData[0]] = (float(objData[1]), float(objData[2]), objData[3]) elif len(objData) == 3: dictObj[objData[0]] = (float(objData[1]), float(objData[2])) for go in GameObject.allGameObjects: strId = str(go.id) if strId in dictObj.keys(): go.SetPosition(dictObj[strId][0], dictObj[strId][1]) if len(dictObj[strId] ) == 3: #ako je 3 znaci da imamo i sprite poslat go.ChangeSprite(dictObj[strId][2])
class SimMoveDemo(QMainWindow): def __init__(self, brojIgraca, lvlNumber): super().__init__() oImage = QImage("images\\back") sImage = oImage.scaled(QSize(1000, 562)) # resize Image to widgets size palette = QPalette() palette.setBrush(10, QBrush(sImage)) # 10 = Windowrole self.setPalette(palette) self.pix1 = QPixmap('images\\sml') self.pix11 = QPixmap('images\\smr') self.pix12 = QPixmap('images\\lml') self.pix112 = QPixmap('images\\lmr') self.pix2 = QPixmap('images\\jasmin') self.pix22 = QPixmap('images\\pll') self.pix3 = QPixmap('images\\gl') self.srce = QPixmap('images\\heart.png') self.pix32 = QPixmap('images\\gr') self.izadji = QPixmap('images\\quit') self.pix4 = QPixmap('images\\barell') self.hitSide = False self.label2 = QLabel(self) self.label4 = QLabel(self) self.label3 = QLabel(self) self.label30 = QLabel(self) self.labelLifes1 = QLabel(self) self.labelLifes2 = QLabel(self) self.life1ispis = QLabel(self) self.life2ispis = QLabel(self) self.label1 = QLabel(self) self.label11 = QLabel(self) self.kraj = None self.labelLevel = QLabel(self) self.ispisLabel1 = QLabel(self) self.playerRez1 = QLabel(self) self.playerRez11 = QLabel(self) self.playerRez2 = QLabel(self) self.playerRez22 = QLabel(self) self.gameoverLab = QLabel(self) self.izlazIzIgre = QLabel(self) self.barrelQueue = Queue() self.barrelProcess = Process(target=generateBarrel, args=[self.barrelQueue]) self.barrels = [] self.barrelProcess.start() self.gorilaStop = Queue() self.gorilaStart = Queue() self.gorilaBug = Process(target=GorilaFreezeProcess, args=[self.gorilaStart, self.gorilaStop]) self.gorilaBug.start() self.hearts = [] self.zaustavio = False self.heart = QLabel(self) self.heart.setPixmap(self.srce) self.prvi = False self.drugi = False # da li su pobedili self.izgubioPrvi = False self.izgubioDrugi = False self.prviSprat = False self.poeniPL1 = 0 self.poeniPL2 = 0 self.trenutniNivo = lvlNumber self.ispisLabel1.setText('Level: ') self.ispisLabel1.setStyleSheet('color: blue') self.playerRez1.setText('P1: ') self.playerRez1.setStyleSheet('color: red') self.playerRez2.setText('P2: ') self.life1ispis.setText('P1 Life: ') self.life1ispis.setStyleSheet('color: red') self.life2ispis.setText('P2 Life: ') self.playerRez11.setText(str(self.poeniPL1)) self.playerRez11.setStyleSheet('color: red') self.playerRez22.setText(str(self.poeniPL2)) self.left = 400 self.top = 200 self.width = 1000 self.height = 562 self.key_notifier = KeyNotifier() if (brojIgraca == 1): self.key_notifier.key_signal.connect(self.__update_position__) # ----------------- self.brojIgracaJedan = True else: self.brojIgracaJedan = False self.key_notifier2 = KeyNotifier2() self.key_notifier.key_signal.connect(self.__update_position__) # ----------------- self.key_notifier2.key_signal2.connect(self.__update_position2__) # ----------------- self.key_notifier2.start() self.key_notifier.start() self.__init_ui__(brLevel, brojIgraca) def __init_ui__(self, brLevel, brojIgraca): self.setWindowTitle('Donkey Kong') self.setGeometry(self.left, self.top, self.width, self.height) self.label1.setPixmap(self.pix1) self.label1.setGeometry(280, 475, 57, 67) self.label2.setPixmap(self.pix2) self.label2.setGeometry(475, 0, 40, 75) self.promenioSliku = True self.label3.setPixmap(self.pix3) self.label3.setGeometry(455, 85, 70, 75) self.izlazIzIgre.setPixmap(self.izadji) self.izlazIzIgre.setGeometry(750, 50, 250, 47) self.izlazIzIgre.mousePressEvent = self.shutdown brLevel += 1 font = QtGui.QFont() font.setPointSize(20) self.labelLevel.setText(str(self.trenutniNivo)) self.labelLevel.setGeometry(110, 5, 50, 50) self.labelLevel.setFont(font) self.labelLevel.setStyleSheet('color: blue') self.ispisLabel1.setGeometry(2, -20, 100, 100) self.ispisLabel1.setFont(font) self.lives1 = 3 self.lives2 = 3 self.labelLifes1.setText(str(self.lives1)) self.labelLifes1.setGeometry(110, 15, 100, 100) self.labelLifes1.setFont(font) self.labelLifes1.setStyleSheet('color: red') self.life1ispis.setGeometry(2, 40, 150, 50) self.life1ispis.setFont(font) self.playerRez1.setGeometry(2, 40, 120, 100) self.playerRez11.setGeometry(110, 40, 100, 100) self.playerRez1.setFont(font) self.playerRez1.setStyleSheet('color: red') self.playerRez11.setFont(font) if (brojIgraca == 2): self.brojIgracaJedan = False self.playerRez2.setGeometry(2, 110, 100, 100) self.playerRez22.setGeometry(110, 110, 100, 100) self.playerRez2.setFont(font) self.playerRez2.setStyleSheet('color: green') self.playerRez22.setFont(font) self.playerRez22.setStyleSheet('color: green') self.life2ispis.setGeometry(2, 85, 120, 100) self.labelLifes2.setGeometry(110, 85, 100, 100) self.life2ispis.setFont(font) self.life2ispis.setStyleSheet('color: green') self.labelLifes2.setText(str(self.lives2)) self.labelLifes2.setStyleSheet('color: green') self.labelLifes2.setFont(font) self.label30.setPixmap(self.pix112) self.label30.setGeometry(660, 475, 57, 75) self.jasminMovement = JasminMovement() self.jasminMovement.jasminMovementSignal.connect(self.moveJasmin) self.jasminMovement.start() self.gorilaMovement = GorilaMovement() self.gorilaMovement.gorilaMovementSignal.connect(self.moveGorila) self.gorilaMovement.start() self.movingBarrels = BarrelMovement() self.movingBarrels.barrelMovementSignal.connect(self.moveBarrels) self.movingBarrels.start() self.heartsMovement = HeartsMovement() self.heartsMovement.heartsMovementSignal.connect(self.generateForce) self.heartsMovement.start() self.show() def keyPressEvent(self, event): a = event.key() self.key_notifier.add_key(a) if (self.brojIgracaJedan == False): b = event.key() self.key_notifier2.add_key(b) def keyReleaseEvent(self, event): a = event.key() self.key_notifier.rem_key(a) if (self.brojIgracaJedan == False): b = event.key() self.key_notifier2.rem_key(b) def __update_position__(self, key): rec1 = self.label1.geometry() if key == Qt.Key_Right: self.label1.setPixmap(self.pix11) elif key == Qt.Key_Left: self.label1.setPixmap(self.pix1) if key == Qt.Key_Right and rec1.x() <= 660 and (rec1.y() == 475 or (rec1.y() == 385 and rec1.x() <= 640) or (rec1.y() == 290 and rec1.x() <= 630) or (rec1.y() == 195 and rec1.x() <= 610) or (rec1.y() == 95 and rec1.x() <= 580) or (rec1.y() == 0 and rec1.x() <= 540)): self.label1.setGeometry(rec1.x() + 5, rec1.y(), rec1.width(), rec1.height()) elif key == Qt.Key_Left and rec1.x() >= 290 and (rec1.y() == 475 or (rec1.y() == 385 and rec1.x() >= 300) or (rec1.y() == 290 and rec1.x() >= 310) or (rec1.y() == 195 and rec1.x() >= 330) or (rec1.y() == 95 and rec1.x() >= 340) or (rec1.y() == 0 and rec1.x() >= 380)): self.label1.setGeometry(rec1.x() - 5, rec1.y(), rec1.width(), rec1.height()) elif key == Qt.Key_Up: if (rec1.x() >= 445 and rec1.x() <= 465 and rec1.y() > 385 and rec1.y() <= 475): self.label1.setGeometry(rec1.x(), rec1.y() - 5, rec1.width(), rec1.height()) if rec1.y() == 395: self.poeniPL1 += 1 self.playerRez11.setText(str(self.poeniPL1)) elif (rec1.x() >= 290 and rec1.x() <= 310 and rec1.y() > 290 and rec1.y() <= 385): self.label1.setGeometry(rec1.x(), rec1.y() - 5, rec1.width(), rec1.height()) if rec1.y() == 305: self.poeniPL1 += 1 self.playerRez11.setText(str(self.poeniPL1)) elif (rec1.x() >= 620 and rec1.x() <= 640 and rec1.y() > 195 and rec1.y() <= 290): self.label1.setGeometry(rec1.x(), rec1.y() - 5, rec1.width(), rec1.height()) if rec1.y() == 215: self.poeniPL1 += 1 self.playerRez11.setText(str(self.poeniPL1)) elif (rec1.x() >= 320 and rec1.x() <= 340 and rec1.y() > 95 and rec1.y() <= 195): self.label1.setGeometry(rec1.x(), rec1.y() - 5, rec1.width(), rec1.height()) if rec1.y() == 125: self.poeniPL1 += 1 self.playerRez11.setText(str(self.poeniPL1)) elif (rec1.x() >= 400 and rec1.x() <= 420 and rec1.y() > 0 and rec1.y() <= 95): self.label1.setGeometry(rec1.x(), rec1.y() - 5, rec1.width(), rec1.height()) if rec1.y() == 5: self.poeniPL1 += 1 self.playerRez11.setText(str(self.poeniPL1)) elif key == Qt.Key_Down: if (rec1.x() >= 445 and rec1.x() <= 465 and rec1.y() >= 385 and rec1.y() < 475): self.label1.setGeometry(rec1.x(), rec1.y() + 5, rec1.width(), rec1.height()) if rec1.y() == 395: self.poeniPL1 -= 1 self.playerRez11.setText(str(self.poeniPL1)) elif (rec1.x() >= 290 and rec1.x() <= 310 and rec1.y() >= 290 and rec1.y() < 385): self.label1.setGeometry(rec1.x(), rec1.y() + 5, rec1.width(), rec1.height()) if rec1.y() == 305: self.poeniPL1 -= 1 self.playerRez11.setText(str(self.poeniPL1)) elif (rec1.x() >= 620 and rec1.x() <= 640 and rec1.y() >= 195 and rec1.y() < 290): self.label1.setGeometry(rec1.x(), rec1.y() + 5, rec1.width(), rec1.height()) if rec1.y() == 215: self.poeniPL1 -= 1 self.playerRez11.setText(str(self.poeniPL1)) elif (rec1.x() >= 320 and rec1.x() <= 340 and rec1.y() >= 95 and rec1.y() < 195): self.label1.setGeometry(rec1.x(), rec1.y() + 5, rec1.width(), rec1.height()) if rec1.y() == 125: self.poeniPL1 -= 1 self.playerRez11.setText(str(self.poeniPL1)) elif (rec1.x() >= 400 and rec1.x() <= 420 and rec1.y() >= 0 and rec1.y() < 95): self.label1.setGeometry(rec1.x(), rec1.y() + 5, rec1.width(), rec1.height()) if rec1.y() == 5: self.poeniPL1 -= 1 self.playerRez11.setText(str(self.poeniPL1)) def __update_position2__(self, key): rec2 = self.label30.geometry() if key == Qt.Key_D: self.label30.setPixmap(self.pix112) elif key == Qt.Key_A: self.label30.setPixmap(self.pix12) if key == Qt.Key_D and rec2.x() <= 660 and (rec2.y() == 475 or (rec2.y() == 380 and rec2.x() <= 640) or (rec2.y() == 285 and rec2.x() <= 630) or (rec2.y() == 185 and rec2.x() <= 610) or (rec2.y() == 95 and rec2.x() <= 580) or (rec2.y() == 0 and rec2.x() <= 540)): self.label30.setGeometry(rec2.x() + 5, rec2.y(), rec2.width(), rec2.height()) elif key == Qt.Key_A and rec2.x() >= 280 and (rec2.y() == 475 or (rec2.y() == 380 and rec2.x() >= 300) or (rec2.y() == 285 and rec2.x() >= 310) or (rec2.y() == 185 and rec2.x() >= 330) or (rec2.y() == 95 and rec2.x() >= 340) or (rec2.y() == 0 and rec2.x() >= 380)): self.label30.setGeometry(rec2.x() - 5, rec2.y(), rec2.width(), rec2.height()) elif key == Qt.Key_W: if (rec2.x() >= 445 and rec2.x() <= 465 and rec2.y() > 380 and rec2.y() <= 475): self.label30.setGeometry(rec2.x(), rec2.y() - 5, rec2.width(), rec2.height()) if rec2.y() == 395: self.poeniPL2 += 1 self.playerRez22.setText(str(self.poeniPL2)) elif (rec2.x() >= 290 and rec2.x() <= 310 and rec2.y() > 285 and rec2.y() <= 380): self.label30.setGeometry(rec2.x(), rec2.y() - 5, rec2.width(), rec2.height()) if rec2.y() == 305: self.poeniPL2 += 1 self.playerRez22.setText(str(self.poeniPL2)) elif (rec2.x() >= 620 and rec2.x() <= 640 and rec2.y() > 185 and rec2.y() <= 285): self.label30.setGeometry(rec2.x(), rec2.y() - 5, rec2.width(), rec2.height()) if rec2.y() == 215: self.poeniPL2 += 1 self.playerRez22.setText(str(self.poeniPL2)) elif (rec2.x() >= 320 and rec2.x() <= 340 and rec2.y() > 95 and rec2.y() <= 185): self.label30.setGeometry(rec2.x(), rec2.y() - 5, rec2.width(), rec2.height()) if rec2.y() == 125: self.poeniPL2 += 1 self.playerRez22.setText(str(self.poeniPL2)) elif (rec2.x() >= 400 and rec2.x() <= 420 and rec2.y() > 0 and rec2.y() <= 95): self.label30.setGeometry(rec2.x(), rec2.y() - 5, rec2.width(), rec2.height()) if rec2.y() == -5: self.poeniPL2 += 1 self.playerRez22.setText(str(self.poeniPL2)) elif key == Qt.Key_S: if (rec2.x() >= 445 and rec2.x() <= 465 and rec2.y() >= 380 and rec2.y() < 475): self.label30.setGeometry(rec2.x(), rec2.y() + 5, rec2.width(), rec2.height()) if rec2.y() == 395: self.poeniPL2 -= 1 self.playerRez22.setText(str(self.poeniPL2)) elif (rec2.x() >= 290 and rec2.x() <= 310 and rec2.y() >= 285 and rec2.y() < 380): self.label30.setGeometry(rec2.x(), rec2.y() + 5, rec2.width(), rec2.height()) if rec2.y() == 305: self.poeniPL2 -= 1 self.playerRez22.setText(str(self.poeniPL2)) elif (rec2.x() >= 620 and rec2.x() <= 640 and rec2.y() >= 185 and rec2.y() < 285): self.label30.setGeometry(rec2.x(), rec2.y() + 5, rec2.width(), rec2.height()) if rec2.y() == 215: self.poeniPL2 -= 1 self.playerRez22.setText(str(self.poeniPL2)) elif (rec2.x() >= 320 and rec2.x() <= 340 and rec2.y() >= 95 and rec2.y() < 185): self.label30.setGeometry(rec2.x(), rec2.y() + 5, rec2.width(), rec2.height()) if rec2.y() == 125: self.poeniPL2 -= 1 self.playerRez22.setText(str(self.poeniPL2)) elif (rec2.x() >= 400 and rec2.x() <= 420 and rec2.y() >= 0 and rec2.y() < 95): self.label30.setGeometry(rec2.x(), rec2.y() + 5, rec2.width(), rec2.height()) if rec2.y() == -5: self.poeniPL2 -= 1 self.playerRez22.setText(str(self.poeniPL2)) def moveJasmin(self): self.timerP1 = QTimer(self) self.timerP1.start(2000) self.timerP1.timeout.connect(self.menjajSliku) if isHit(self.label2, self.label1) or isHit(self.label2, self.label30): if self.brojIgracaJedan: self.label1.setGeometry(280, 475, 75, 75) self.lives1 = 3 self.trenutniNivo += 1 self.labelLifes1.setText(str(self.lives1)) self.labelLevel.setText(str(self.trenutniNivo)) else: if isHit(self.label2, self.label1) and isHit(self.label2, self.label30): #self.prvi and self.drugi: self.trenutniNivo += 1 self.labelLevel.setText(str(self.trenutniNivo)) self.label1.setGeometry(280, 475, 75, 75) self.label30.setGeometry(660, 475, 75, 75) self.label30.show() self.label1.show() self.drugi = False self.prvi = False elif isHit(self.label2, self.label1): self.label1.hide() self.prvi = True self.lives1 = 3 self.labelLifes1.setText(str(self.lives1)) elif isHit(self.label2, self.label30): self.label30.hide() self.drugi = True self.lives2 = 3 self.labelLifes2.setText(str(self.lives2)) if self.lives1 == 0: self.label1.setGeometry(200, 475, 75, 75) self.label1.hide() elif self.lives2 == 0: self.label30.setGeometry(200, 475, 75, 75) self.label30.hide() if self.lives1 == 0 and self.drugi: self.drugi = False self.trenutniNivo += 1 self.label30.setGeometry(660, 475, 75, 75) self.labelLevel.setText(str(self.trenutniNivo)) self.label30.show() self.izgubioPrvi = True if self.lives2 == 0 and self.prvi: self.prvi = False self.label1.setGeometry(280, 475, 75, 75) self.trenutniNivo += 1 self.labelLevel.setText(str(self.trenutniNivo)) self.label1.show() self.izgubioDrugi = True if self.lives1 <= 0 and self.lives2 <= 0: if self.izgubioPrvi: self.kraj = GameOver(2, self.poeniPL2) else: self.kraj = GameOver(1, self.poeniPL1) self.close() def menjajSliku(self): if self.promenioSliku: self.label2.setPixmap(self.pix22) self.promenioSliku = False else: self.label2.setPixmap(self.pix2) self.promenioSliku = True def moveGorila(self): rec2 = self.label3.geometry() if (rec2.x() >= 580): self.hitSide = True elif (rec2.x() <= 320): self.hitSide = False a = randint(0, 100) if a % 15 == 0: self.hitSide = True b = randint(0, 100) if b % 13 == 0: self.hitSide = False if (self.hitSide): self.label3.setGeometry(rec2.x() - 10, rec2.y(), rec2.width(), rec2.height()) self.label3.setPixmap(self.pix3) else: self.label3.setGeometry(rec2.x() + 10, rec2.y(), rec2.width(), rec2.height()) self.label3.setPixmap(self.pix32) if isHit(self.label1, self.label3): if self.lives1 > 0: self.lives1 -= 1 self.labelLifes1.setText(str(self.lives1)) if self.lives1 == 0: if self.brojIgracaJedan: self.kraj = GameOver(1, self.poeniPL1) self.close() else: self.label1.setGeometry(200, 475, 75, 75) self.label1.hide() if self.izgubioDrugi: self.kraj = GameOver(1, self.poeniPL1) self.close() else: self.izgubioPrvi = True if isHit(self.label30, self.label3): if self.lives2 > 0: self.lives2 -= 1 self.labelLifes2.setText(str(self.lives2)) if self.lives2 == 0: self.label30.setGeometry(200, 475, 75, 75) self.label30.hide() if self.izgubioPrvi: self.kraj = GameOver(2, self.poeniPL2) self.close() else: self.izgubioDrugi = True if not self.zaustavio: self.gorilaStop.put(1) self.zaustavio = True return else: if self.gorilaStart.empty(): return else: a = self.gorilaStart.get() self.zaustavio = False def moveBarrels(self): rec = self.label3.geometry() a = randint(0, 100) if a % 12 == 0: barrel = QLabel(self) self.barrels.append(barrel) self.barrels[len(self.barrels) - 1].setPixmap(self.pix4) self.barrels[len(self.barrels) - 1].setGeometry(rec.x(), rec.y(), 40, 40) self.barrels[len(self.barrels) - 1].show() for barrel in self.barrels: recb = barrel.geometry() barrel.setGeometry(recb.x(), recb.y() + 10, recb.width(), recb.height()) if recb.y() > 600: barrel.hide() self.barrels.remove(barrel) if isHit(barrel, self.label1): if self.lives1 > 0: self.lives1 -= 1 self.labelLifes1.setText(str(self.lives1)) barrel.hide() self.barrels.remove(barrel) if self.lives1 == 0: if self.brojIgracaJedan: self.kraj = GameOver(1, self.poeniPL1) self.close() else: self.label1.setGeometry(200, 475, 75, 75) self.label1.hide() if self.izgubioDrugi: self.kraj = GameOver(1, self.poeniPL1) self.close() else: self.izgubioPrvi = True if isHit(barrel, self.label30): if self.lives2 > 0: self.lives2 -= 1 self.labelLifes2.setText(str(self.lives2)) barrel.hide() self.barrels.remove(barrel) if self.lives2 == 0: self.label30.setGeometry(200, 475, 75, 75) self.label30.hide() if self.izgubioPrvi: self.kraj = GameOver(2, self.poeniPL2) self.close() else: self.izgubioDrugi = True def generateForce(self): #a = randint(0, 100) #if a % 73 == 0: #heart = QLabel(self) #self.hearts.append(heart) #self.hearts[len(self.hearts) - 1].setPixmap(self.srce) #self.hearts[len(self.hearts) - 1].setGeometry(randint(300, 600), randint(440, 475), 40, 40) #self.hearts[len(self.hearts) - 1].show() self.heart.setGeometry(randint(300, 600), 310, 40, 40) self.heart.show() self.timerP3 = QTimer(self) self.timerP3.start(7000) self.timerP3.timeout.connect(self.sakrij) #for heart in self.hearts: if isHit(self.heart, self.label1): self.lives1 += randint(-2, 2) self.labelLifes1.setText(str(self.lives1)) self.heart.hide() #self.hearts.remove(heart) if self.lives1 <= 0: if self.brojIgracaJedan: self.kraj = GameOver(1, self.poeniPL1) self.close() else: self.label1.setGeometry(200, 40, 75, 75) self.label1.hide() self.lives1 = 0 self.labelLifes1.setText(str(self.lives1)) if self.izgubioDrugi: self.kraj = GameOver(1, self.poeniPL1) self.close() else: self.izgubioPrvi = True if isHit(self.heart, self.label30): self.lives2 += randint(-2, 2) self.labelLifes2.setText(str(self.lives2)) self.heart.hide() #self.hearts.remove(heart) if self.lives2 <= 0: self.lives2 = 0 self.labelLifes2.setText(str(self.lives2)) self.label30.setGeometry(200, 40, 75, 75) self.label30.hide() if self.izgubioPrvi: self.kraj = GameOver(2, self.poeniPL2) self.close() else: self.izgubioDrugi = True def sakrij(self): self.heart.hide() def closeEvent(self, event): self.jasminMovement.die() self.gorilaMovement.die() self.barrelProcess.terminate() self.heartsMovement.die() self.movingBarrels.die() self.gorilaBug.terminate() self.key_notifier.die() self.key_notifier2.die() def shutdown(self, event): self.barrelProcess.terminate() self.gorilaBug.terminate() self.close()
def __init__(self, parent, width, height): super().__init__(parent) self.connects() # self.omega() text = '' bin = self.s.recv(2048) text += str(bin, 'utf-8') print(text) if text == "1": Server.second_player_is_here = False # print("labela.") elif text == "2": Server.second_player_is_here = True self.label = QLabel() self.pixmap = QPixmap('Images/img2.png') self.label.setPixmap(self.pixmap) self.label.resize(600, 500) self.addWidget(self.label) self.asteroid_position_counter = 0 if Server.second_player_is_here == False: self.width = width self.height = height self.setSceneRect(0, 0, self.width - 2, self.height - 2) self.sceneParent = parent self.queue = mp.Queue() self.queueForPlayer2 = mp.Queue() self.label2 = QLabel("Waiting for other clients to connect.") self.label2.resize(400, 30) self.label2.move(165, 120) self.label2.setStyleSheet( "font: 12pt; color: #f03a54; font:italic; background-color: transparent; " ) self.addWidget(self.label2) # self.label2.hide() self.ply1 = False # self.queue.put('go') self.checkPlayers = QPushButton("Search opponents") self.checkPlayers.setStyleSheet( "QPushButton{" "color: white; background-color: transparent; font:bold; border-style: outset; border-width: 2px; border-color: white" "}" "QPushButton:hover{" "background-color: #C14242" "}") self.checkPlayers.resize(150, 50) self.checkPlayers.move(218, 260) self.addWidget(self.checkPlayers) self.key_notifier = KeyNotifier() self.key_notifier.key_signal.connect(self.__update_position__) self.key_notifier.start() self.key_notifier2 = KeyNotifier() self.key_notifier2.key_signal.connect(self.__update_position__2) self.key_notifier2.start() # self.omega("pera") elif Server.second_player_is_here == True: self.width = width self.height = height self.setSceneRect(0, 0, self.width - 2, self.height - 2) self.sceneParent = parent self.queue = mp.Queue() self.queueToSend = mp.Queue() self.label2 = QLabel("Waiting for other clients to connect.") self.label2.resize(400, 30) self.label2.move(165, 120) self.label2.setStyleSheet( "font: 12pt; color: #f03a54; font:italic; background-color: transparent; " ) self.addWidget(self.label2) self.ply1 = False self.checkPlayers = QPushButton("Search opponents") self.checkPlayers.setStyleSheet( "QPushButton{" "color: white; background-color: transparent; font:bold; border-style: outset; border-width: 2px; border-color: white" "}" "QPushButton:hover{" "background-color: #C14242" "}") self.checkPlayers.resize(150, 50) self.checkPlayers.move(218, 260) self.addWidget(self.checkPlayers) self.key_notifier = KeyNotifier() self.key_notifier.key_signal.connect(self.__update_position__) self.key_notifier.start() self.key_notifier2 = KeyNotifier() self.key_notifier2.key_signal.connect(self.__update_position__2) self.key_notifier2.start()
class Window(QWidget): def __init__(self, qu1: Queue, qu2: Queue, qu3: Queue): super().__init__() self.q = qu1 self.q2 = qu2 self.q3 = qu3 self.init_ui() self.showFullScreen() def init_ui(self): self.screen = QDesktopWidget().screenGeometry() self.half_width = (self.screen.width()) / 2 self.setFixedSize(self.screen.width(), self.screen.height() - 70) self.move(0, 0) self.game_mode = 1 # indikator da li se igra sa jednim ili dva igraca self.started = False self.paused = False self.left1 = False self.right1 = False self.left2 = False self.right2 = False self.timer = QTimer() self.timer.timeout.connect(self.tick) self.setWindowTitle('Breakout') self.main_menu = QWidget(self) self.game_widget = QWidget(self) self.game_widget.setMouseTracking(True) self.mouse_x = None self.key_notifier = KeyNotifier() self.key_notifier.key_signal.connect(self.__update_position__) self.key_notifier.start() o_image = QImage(os.path.join('images', 'space.jpg')) s_image = o_image.scaled( QSize(self.screen.width(), self.screen.height())) # resize Image to widgets size palette = QPalette() palette.setBrush(10, QBrush(s_image)) # 10 = Windowrole self.setPalette(palette) self.game = 0 self.painter = QPainter() self.stacked = QStackedLayout(self) self.stacked.addWidget(self.game_widget) self.set_main_menu() self.stacked.setCurrentWidget(self.main_menu) def start1(self): self.game = GameOnePlayer(Size(self.width(), self.height()), self.q2, self.q3) self.left1 = self.right1 = False self.change_current_widget(self.game_widget) self.started = True #self.doAction() self.timer.start(12) def start2(self): self.game = GameTwoPlayers(Size(self.width(), self.height()), self.q2, self.q3) self.left1 = self.right1 = False self.left2 = self.right2 = False self.change_current_widget(self.game_widget) self.started = True self.doAction() self.timer.start(12) def restart(self): if self.game_mode == 1: reply = QMessageBox.question( self, 'Play again', 'Your score: %s.\nDo you want to play again?' % self.game.player.score, QMessageBox.Yes | QMessageBox.No) else: reply = QMessageBox.question( self, 'Play again', 'Player 1 score: %s.\nPlayer 2 score: %s.\nDo you want to play again?' % (self.game.player1.score, self.game.player2.score), QMessageBox.Yes | QMessageBox.No) if reply == QMessageBox.Yes: self.change_current_widget(self.main_menu) else: self.quit() def change_current_widget(self, widget): self.stacked.setCurrentWidget(widget) self.update() def listen(self): while True: num = self.q.get() print(num) self.game.get_deus(num, self.half_width) def doAction(self): self.q.put('go') t = Thread(target=self.listen) t.start() def tick(self): if self.game.game_over: self.restart() self.timer.stop() if self.game.won: self.notify_win() self.timer.stop() if self.game_mode == 1: turn_rate = 1 if self.right1 else -1 if self.left1 else 0 self.game.tick(turn_rate) else: turn_rate1 = 1 if self.right1 else -1 if self.left1 else 0 turn_rate2 = 1 if self.right2 else -1 if self.left2 else 0 self.game.tick(turn_rate1, turn_rate2) self.repaint() def notify_win(self): if self.game_mode == 1: QMessageBox.information( self, 'Win', 'You win. Your score: %s' % self.game.player.score) else: if self.game.player1.score > self.game.player2.score: QMessageBox.information( self, 'Win', 'Player 1 score: %s\nPlayer 2 score: %s\nCongratulations to player 1!' % (self.game.player1.score, self.game.player2.score)) elif self.game.player1.score < self.game.player2.score: QMessageBox.information( self, 'Win', 'Player 1 score: %s\nPlayer 2 score: %s\nCongratulations to player 2!' % (self.game.player1.score, self.game.player2.score)) else: QMessageBox.information( self, 'Win', 'Player 1 score: %s\nPlayer 2 score: %s\nCongratulations to both players!' % (self.game.player1.score, self.game.player2.score)) self.started = False self.change_current_widget(self.main_menu) def quit(self): os._exit(1) def set_main_menu(self): v_box = QVBoxLayout(self.main_menu) self.add_button('One Player Game', self.start1, v_box) self.add_button('Two Player Game', self.start2, v_box) self.add_button('Quit', self.quit, v_box) v_box.setAlignment(Qt.AlignCenter) self.stacked.addWidget(self.main_menu) #def mousePressEvent(self, event): #self.game.release_ball() def keyPressEvent(self, event): """ SPACE -> release ball ESC -> pause P -> pause/continue Q -> quit One player game -> moving on arrows Two player game -> moving on ASDW and arrows """ key = event.key() self.key_notifier.add_key(event.key()) if self.game_mode == 1: self.left1 = key == Qt.Key_Left self.right1 = key == Qt.Key_Right else: self.left1 = key == Qt.Key_A self.right1 = key == Qt.Key_D self.left2 = key == Qt.Key_Left self.right2 = key == Qt.Key_Right if key == Qt.Key_Space: self.game.release_ball() if key == Qt.Key_Escape: self.timer.stop() self.started = False self.change_current_widget(self.main_menu) if key == Qt.Key_P: self.paused = not self.paused if self.paused: self.timer.stop() else: self.timer.start() if key == Qt.Key_Q: self.quit() def keyReleaseEvent(self, event): key = event.key() self.key_notifier.rem_key(event.key()) if self.game_mode == 1: if key == Qt.Key_Left: self.left1 = False elif key == Qt.Key_Right: self.right1 = False else: if key == Qt.Key_A: self.left1 = False elif key == Qt.Key_D: self.right1 = False elif key == Qt.Key_Left: self.left2 = False elif key == Qt.Key_Right: self.right2 = False def __update_position__(self, key): self.game.update_moving_objects(key) def paintEvent(self, event): self.painter.begin(self) self.draw() self.painter.end() def draw(self): """ Function draws all the objects inside game window """ self.painter.setRenderHint(self.painter.Antialiasing) self.painter.setFont(QFont('Times New Roman', 20)) self.painter.setPen(QColor('silver')) if not self.started: return game = self.game life_img = QImage(os.path.join('images', 'lifebonus.png')).scaled( QSize(30, 30)) # resize Image to widgets size draw_x = 60 draw_y = 30 if self.game.__class__ == GameOnePlayer: self.game_mode = 1 self.painter.drawText( 0, 20, 'Player score: %s' % str(self.game.player.score)) for _ in range(self.game.player.lives): self.painter.drawImage(draw_x, draw_y, life_img) draw_x -= life_img.width() else: self.game_mode = 2 self.painter.drawText( 0, 20, 'Player 1 score: %s' % str(self.game.player1.score)) self.painter.drawText( self.screen.width() - 250, 20, 'Player 2 score: %s' % str(self.game.player2.score)) draw_x = (self.screen.width()) / 2 + 20 draw_y = 0 for _ in range(self.game.player1.lives): self.painter.drawImage(draw_x, draw_y, life_img) draw_x -= life_img.width() self.painter.drawLine(game.frame.left, game.border_line, game.frame.right, game.border_line) if self.game.game_over: return self.draw_game_objects() def draw_game_objects(self): """ Function draw all the objects in the game """ for obj in self.game.get_objects(): self.painter.drawImage( QRectF(*obj.location, obj.frame.width, obj.frame.height), QImage(obj.get_image())) @staticmethod def add_button(text, callback, layout, alignment=Qt.AlignCenter): button = QPushButton(text) button.setFixedSize(400, 50) button.pressed.connect(callback) button.setStyleSheet('QPushButton {' 'font-size: 20px;' 'background-color: transparent;' 'color: rgb(0, 0, 0);' '}' 'QPushButton:focus {' 'opacity: 0.5;' 'background-color: rgba(179, 179, 255,0.3);' '}') button.setAutoDefault(True) layout.addWidget(button, alignment=alignment) return button
class NetworkScene(QGraphicsScene): def __init__(self, parent, width, height): super().__init__(parent) self.connects() # self.omega() text = '' bin = self.s.recv(2048) text += str(bin, 'utf-8') print(text) if text == "1": Server.second_player_is_here = False # print("labela.") elif text == "2": Server.second_player_is_here = True self.label = QLabel() self.pixmap = QPixmap('Images/img2.png') self.label.setPixmap(self.pixmap) self.label.resize(600, 500) self.addWidget(self.label) self.asteroid_position_counter = 0 if Server.second_player_is_here == False: self.width = width self.height = height self.setSceneRect(0, 0, self.width - 2, self.height - 2) self.sceneParent = parent self.queue = mp.Queue() self.queueForPlayer2 = mp.Queue() self.label2 = QLabel("Waiting for other clients to connect.") self.label2.resize(400, 30) self.label2.move(165, 120) self.label2.setStyleSheet( "font: 12pt; color: #f03a54; font:italic; background-color: transparent; " ) self.addWidget(self.label2) # self.label2.hide() self.ply1 = False # self.queue.put('go') self.checkPlayers = QPushButton("Search opponents") self.checkPlayers.setStyleSheet( "QPushButton{" "color: white; background-color: transparent; font:bold; border-style: outset; border-width: 2px; border-color: white" "}" "QPushButton:hover{" "background-color: #C14242" "}") self.checkPlayers.resize(150, 50) self.checkPlayers.move(218, 260) self.addWidget(self.checkPlayers) self.key_notifier = KeyNotifier() self.key_notifier.key_signal.connect(self.__update_position__) self.key_notifier.start() self.key_notifier2 = KeyNotifier() self.key_notifier2.key_signal.connect(self.__update_position__2) self.key_notifier2.start() # self.omega("pera") elif Server.second_player_is_here == True: self.width = width self.height = height self.setSceneRect(0, 0, self.width - 2, self.height - 2) self.sceneParent = parent self.queue = mp.Queue() self.queueToSend = mp.Queue() self.label2 = QLabel("Waiting for other clients to connect.") self.label2.resize(400, 30) self.label2.move(165, 120) self.label2.setStyleSheet( "font: 12pt; color: #f03a54; font:italic; background-color: transparent; " ) self.addWidget(self.label2) self.ply1 = False self.checkPlayers = QPushButton("Search opponents") self.checkPlayers.setStyleSheet( "QPushButton{" "color: white; background-color: transparent; font:bold; border-style: outset; border-width: 2px; border-color: white" "}" "QPushButton:hover{" "background-color: #C14242" "}") self.checkPlayers.resize(150, 50) self.checkPlayers.move(218, 260) self.addWidget(self.checkPlayers) self.key_notifier = KeyNotifier() self.key_notifier.key_signal.connect(self.__update_position__) self.key_notifier.start() self.key_notifier2 = KeyNotifier() self.key_notifier2.key_signal.connect(self.__update_position__2) self.key_notifier2.start() # self.omega("player2") def connects(self): self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.s.connect((HOST, PORT)) def omega(self, mssg): # self.s.setblocking(0) text2send = '1' self.s.sendall(text2send.encode('utf8')) def alfa(self): if Server.second_player_is_here == False: while True: text = '' bin = self.s.recv(2048) text += str(bin, 'utf-8') print(text) if text == "go": print("labela.") self.createAsteroids() # pocetno kreiranje asteroida self.label2.hide() self.checkPlayers.hide() self.start_new_game() tt = Thread(target=self.recevee) tt.daemon = True tt.start() self.timer = QBasicTimer() self.timer.start(2000, self) break elif Server.second_player_is_here == True: while True: text = '' bin = self.s.recv(2048) text += str(bin, 'utf-8') print(text) if text == "go": print("labela.") self.createAsteroids() # pocetno kreiranje asteroida self.label2.hide() self.checkPlayers.hide() self.start_new_game() tt = Thread(target=self.recevee) tt.daemon = True tt.start() self.timer = QBasicTimer() self.timer.start(2000, self) break if Server.second_player_is_here == False: tt3 = Thread(target=self.prnt) tt3.daemon = True tt3.start() tt33 = Thread(target=self.prntCheck) tt33.daemon = True tt33.start() elif Server.second_player_is_here == True: tt4 = Thread(target=self.prnt2) tt4.daemon = True tt4.start() tt44 = Thread(target=self.prntCheck2) tt44.daemon = True tt44.start() def start_new_game(self): self.set_up_scores_labels() if Server.second_player_is_here == False: self.rocketnumber1 = NetworkSpaceShuttle(self.width, self.height, self, 1) self.rocketnumber1.resize( 60, 50 ) # slika je 50x50 ali se glupo okrece tako da je bolje ovako da bi se uvek videla cela self.rocketnumber1.setStyleSheet("background:transparent") self.addWidget(self.rocketnumber1) self.rocketnumber2 = NetworkSpaceShuttle(self.width, self.height, self, 2) self.rocketnumber2.resize( 60, 50 ) # slika je 50x50 ali se glupo okrece tako da je bolje ovako da bi se uvek videla cela self.rocketnumber2.setStyleSheet("background:transparent") self.addWidget(self.rocketnumber2) self.rocketnumber3 = NetworkSpaceShuttle(self.width, self.height, self, 3) self.rocketnumber3.resize( 60, 50 ) # slika je 50x50 ali se glupo okrece tako da je bolje ovako da bi se uvek videla cela self.rocketnumber3.setStyleSheet("background:transparent") self.addWidget(self.rocketnumber3) self.rocketnumber4 = NetworkSpaceShuttle(self.width, self.height, self, 4) self.rocketnumber4.resize( 60, 50 ) # slika je 50x50 ali se glupo okrece tako da je bolje ovako da bi se uvek videla cela self.rocketnumber4.setStyleSheet("background:transparent") self.addWidget(self.rocketnumber4) elif Server.second_player_is_here == True: self.rocketnumber1 = NetworkSpaceShuttle(self.width, self.height, self, 1) self.rocketnumber1.resize( 60, 50 ) # slika je 50x50 ali se glupo okrece tako da je bolje ovako da bi se uvek videla cela self.rocketnumber1.setStyleSheet("background:transparent") self.addWidget(self.rocketnumber1) self.rocketnumber2 = NetworkSpaceShuttle(self.width, self.height, self, 2) self.rocketnumber2.resize( 60, 50 ) # slika je 50x50 ali se glupo okrece tako da je bolje ovako da bi se uvek videla cela self.rocketnumber2.setStyleSheet("background:transparent") self.addWidget(self.rocketnumber2) self.rocketnumber3 = NetworkSpaceShuttle(self.width, self.height, self, 3) self.rocketnumber3.resize( 60, 50 ) # slika je 50x50 ali se glupo okrece tako da je bolje ovako da bi se uvek videla cela self.rocketnumber3.setStyleSheet("background:transparent") self.addWidget(self.rocketnumber3) self.rocketnumber4 = NetworkSpaceShuttle(self.width, self.height, self, 4) self.rocketnumber4.resize( 60, 50 ) # slika je 50x50 ali se glupo okrece tako da je bolje ovako da bi se uvek videla cela self.rocketnumber4.setStyleSheet("background:transparent") self.addWidget(self.rocketnumber4) def keyPressEvent(self, event): self.key_notifier.add_key(event.key()) self.key_notifier2.add_key(event.key()) def keyReleaseEvent(self, event): self.key_notifier.rem_key(event.key()) self.key_notifier2.rem_key(event.key()) def __update_position__(self, key): if Server.second_player_is_here == False: # prebaciti dole ovo da ima u oba ifaa if key == Qt.Key_Up and Server.player1Lives > 0: # self.rocketnumber1.upRocket1.emit() self.ply1 = True self.queue.put(111) elif key == Qt.Key_Right and Server.player1Lives > 0: # self.rocketnumber1.rightRocket1.emit() self.ply1 = True self.queue.put(222) elif key == Qt.Key_Left and Server.player1Lives > 0: # self.rocketnumber1.leftRocket1.emit() self.ply1 = True self.queue.put(333) elif key == Qt.Key_Space and Server.player1Lives > 0: # self.rocketnumber1.fireRocket1.emit() self.ply1 = True self.queue.put(444) elif Server.second_player_is_here == True: # tacnije tipa ovde ide if ket == up que.put(1111), if key == down que.put(2222) i onda provere i oba queue dole if key == Qt.Key_W and Server.player3Lives > 0: # dodata logika da moze da se pomera samo ako je idalje ziva ta raketa # self.rocketnumber2.upRocket2.emit() self.queueToSend.put(555) elif key == Qt.Key_A and Server.player3Lives > 0: # self.rocketnumber2.leftRocket2.emit() self.queueToSend.put(777) elif key == Qt.Key_D and Server.player3Lives > 0: # self.rocketnumber2.rightRocket2.emit() self.queueToSend.put(666) elif key == Qt.Key_S and Server.player3Lives > 0: # self.rocketnumber2.fireRocket2.emit() self.queueToSend.put(888) def __update_position__2(self, key): if Server.second_player_is_here == False: # prebaciti dole ovo da ima u oba ifaa if key == Qt.Key_W and Server.player2Lives > 0: # dodata logika da moze da se pomera samo ako je idalje ziva ta raketa # self.rocketnumber2.upRocket2.emit() self.queue.put(1111) elif key == Qt.Key_A and Server.player2Lives > 0: # self.rocketnumber2.leftRocket2.emit() self.queue.put(2222) elif key == Qt.Key_D and Server.player2Lives > 0: # self.rocketnumber2.rightRocket2.emit() self.queue.put(3333) elif key == Qt.Key_S and Server.player2Lives > 0: # self.rocketnumber2.fireRocket2.emit() self.queue.put(4444) elif Server.second_player_is_here == True: # tacnije tipa ovde ide if ket == up que.put(1111), if key == down que.put(2222) i onda provere i oba queue dole if key == Qt.Key_Up and Server.player4Lives > 0: # self.rocketnumber1.upRocket1.emit() # self.ply1 = True self.queueToSend.put(5555) elif key == Qt.Key_Right and Server.player4Lives > 0: # self.rocketnumber1.rightRocket1.emit() # self.ply1 = True self.queueToSend.put(6666) elif key == Qt.Key_Left and Server.player4Lives > 0: # self.rocketnumber1.leftRocket1.emit() # self.ply1 = True self.queueToSend.put(7777) elif key == Qt.Key_Space and Server.player4Lives > 0: # self.rocketnumber1.fireRocket1.emit() # self.ply1 = True self.queueToSend.put(8888) def prnt(self): #send data from client1 to server while True: while not self.queue.empty(): val = self.queue.get() val_str = val.__str__() self.s.sendall(val_str.encode('utf8')) def prnt2(self): while True: while not self.queueToSend.empty(): vals = self.queueToSend.get() val_str = vals.__str__() self.s.sendall(val_str.encode('utf8')) def prntCheck( self ): #recv data from client1 from server and read them from queue while True: while not self.queueForPlayer2.empty(): vals = self.queueForPlayer2.get() val_str = vals.__str__() if val_str == "555": self.rocketnumber3.upRocket3.emit( ) # napraviti signale i za raketu 3 i za raketu 4 elif val_str == "666": self.rocketnumber3.rightRocket3.emit() elif val_str == "777": self.rocketnumber3.leftRocket3.emit() elif val_str == "888": self.rocketnumber3.fireRocket3.emit() elif val_str == "111": self.rocketnumber1.upRocket1.emit() elif val_str == "222": self.rocketnumber1.rightRocket1.emit() elif val_str == "333": self.rocketnumber1.leftRocket1.emit() elif val_str == "444": self.rocketnumber1.fireRocket1.emit() if val_str == "1111": self.rocketnumber2.upRocket2.emit() elif val_str == "2222": self.rocketnumber2.leftRocket2.emit() elif val_str == "3333": self.rocketnumber2.rightRocket2.emit() elif val_str == "4444": self.rocketnumber2.fireRocket2.emit() elif val_str == "5555": self.rocketnumber4.upRocket4.emit() elif val_str == "6666": self.rocketnumber4.rightRocket4.emit() elif val_str == "7777": self.rocketnumber4.leftRocket4.emit() elif val_str == "8888": self.rocketnumber4.fireRocket4.emit() def prntCheck2(self): while True: while not self.queue.empty(): val = self.queue.get() val_str = val.__str__() if val_str == "111": self.rocketnumber1.upRocket1.emit() elif val_str == "222": self.rocketnumber1.rightRocket1.emit() elif val_str == "333": self.rocketnumber1.leftRocket1.emit() elif val_str == "444": self.rocketnumber1.fireRocket1.emit() elif val_str == "555": self.rocketnumber3.upRocket3.emit() elif val_str == "666": self.rocketnumber3.rightRocket3.emit() elif val_str == "777": self.rocketnumber3.leftRocket3.emit() elif val_str == "888": self.rocketnumber3.fireRocket3.emit() if val_str == "1111": self.rocketnumber2.upRocket2.emit() elif val_str == "2222": self.rocketnumber2.leftRocket2.emit() elif val_str == "3333": self.rocketnumber2.rightRocket2.emit() elif val_str == "4444": self.rocketnumber2.fireRocket2.emit() elif val_str == "5555": self.rocketnumber4.upRocket4.emit() elif val_str == "6666": self.rocketnumber4.rightRocket4.emit() elif val_str == "7777": self.rocketnumber4.leftRocket4.emit() elif val_str == "8888": self.rocketnumber4.fireRocket4.emit() def timerEvent(self, a0: 'QTimerEvent'): if Server.bonus_time < 15: Server.bonus_time = Server.bonus_time + 1 elif Server.bonus_time == 15: Server.bonus_x_coordinate = 150 + Server.level + self.asteroid_position_counter Server.bonus_y_coordinate = 250 + Server.level + self.asteroid_position_counter Server.bonus_x_expanded.clear() Server.bonus_y_expanded.clear() tmpXX = 0 for tmpXX in range(50): Server.bonus_x_expanded.append( tmpXX + Server.bonus_x_coordinate) #prosirivanje koordinata bonusa tmpYY = 0 for tmpYY in range(50): Server.bonus_y_expanded.append( tmpYY + Server.bonus_y_coordinate) #prosirivanje koordinata bonusa self.bonus = Bonus(self.width, self.height, Server.bonus_x_coordinate, Server.bonus_y_coordinate, self) self.bonus.setStyleSheet("background:transparent") self.addWidget(self.bonus) Server.bonus_time = Server.bonus_time + 1 elif Server.bonus_time == 16: if (any(checkXCords in Server.bonus_x_expanded for checkXCords in Server.coordinatesOfRocket1X) and any(checkYCords in Server.bonus_y_expanded for checkYCords in Server.coordinatesOfRocket1Y)): Server.player1Lives = Server.player1Lives + 1 self.label11.setText("Player1 lives--->[" + Server.player1Lives.__str__() + "] score--->[" + Server.player1Score.__str__() + "]") if (any(checkXCords in Server.bonus_x_expanded for checkXCords in Server.coordinatesOfRocket2X) and any(checkYCords in Server.bonus_y_expanded for checkYCords in Server.coordinatesOfRocket2Y)): Server.player2Lives = Server.player2Lives + 1 self.label22.setText("Player2 lives--->[" + Server.player2Lives.__str__() + "] score--->[" + Server.player2Score.__str__() + "]") if (any(checkXCords in Server.bonus_x_expanded for checkXCords in Server.coordinatesOfRocket3X) and any(checkYCords in Server.bonus_y_expanded for checkYCords in Server.coordinatesOfRocket3Y)): Server.player3Lives = Server.player3Lives + 1 self.label22.setText("Player3 lives--->[" + Server.player3Lives.__str__() + "] score--->[" + Server.player3Score.__str__() + "]") if (any(checkXCords in Server.bonus_x_expanded for checkXCords in Server.coordinatesOfRocket4X) and any(checkYCords in Server.bonus_y_expanded for checkYCords in Server.coordinatesOfRocket4Y)): Server.player4Lives = Server.player4Lives + 1 self.label22.setText("Player4 lives--->[" + Server.player4Lives.__str__() + "] score--->[" + Server.player4Score.__str__() + "]") self.bonus.hide() self.bonus.move(1234, 1234) Server.bonus_time = 0 def recevee(self): if Server.second_player_is_here == False: while True: text = '' print("cekam recv neki") bin = self.s.recv(2048) text += str(bin, 'utf-8') print("dobio recv") print(text) self.queueForPlayer2.put(text) elif Server.second_player_is_here == True: while True: text = '' print("cekam recv neki") bin = self.s.recv(2048) text += str(bin, 'utf-8') print("dobio recv") print(text) self.queue.put(text) def createAsteroids(self): o = 0 for o in range(Server.level): self.asteroid_position_counter += 1 self.asteroid_0 = NetworkAsteroid(self.width, self.height, self, Server.asteroid_id.__str__(), False, 3, self.asteroid_position_counter) self.asteroid_0.setFocus() # mozda i ne mora posto je timer tamo self.asteroid_0.setStyleSheet("background:transparent") self.asteroid_0.resize(60, 50) self.addWidget(self.asteroid_0) # activeBigAsteroids.append(self.asteroid_0) Server.activeAsteroids[Server.asteroid_id.__str__()] = 0 Server.asteroid_id = Server.asteroid_id.__int__() + 1 def createMediumAsteroids(self): o = 0 for o in range(2): self.asteroid_position_counter += 1 self.asteroid_0 = NetworkAsteroid(self.width, self.height, self, Server.asteroid_id.__str__(), False, 2, self.asteroid_position_counter) self.asteroid_0.setFocus() # mozda i ne mora posto je timer tamo self.asteroid_0.setStyleSheet("background:transparent") self.asteroid_0.resize(60, 50) self.addWidget(self.asteroid_0) # activeBigAsteroids.append(self.asteroid_0) Server.activeAsteroids[Server.asteroid_id.__str__()] = 0 Server.asteroid_id = Server.asteroid_id.__int__() + 1 def createSmallAsteroids(self): o = 0 for o in range(2): self.asteroid_position_counter += 1 self.asteroid_0 = NetworkAsteroid(self.width, self.height, self, Server.asteroid_id.__str__(), False, 1, self.asteroid_position_counter) self.asteroid_0.setFocus() # mozda i ne mora posto je timer tamo self.asteroid_0.setStyleSheet("background:transparent") self.asteroid_0.resize(60, 50) self.addWidget(self.asteroid_0) # activeBigAsteroids.append(self.asteroid_0) Server.activeAsteroids[Server.asteroid_id.__str__()] = 0 Server.asteroid_id = Server.asteroid_id.__int__() + 1 def set_up_scores_labels(self): self.label11 = QLabel("Player1 lives--->[" + Server.player1Lives.__str__() + "] score--->[" + Server.player1Score.__str__() + "]") self.label11.resize(400, 30) self.label11.move(5, 440) self.label11.setStyleSheet( "font: 9pt; color: #f03a54; font:bold; background-color: transparent; " ) self.addWidget(self.label11) self.label22 = QLabel("Player2 lives--->[" + Server.player2Lives.__str__() + "] score--->[" + Server.player2Score.__str__() + "]") self.label22.resize(400, 30) self.label22.move(5, 470) self.label22.setStyleSheet( "font: 9pt; color: yellow; font:bold; background-color: transparent; " ) self.addWidget(self.label22) self.label33 = QLabel("Player3 lives--->[" + Server.player3Lives.__str__() + "] score--->[" + Server.player3Score.__str__() + "]") self.label33.resize(400, 30) self.label33.move(320, 440) self.label33.setStyleSheet( "font: 9pt; color: blue; font:bold; background-color: transparent; " ) self.addWidget(self.label33) self.label44 = QLabel("Player4 lives--->[" + Server.player4Lives.__str__() + "] score--->[" + Server.player4Score.__str__() + "]") self.label44.resize(400, 30) self.label44.move(320, 470) self.label44.setStyleSheet( "font: 9pt; color: green; font:bold; background-color: transparent; " ) self.addWidget(self.label44) self.labelLevel = QLabel("Level : " + Server.level.__str__()) self.labelLevel.resize(400, 30) self.labelLevel.move(500, 10) self.labelLevel.setStyleSheet( "font: 9pt; color: white; font: bold; background-color: transparent;" ) self.addWidget(self.labelLevel) def game_is_over( self, playerId ): # ako je game over proveri za kog igraca je game over ako je multiplayer, onog drugog pusti da jos igra if playerId == 1: Server.coordinatesOfRocket1X.clear() Server.coordinatesOfRocket1Y.clear() self.rocketnumber1.hide() self.rocketnumber1.move(1000, 1000) elif playerId == 2: Server.coordinatesOfRocket2X.clear() Server.coordinatesOfRocket2Y.clear() self.rocketnumber2.hide() self.rocketnumber2.move(1000, 1000) elif playerId == 3: Server.coordinatesOfRocket3X.clear() Server.coordinatesOfRocket3Y.clear() self.rocketnumber3.hide() self.rocketnumber3.move(1000, 1000) elif playerId == 4: Server.coordinatesOfRocket4X.clear() Server.coordinatesOfRocket4Y.clear() self.rocketnumber4.hide() self.rocketnumber4.move(1000, 1000) if Server.player1Lives == 0 and Server.player2Lives == 0 and Server.player3Lives == 0 and Server.player4Lives == 0: # ako su 4 playera, tek kada su sva 4 mrtva prebaci na game_over_scene self.check_game_over_new_scene() def check_game_over_new_scene(self): self.gameOverScene = GameOver(self, self.width, self.height) self.gameOverScene.returnBtn.clicked.connect(self.menus) self.gameOverScene.label6.hide() # self.gameOverScene.label2.hide() self.gameOverScene.label3.hide() self.gameOverScene.label4.hide() self.gameOverScene.label5.hide() if Server.player1Score >= Server.player2Score and Server.player1Score >= Server.player3Score and Server.player1Score >= Server.player4Score: self.gameOverScene.label2.setText( "Network game winner is Player1.") elif Server.player2Score >= Server.player1Score and Server.player2Score >= Server.player3Score and Server.player2Score >= Server.player4Score: self.gameOverScene.label2.setText( "Network game winner is Player2.") self.gameOverScene.label2.setStyleSheet( "font: 9pt; color: yellow; font:bold; background-color: transparent; " ) elif Server.player3Score >= Server.player1Score and Server.player3Score >= Server.player2Score and Server.player3Score >= Server.player4Score: self.gameOverScene.label2.setText( "Network game winner is Player3.") self.gameOverScene.label2.setStyleSheet( "font: 9pt; color: blue; font:bold; background-color: transparent; " ) elif Server.player4Score >= Server.player1Score and Server.player4Score >= Server.player2Score and Server.player4Score >= Server.player3Score: self.gameOverScene.label2.setText( "Network game winner is Player4.") self.gameOverScene.label2.setStyleSheet( "font: 9pt; color: green; font:bold; background-color: transparent; " ) self.gameOverScene.label2.move(140, 350) self.sceneParent.setScene(self.gameOverScene) def menus(self): self.sceneParent.ExitGame()
def __init__(self, parent, width, height): super().__init__(parent) Server.tournamentActivated = True global activeMediumAsteroids global activeSmallAsteroids self.width = width self.height = height self.setSceneRect(0, 0, self.width - 2, self.height - 2) self.sceneParent = parent self.queue = mp.Queue() self.firstrelease = False self.gameOverScene = None self.keyList = [] self.timer = QBasicTimer() self.timer.start(2000, self) self.key_notifier = KeyNotifier() self.key_notifier.key_signal.connect(self.__update_position__) self.key_notifier.start() self.label = QLabel() self.pixmap = QPixmap('Images/img2.png') self.label.setPixmap(self.pixmap) self.label.resize(600, 500) self.addWidget(self.label) # self.bonus = None self.rocketnumber1 = SpaceShuttle(self.width, self.height, self, 1) self.rocketnumber1.resize(60, 50) # slika je 50x50 ali se glupo okrece tako da je bolje ovako da bi se uvek videla cela self.rocketnumber1.setStyleSheet("background:transparent") self.rocketnumber2 = SpaceShuttle(self.width, self.height, self, 2) self.rocketnumber2.resize(60, 50) # slika je 50x50 ali se glupo okrece tako da je bolje ovako da bi se uvek videla cela self.rocketnumber2.setStyleSheet("background:transparent") self.queue.put('go') self.createAsteroids() print("DONE") self.label2 = QLabel( "Player1 lives--->[" + Server.player1Lives.__str__() + "] score--->[" + Server.player1Score.__str__() + "]") self.label2.resize(400, 30) self.label2.move(5, 440) self.label2.setStyleSheet("font: 9pt; color: #f03a54; font:bold; background-color: transparent; ") self.addWidget(self.label2) self.label3 = QLabel( "Player2 lives--->[" + Server.player2Lives.__str__() + "] score--->[" + Server.player2Score.__str__() + "]") self.label3.resize(400, 30) self.label3.move(5, 470) self.label3.setStyleSheet("font: 9pt; color: yellow; font:bold; background-color: transparent; ") self.addWidget(self.label3) self.label6 = QLabel( "Player3 lives--->[" + Server.player3Lives.__str__() + "] score--->[" + Server.player3Score.__str__() + "]") self.label6.resize(400, 30) self.label6.move(320, 440) self.label6.setStyleSheet("font: 9pt; color: blue; font:bold; background-color: transparent; ") self.addWidget(self.label6) self.label7 = QLabel( "Player4 lives--->[" + Server.player4Lives.__str__() + "] score--->[" + Server.player4Score.__str__() + "]") self.label7.resize(400, 30) self.label7.move(320, 470) self.label7.setStyleSheet("font: 9pt; color: green; font:bold; background-color: transparent; ") self.addWidget(self.label7) self.setPlayers(self.label6, self.label7) self.label4 = QLabel("Level : " + Server.level.__str__()) self.label4.resize(400, 30) self.label4.move(500, 10) self.label4.setStyleSheet("font: 9pt; color: white; font: bold; background-color: transparent;") self.addWidget(self.label4)
class Tournament(QGraphicsScene): def __init__(self, parent, width, height): super().__init__(parent) Server.tournamentActivated = True global activeMediumAsteroids global activeSmallAsteroids self.width = width self.height = height self.setSceneRect(0, 0, self.width - 2, self.height - 2) self.sceneParent = parent self.queue = mp.Queue() self.firstrelease = False self.gameOverScene = None self.keyList = [] self.timer = QBasicTimer() self.timer.start(2000, self) self.key_notifier = KeyNotifier() self.key_notifier.key_signal.connect(self.__update_position__) self.key_notifier.start() self.label = QLabel() self.pixmap = QPixmap('Images/img2.png') self.label.setPixmap(self.pixmap) self.label.resize(600, 500) self.addWidget(self.label) # self.bonus = None self.rocketnumber1 = SpaceShuttle(self.width, self.height, self, 1) self.rocketnumber1.resize(60, 50) # slika je 50x50 ali se glupo okrece tako da je bolje ovako da bi se uvek videla cela self.rocketnumber1.setStyleSheet("background:transparent") self.rocketnumber2 = SpaceShuttle(self.width, self.height, self, 2) self.rocketnumber2.resize(60, 50) # slika je 50x50 ali se glupo okrece tako da je bolje ovako da bi se uvek videla cela self.rocketnumber2.setStyleSheet("background:transparent") self.queue.put('go') self.createAsteroids() print("DONE") self.label2 = QLabel( "Player1 lives--->[" + Server.player1Lives.__str__() + "] score--->[" + Server.player1Score.__str__() + "]") self.label2.resize(400, 30) self.label2.move(5, 440) self.label2.setStyleSheet("font: 9pt; color: #f03a54; font:bold; background-color: transparent; ") self.addWidget(self.label2) self.label3 = QLabel( "Player2 lives--->[" + Server.player2Lives.__str__() + "] score--->[" + Server.player2Score.__str__() + "]") self.label3.resize(400, 30) self.label3.move(5, 470) self.label3.setStyleSheet("font: 9pt; color: yellow; font:bold; background-color: transparent; ") self.addWidget(self.label3) self.label6 = QLabel( "Player3 lives--->[" + Server.player3Lives.__str__() + "] score--->[" + Server.player3Score.__str__() + "]") self.label6.resize(400, 30) self.label6.move(320, 440) self.label6.setStyleSheet("font: 9pt; color: blue; font:bold; background-color: transparent; ") self.addWidget(self.label6) self.label7 = QLabel( "Player4 lives--->[" + Server.player4Lives.__str__() + "] score--->[" + Server.player4Score.__str__() + "]") self.label7.resize(400, 30) self.label7.move(320, 470) self.label7.setStyleSheet("font: 9pt; color: green; font:bold; background-color: transparent; ") self.addWidget(self.label7) self.setPlayers(self.label6, self.label7) self.label4 = QLabel("Level : " + Server.level.__str__()) self.label4.resize(400, 30) self.label4.move(500, 10) self.label4.setStyleSheet("font: 9pt; color: white; font: bold; background-color: transparent;") self.addWidget(self.label4) def setPlayers(self, label1Hide, label2Hide): if Server.currentRound == 0: self.addWidget(self.rocketnumber1) self.addWidget(self.rocketnumber2) label1Hide.hide() label2Hide.hide() elif Server.currentRound == 1: self.rocketnumber1.hide() self.rocketnumber2.hide() Server.level = 0 Server.coordinatesOfRocket1X.clear() Server.coordinatesOfRocket1Y.clear() Server.coordinatesOfRocket2X.clear() Server.coordinatesOfRocket2Y.clear() Server.bulletsCollection1X.clear() Server.bulletsCollection1Y.clear() Server.bulletsCollection2X.clear() Server.bulletsCollection2Y.clear() Server.i = 1 Server.i2 = 1 Server.i3 = 1 Server.i4 = 1 self.rocketnumber3 = SpaceShuttle(self.width, self.height, self, 1) self.rocketnumber3.resize(60, 50) # slika je 50x50 ali se glupo okrece tako da je bolje ovako da bi se uvek videla cela self.rocketnumber3.setStyleSheet("background:transparent") self.rocketnumber4 = SpaceShuttle(self.width, self.height, self, 2) self.rocketnumber4.resize(60, 50) # slika je 50x50 ali se glupo okrece tako da je bolje ovako da bi se uvek videla cela self.rocketnumber4.setStyleSheet("background:transparent") self.addWidget(self.rocketnumber3) self.addWidget(self.rocketnumber4) label1Hide.hide() label2Hide.hide() elif Server.currentRound == 2:#napraviti nove rakete samo im zapamtiti id zbog player naziva self.rocketnumber3.hide() self.rocketnumber4.hide() Server.level = 0 Server.coordinatesOfRocket1X.clear() Server.coordinatesOfRocket1Y.clear() Server.coordinatesOfRocket2X.clear() Server.coordinatesOfRocket2Y.clear() Server.bulletsCollection1X.clear() Server.bulletsCollection1Y.clear() Server.bulletsCollection2X.clear() Server.bulletsCollection2Y.clear() Server.i = 1 Server.i2 = 1 Server.i3 = 1 Server.i4 = 1 if Server.player1Score > Server.player2Score: Server.Win0 = 1 elif Server.player1Score < Server.player2Score: Server.Win0 = 2 elif Server.player1Score == Server.player2Score: if Server.Died == 1: # ako je p1 prvi poginuo Server.Win0 = 1 else: Server.Win0 = 2 if Server.player3Score > Server.player4Score: Server.Win1 = 3 elif Server.player3Score < Server.player4Score: Server.Win1 = 4 elif Server.player3Score == Server.player4Score: if Server.Died2 == 3: Server.Win1 = 3 else: Server.Win1 = 4 print("Server.Died -> " + Server.Died.__str__()) print("Win0 -> " + Server.Win0.__str__()) print("Win1 -> " + Server.Win1.__str__()) Server.player1Lives = 3 Server.player2Lives = 3 Server.player3Lives = 3 Server.player4Lives = 3 Server.player1Score = 0 Server.player2Score = 0 Server.player3Score = 0 Server.player4Score = 0 self.rocketnumber5 = SpaceShuttle(self.width, self.height, self, 1) self.rocketnumber5.resize(60, 50) # slika je 50x50 ali se glupo okrece tako da je bolje ovako da bi se uvek videla cela self.rocketnumber5.setStyleSheet("background:transparent") self.rocketnumber6 = SpaceShuttle(self.width, self.height, self, 2) self.rocketnumber6.resize(60, 50) # slika je 50x50 ali se glupo okrece tako da je bolje ovako da bi se uvek videla cela self.rocketnumber6.setStyleSheet("background:transparent") self.addWidget(self.rocketnumber5) self.addWidget(self.rocketnumber6) label1Hide.hide() label2Hide.hide() # postavlja pobednika iz prvog meca if Server.Win0 == 1: #self.addWidget(self.rocketnumber1) self.label2.setText("Player1 lives--->[" + Server.player5Lives.__str__() + "] score--->[" + Server.player5Score.__str__() + "]") self.label2.setStyleSheet("font: 9pt; color: #f03a54; font:bold; background-color: transparent; ") self.label2.show() elif Server.Win0 == 2: #self.addWidget(self.rocketnumber2) self.label2.setText("Player2 lives--->[" + Server.player5Lives.__str__() + "] score--->[" + Server.player5Score.__str__() + "]") self.label2.setStyleSheet("font: 9pt; color: yellow; font:bold; background-color: transparent; ") self.label2.show() # postavlja pobednika iz drugog meca if Server.Win1 == 3: #self.addWidget(self.rocketnumber3) self.label6.setText( "Player3 lives--->[" + Server.player6Lives.__str__() + "] score--->[" + Server.player6Score.__str__() + "]") self.label6.setStyleSheet("font: 9pt; color: blue; font:bold; background-color: transparent; ") self.label6.show() elif Server.Win1 == 4: #self.addWidget(self.rocketnumber4) self.label6.setText( "Player4 lives--->[" + Server.player6Lives.__str__() + "] score--->[" + Server.player6Score.__str__() + "]") self.label6.setStyleSheet("font: 9pt; color: green; font:bold; background-color: transparent; ") self.label6.show() def createAsteroids(self): o = 0 print("Create big for second rounds") print(Server.level) for o in range(Server.level): self.asteroid_0 = Asteroid(self.width, self.height, self, Server.asteroid_id.__str__(), True, 3) self.asteroid_0.setFocus() # mozda i ne mora posto je timer tamo self.asteroid_0.setStyleSheet("background:transparent") self.asteroid_0.resize(60, 50) self.addWidget(self.asteroid_0) Server.activeBigAsteroids.append(self.asteroid_0) Server.activeAsteroids[Server.asteroid_id.__str__()] = 0 Server.asteroid_id = Server.asteroid_id.__int__() + 1 def createMediumAsteroids(self): o = 0 for o in range(2): self.asteroid_0 = Asteroid(self.width, self.height, self, Server.asteroid_id.__str__(), True, 2) self.asteroid_0.setFocus() # mozda i ne mora posto je timer tamo self.asteroid_0.setStyleSheet("background:transparent") self.asteroid_0.resize(60, 50) self.addWidget(self.asteroid_0) Server.activeBigAsteroids.append(self.asteroid_0) Server.activeAsteroids[Server.asteroid_id.__str__()] = 0 Server.asteroid_id = Server.asteroid_id.__int__() + 1 def createSmallAsteroids(self): o = 0 for o in range(2): self.asteroid_0 = Asteroid(self.width, self.height, self, Server.asteroid_id.__str__(), True, 1) self.asteroid_0.setFocus() # mozda i ne mora posto je timer tamo self.asteroid_0.setStyleSheet("background:transparent") self.asteroid_0.resize(60, 50) self.addWidget(self.asteroid_0) Server.activeBigAsteroids.append(self.asteroid_0) Server.activeAsteroids[Server.asteroid_id.__str__()] = 0 Server.asteroid_id = Server.asteroid_id.__int__() + 1 def game_is_over(self, playerId): # ako je game over proveri za kog igraca je game over ako je multiplayer, onog drugog pusti da jos igra """if self.players_number == 1: # ako je singleplyaer cim ima 0 lives znaci mrtav je znaci game_over je self.gameOverScene = GameOver(self, self.width, self.height) self.gameOverScene.returnBtn.clicked.connect(self.menus) self.gameOverScene.label4.hide() # hide that player2 is winner self.gameOverScene.label3.hide() # hide player2 score bcs this is singleplayer self.sceneParent.setScene(self.gameOverScene)""" if playerId == 10: Server.coordinatesOfRocket1X.clear() Server.coordinatesOfRocket1Y.clear() #if Server.currentRound == 0: self.rocketnumber1.hide() self.rocketnumber1.move(1000, 1000) elif playerId == 20: Server.coordinatesOfRocket2X.clear() Server.coordinatesOfRocket2Y.clear() self.rocketnumber2.hide() self.rocketnumber2.move(1000, 1000) elif playerId == 12: Server.coordinatesOfRocket1X.clear() Server.coordinatesOfRocket1Y.clear() self.rocketnumber5.hide() self.rocketnumber5.move(1000, 1000) elif playerId == 31: Server.coordinatesOfRocket1X.clear() Server.coordinatesOfRocket1Y.clear() self.rocketnumber3.hide() self.rocketnumber3.move(1000, 1000) elif playerId == 32: Server.coordinatesOfRocket1X.clear() Server.coordinatesOfRocket1Y.clear() self.rocketnumber5.hide() self.rocketnumber5.move(1000, 1000) elif playerId == 41: Server.coordinatesOfRocket2X.clear() Server.coordinatesOfRocket2Y.clear() self.rocketnumber4.hide() self.rocketnumber4.move(1000, 1000) elif playerId == 22: Server.coordinatesOfRocket2X.clear() Server.coordinatesOfRocket2Y.clear() self.rocketnumber6.hide() self.rocketnumber6.move(1000, 1000) elif playerId == 42: Server.coordinatesOfRocket2X.clear() Server.coordinatesOfRocket2Y.clear() self.rocketnumber6.hide() self.rocketnumber6.move(1000, 1000) if Server.currentRound == 2 and Server.player5Lives == 0 and Server.player6Lives == 0: self.gameOverScene = GameOver(self, self.width, self.height) self.gameOverScene.returnBtn.clicked.connect(self.menus) if Server.player5Score > Server.player6Score: self.gameOverScene.label4.hide() self.gameOverScene.label3.hide() self.gameOverScene.label2.hide() self.gameOverScene.label5.hide() if Server.Win0 == 1: self.gameOverScene.label6.setText("Player1 Win") self.gameOverScene.label6.setStyleSheet("font: 9pt; color: #f03a54; font:bold; background-color: transparent; ") else: self.gameOverScene.label6.setText("Player2 Win") self.gameOverScene.label6.setStyleSheet("font: 9pt; color: yellow; font:bold; background-color: transparent; ") elif Server.player5Score < Server.player6Score: self.gameOverScene.label4.hide() self.gameOverScene.label3.hide() self.gameOverScene.label2.hide() self.gameOverScene.label5.hide() if Server.Win1 == 3: self.gameOverScene.label6.setText("Player3 Win") self.gameOverScene.label6.setStyleSheet("font: 9pt; color: blue; font:bold; background-color: transparent; ") else: self.gameOverScene.label6.setText("Player4 Win") self.gameOverScene.label6.setStyleSheet("font: 9pt; color: green; font:bold; background-color: transparent; ") else: self.gameOverScene.label4.hide() self.gameOverScene.label3.hide() self.gameOverScene.label2.hide() self.gameOverScene.label5.hide() self.gameOverScene.label6.setText("Tied") self.sceneParent.setScene(self.gameOverScene) def menus(self): self.sceneParent.ExitGame() def keyPressEvent(self, event): self.key_notifier.add_key(event.key()) def keyReleaseEvent(self, event): self.key_notifier.rem_key(event.key()) def __update_position__(self, key): # time.sleep(1) if key == Qt.Key_W: # dodata logika da moze da se pomera samo ako je idalje ziva ta raketa if Server.currentRound == 0 and Server.player2Lives > 0: self.rocketnumber2.upRocket2.emit() elif Server.currentRound == 1 and Server.player4Lives > 0: self.rocketnumber4.upRocket2.emit() elif Server.currentRound == 2 and Server.player6Lives > 0: self.rocketnumber6.upRocket2.emit() elif key == Qt.Key_A: if Server.currentRound == 0 and Server.player2Lives > 0: self.rocketnumber2.leftRocket2.emit() elif Server.currentRound == 1 and Server.player4Lives > 0: self.rocketnumber4.leftRocket2.emit() elif Server.currentRound == 2 and Server.player6Lives > 0: self.rocketnumber6.leftRocket2.emit() elif key == Qt.Key_D: if Server.currentRound == 0 and Server.player2Lives > 0: self.rocketnumber2.rightRocket2.emit() elif Server.currentRound == 1 and Server.player4Lives > 0: self.rocketnumber4.rightRocket2.emit() elif Server.currentRound == 2 and Server.player6Lives > 0: self.rocketnumber6.rightRocket2.emit() elif key == Qt.Key_S: if Server.currentRound == 0 and Server.player2Lives > 0: self.rocketnumber2.fireRocket2.emit() elif Server.currentRound == 1 and Server.player4Lives > 0: self.rocketnumber4.fireRocket2.emit() elif Server.currentRound == 2 and Server.player6Lives > 0: self.rocketnumber6.fireRocket2.emit() elif key == Qt.Key_Up: if Server.currentRound == 0 and Server.player1Lives > 0: self.rocketnumber1.upRocket1.emit() elif Server.currentRound == 1 and Server.player3Lives > 0: self.rocketnumber3.upRocket1.emit() elif Server.currentRound == 2 and Server.player5Lives > 0: self.rocketnumber5.upRocket1.emit() elif key == Qt.Key_Right: if Server.currentRound == 0 and Server.player1Lives > 0: self.rocketnumber1.rightRocket1.emit() elif Server.currentRound == 1 and Server.player3Lives > 0: self.rocketnumber3.rightRocket1.emit() elif Server.currentRound == 2 and Server.player5Lives > 0: self.rocketnumber5.rightRocket1.emit() elif key == Qt.Key_Left: if Server.currentRound == 0 and Server.player1Lives > 0: self.rocketnumber1.leftRocket1.emit() elif Server.currentRound == 1 and Server.player3Lives > 0: self.rocketnumber3.leftRocket1.emit() elif Server.currentRound == 2 and Server.player5Lives > 0: self.rocketnumber5.leftRocket1.emit() elif key == Qt.Key_Space: if Server.currentRound == 0 and Server.player1Lives > 0: self.rocketnumber1.fireRocket1.emit() elif Server.currentRound == 1 and Server.player3Lives > 0: self.rocketnumber3.fireRocket1.emit() elif Server.currentRound == 2 and Server.player5Lives > 0: self.rocketnumber5.fireRocket1.emit() def timerEvent(self, a0: 'QTimerEvent'): if Server.bonus_time < 15: Server.bonus_time = Server.bonus_time + 1 elif Server.bonus_time == 15: Server.bonus_x_coordinate = random.randrange(0, 500) Server.bonus_y_coordinate = random.randrange(0, 450) Server.bonus_x_expanded.clear() Server.bonus_y_expanded.clear() tmpXX = 0 for tmpXX in range(50): Server.bonus_x_expanded.append(tmpXX + Server.bonus_x_coordinate) # prosirivanje koordinata bonusa tmpYY = 0 for tmpYY in range(50): Server.bonus_y_expanded.append(tmpYY + Server.bonus_y_coordinate) # prosirivanje koordinata bonusa self.bonus = Bonus(self.width, self.height, Server.bonus_x_coordinate, Server.bonus_y_coordinate, self) self.bonus.setStyleSheet("background:transparent") self.addWidget(self.bonus) Server.bonus_time = Server.bonus_time + 1 elif Server.bonus_time == 16 and Server.currentRound == 0: # ako igraju P1 i P2 if (any(checkXCords in Server.bonus_x_expanded for checkXCords in Server.coordinatesOfRocket1X) and any( checkYCords in Server.bonus_y_expanded for checkYCords in Server.coordinatesOfRocket1Y)): Server.player1Lives = Server.player1Lives + 1 self.label2.setText( "Player1 lives--->[" + Server.player1Lives.__str__() + "] score--->[" + Server.player1Score.__str__() + "]") if (any(checkXCords in Server.bonus_x_expanded for checkXCords in Server.coordinatesOfRocket2X) and any( checkYCords in Server.bonus_y_expanded for checkYCords in Server.coordinatesOfRocket2Y)): Server.player2Lives = Server.player2Lives + 1 self.label3.setText( "Player2 lives--->[" + Server.player2Lives.__str__() + "] score--->[" + Server.player2Score.__str__() + "]") self.bonus.hide() self.bonus.move(1234, 1234) Server.bonus_time = 0 elif Server.bonus_time == 16 and Server.currentRound == 1: # ako igraju P3 i P4 if (any(checkXCords in Server.bonus_x_expanded for checkXCords in Server.coordinatesOfRocket1X) and any( checkYCords in Server.bonus_y_expanded for checkYCords in Server.coordinatesOfRocket1Y)): Server.player3Lives = Server.player3Lives + 1 self.label6.setText( "Player3 lives--->[" + Server.player3Lives.__str__() + "] score--->[" + Server.player3Score.__str__() + "]") if (any(checkXCords in Server.bonus_x_expanded for checkXCords in Server.coordinatesOfRocket2X) and any( checkYCords in Server.bonus_y_expanded for checkYCords in Server.coordinatesOfRocket2Y)): Server.player4Lives = Server.player4Lives + 1 self.label7.setText( "Player4 lives--->[" + Server.player4Lives.__str__() + "] score--->[" + Server.player4Score.__str__() + "]") self.bonus.hide() self.bonus.move(1234, 1234) Server.bonus_time = 0 elif Server.bonus_time == 16 and Server.currentRound == 2: # pobednici if (any(checkXCords in Server.bonus_x_expanded for checkXCords in Server.coordinatesOfRocket1X) and any( checkYCords in Server.bonus_y_expanded for checkYCords in Server.coordinatesOfRocket1Y)): if Server.Win0 == 1: # ako je bio pobedio P1 Server.player5Lives = Server.player5Lives + 1 self.label2.setText( "Player1 lives--->[" + Server.player5Lives.__str__() + "] score--->[" + Server.player5Score.__str__() + "]") elif Server.Win0 == 2: # ako je bio pobedio P2 Server.player5Lives = Server.player5Lives + 1 self.label2.setText( "Player2 lives--->[" + Server.player5Lives.__str__() + "] score--->[" + Server.player5Score.__str__() + "]") if (any(checkXCords in Server.bonus_x_expanded for checkXCords in Server.coordinatesOfRocket2X) and any( checkYCords in Server.bonus_y_expanded for checkYCords in Server.coordinatesOfRocket2Y)): if Server.Win1 == 3: # ako je bio pobedio P3 Server.player6Lives = Server.player6Lives + 1 self.label6.setText( "Player3 lives--->[" + Server.player6Lives.__str__() + "] score--->[" + Server.player6Score.__str__() + "]") elif Server.Win1 == 4: # ako je bio pobedio P4 Server.player6Lives = Server.player6Lives + 1 self.label6.setText( "Player4 lives--->[" + Server.player6Lives.__str__() + "] score--->[" + Server.player6Score.__str__() + "]") self.bonus.hide() self.bonus.move(1234, 1234) Server.bonus_time = 0
class GameWindow(QMainWindow): startAgain = pyqtSignal() def __init__(self): super().__init__() print('Started new game window') self.game = None self.centralWidget = QStackedWidget() self.setCentralWidget(self.centralWidget) self.mainMenuWidget = MainMenu() self.menu() self.key_notifier = KeyNotifier() self.key_notifier.key_signal.connect(self.do_key_press) self.key_notifier.start() self.setWindowTitle('Galaga') self.setWindowIcon(QIcon('images/ship.png')) self.show() def center(self): screen = QDesktopWidget().screenGeometry() size = self.geometry() self.move((screen.width() - size.width()) / 2, (screen.height() - size.height()) / 2) def menu(self): self.mainMenuWidget.playOnePlayerGameSignal.connect(self.playOnePlayerGame) self.mainMenuWidget.playTwoPlayerGameSignal.connect(self.playTwoPlayersGame) self.mainMenuWidget.quitGameSignal.connect(self.quit) self.centralWidget.addWidget(self.mainMenuWidget) self.centralWidget.setCurrentWidget(self.mainMenuWidget) self.resize(240, 250) self.center() def playOnePlayerGame(self): self.resize(config.BOARD_WIDTH, config.BOARD_HEIGHT) self.center() self.game = game.Game(1) self.game.gameOverSignal.connect(self.gameOver) self.setCentralWidget(self.game) def playTwoPlayersGame(self): self.resize(config.BOARD_WIDTH, config.BOARD_HEIGHT) self.center() self.game = game.Game(2) self.game.gameOverSignal.connect(self.gameOver) self.setCentralWidget(self.game) def gameOver(self): print('GAME IS OVER') self.startAgain.emit() def do_key_press(self, key): try: self.game.__update_position__(key) except Exception as e: print('Exception: {}'.format(str(e))) def keyPressEvent(self, event): self.key_notifier.add_key(event.key()) def keyReleaseEvent(self, event): self.key_notifier.rem_key(event.key()) def quit(self): sys.exit() def stopThreads(self): try: print('Closing all threads from Galagaa') if self.game is not None: self.game.shootLaser.die() self.game.moveEnemy.die() self.game.enemyShoot.die() self.game.enemyAttack.die() self.game.deusExMachina.die() self.key_notifier.die() except Exception as e: print('Exception while trying to close threads: {}', str(e)) def closeEvent(self, event): try: if self.game is not None: self.game.shootLaser.die() self.game.moveEnemy.die() self.game.enemyShoot.die() self.game.enemyAttack.die() self.game.deusExMachina.die() self.key_notifier.die() except Exception as e: print('Exception while trying to close threads: {}', str(e)) sys.exit()
class GameScene(QGraphicsScene): def __init__(self, parent, width, height, num_of_players): super().__init__(parent) global activeBigAsteroids global activeMediumAsteroids global activeSmallAsteroids self.width = width self.height = height self.setSceneRect(0, 0, self.width - 2, self.height - 2) self.sceneParent = parent # self.players_number = num_of_players self.queue = mp.Queue() self.firstrelease = False self.keyList = [] self.timer = QBasicTimer() self.timer.start(2000, self) self.key_notifier = KeyNotifier() self.key_notifier.key_signal.connect(self.__update_position__) self.key_notifier.start() self.label = QLabel() self.pixmap = QPixmap('Images/img2.png') self.label.setPixmap(self.pixmap) self.label.resize(600, 500) self.addWidget(self.label) # self.bonus = None self.rocketnumber1 = SpaceShuttle(self.width, self.height, self, 1) self.rocketnumber1.resize( 60, 50 ) #slika je 50x50 ali se glupo okrece tako da je bolje ovako da bi se uvek videla cela self.rocketnumber1.setStyleSheet("background:transparent") self.addWidget(self.rocketnumber1) if self.players_number == 2: self.rocketnumber2 = SpaceShuttle(self.width, self.height, self, 2) self.rocketnumber2.resize( 60, 50 ) # slika je 50x50 ali se glupo okrece tako da je bolje ovako da bi se uvek videla cela self.rocketnumber2.setStyleSheet("background:transparent") self.addWidget(self.rocketnumber2) self.queue.put('go') self.createAsteroids() print("DONE") self.label2 = QLabel("Player1 lives--->[" + Server.player1Lives.__str__() + "] score--->[" + Server.player1Score.__str__() + "]") self.label2.resize(400, 30) self.label2.move(5, 440) self.label2.setStyleSheet( "font: 9pt; color: #f03a54; font:bold; background-color: transparent; " ) self.addWidget(self.label2) self.label3 = QLabel("Player2 lives--->[" + Server.player2Lives.__str__() + "] score--->[" + Server.player2Score.__str__() + "]") self.label3.resize(400, 30) self.label3.move(5, 470) self.label3.setStyleSheet( "font: 9pt; color: yellow; font:bold; background-color: transparent; " ) if self.players_number == 1: self.label3.hide() elif self.players_number == 2: self.addWidget(self.label3) self.label4 = QLabel("Level : " + Server.level.__str__()) self.label4.resize(400, 30) self.label4.move(500, 10) self.label4.setStyleSheet( "font: 12pt; color: white; font: bold; background-color: transparent;" ) self.addWidget(self.label4) def createAsteroids(self): o = 0 for o in range(Server.level): self.asteroid_0 = Asteroid(self.width, self.height, self, Server.asteroid_id.__str__(), False, 3) self.asteroid_0.setFocus() # mozda i ne mora posto je timer tamo self.asteroid_0.setStyleSheet("background:transparent") self.asteroid_0.resize(60, 50) self.addWidget(self.asteroid_0) activeBigAsteroids.append(self.asteroid_0) Server.activeAsteroids[Server.asteroid_id.__str__()] = 0 Server.asteroid_id = Server.asteroid_id.__int__() + 1 def createMediumAsteroids(self): o = 0 for o in range(2): self.asteroid_0 = Asteroid(self.width, self.height, self, Server.asteroid_id.__str__(), False, 2) self.asteroid_0.setFocus() # mozda i ne mora posto je timer tamo self.asteroid_0.setStyleSheet("background:transparent") self.asteroid_0.resize(60, 50) self.addWidget(self.asteroid_0) activeBigAsteroids.append(self.asteroid_0) Server.activeAsteroids[Server.asteroid_id.__str__()] = 0 Server.asteroid_id = Server.asteroid_id.__int__() + 1 def createSmallAsteroids(self): o = 0 for o in range(2): self.asteroid_0 = Asteroid(self.width, self.height, self, Server.asteroid_id.__str__(), False, 1) self.asteroid_0.setFocus() # mozda i ne mora posto je timer tamo self.asteroid_0.setStyleSheet("background:transparent") self.asteroid_0.resize(60, 50) self.addWidget(self.asteroid_0) activeBigAsteroids.append(self.asteroid_0) Server.activeAsteroids[Server.asteroid_id.__str__()] = 0 Server.asteroid_id = Server.asteroid_id.__int__() + 1 def game_is_over( self, playerId ): #ako je game over proveri za kog igraca je game over ako je multiplayer, onog drugog pusti da jos igra if self.players_number == 1: #ako je singleplyaer cim ima 0 lives znaci mrtav je znaci game_over je self.gameOverScene = GameOver(self, self.width, self.height) self.gameOverScene.returnBtn.clicked.connect(self.menus) self.gameOverScene.label4.hide() #hide that player2 is winner self.gameOverScene.label6.hide() #hide that player2 is winner self.gameOverScene.label3.hide( ) #hide player2 score bcs this is singleplayer self.sceneParent.setScene(self.gameOverScene) elif self.players_number == 2: if playerId == 1: Server.coordinatesOfRocket1X.clear() Server.coordinatesOfRocket1Y.clear() self.rocketnumber1.hide() self.rocketnumber1.move(1000, 1000) elif playerId == 2: Server.coordinatesOfRocket2X.clear() Server.coordinatesOfRocket2Y.clear() self.rocketnumber2.hide() self.rocketnumber2.move(1000, 1000) if Server.player1Lives == 0 and Server.player2Lives == 0: #ako su dva playera, tek kada su oba mrtva prebaci na game_over_scene self.gameOverScene = GameOver(self, self.width, self.height) self.gameOverScene.returnBtn.clicked.connect(self.menus) self.gameOverScene.label6.hide() if Server.player1Score > Server.player2Score: self.gameOverScene.label4.hide() elif Server.player2Score > Server.player1Score: self.gameOverScene.label5.hide() elif Server.player1Score == Server.player2Score: self.gameOverScene.label4.hide() self.gameOverScene.label5.hide() self.sceneParent.setScene(self.gameOverScene) def menus(self): self.sceneParent.ExitGame() def keyPressEvent(self, event): self.key_notifier.add_key(event.key()) def keyReleaseEvent(self, event): self.key_notifier.rem_key(event.key()) def __update_position__(self, key): # time.sleep(1) if key == Qt.Key_W and self.players_number == 2 and Server.player2Lives > 0: #dodata logika da moze da se pomera samo ako je idalje ziva ta raketa self.rocketnumber2.upRocket2.emit() elif key == Qt.Key_A and self.players_number == 2 and Server.player2Lives > 0: self.rocketnumber2.leftRocket2.emit() elif key == Qt.Key_D and self.players_number == 2 and Server.player2Lives > 0: self.rocketnumber2.rightRocket2.emit() elif key == Qt.Key_S and self.players_number == 2 and Server.player2Lives > 0: self.rocketnumber2.fireRocket2.emit() elif key == Qt.Key_Up and Server.player1Lives > 0: self.rocketnumber1.upRocket1.emit() elif key == Qt.Key_Right and Server.player1Lives > 0: self.rocketnumber1.rightRocket1.emit() elif key == Qt.Key_Left and Server.player1Lives > 0: self.rocketnumber1.leftRocket1.emit() elif key == Qt.Key_Space and Server.player1Lives > 0: self.rocketnumber1.fireRocket1.emit() def timerEvent( self, a0: 'QTimerEvent' ): #timer je na 2 sekunde gore, zato su ove provere, tako da se na svakih 30 sekundi stvori bonus i da igrac ima 2 sekunde da stane na njega pa se vrsi provera i resetuje se if Server.bonus_time < 15: Server.bonus_time = Server.bonus_time + 1 elif Server.bonus_time == 15: Server.bonus_x_coordinate = random.randrange(0, 500) Server.bonus_y_coordinate = random.randrange(0, 450) Server.bonus_x_expanded.clear() Server.bonus_y_expanded.clear() tmpXX = 0 for tmpXX in range(50): Server.bonus_x_expanded.append( tmpXX + Server.bonus_x_coordinate) #prosirivanje koordinata bonusa tmpYY = 0 for tmpYY in range(50): Server.bonus_y_expanded.append( tmpYY + Server.bonus_y_coordinate) #prosirivanje koordinata bonusa self.bonus = Bonus(self.width, self.height, Server.bonus_x_coordinate, Server.bonus_y_coordinate, self) self.bonus.setStyleSheet("background:transparent") self.addWidget(self.bonus) Server.bonus_time = Server.bonus_time + 1 elif Server.bonus_time == 16: if (any(checkXCords in Server.bonus_x_expanded for checkXCords in Server.coordinatesOfRocket1X) and any(checkYCords in Server.bonus_y_expanded for checkYCords in Server.coordinatesOfRocket1Y)): Server.player1Lives = Server.player1Lives + 1 self.label2.setText("Player1 lives--->[" + Server.player1Lives.__str__() + "] score--->[" + Server.player1Score.__str__() + "]") if (any(checkXCords in Server.bonus_x_expanded for checkXCords in Server.coordinatesOfRocket2X) and any(checkYCords in Server.bonus_y_expanded for checkYCords in Server.coordinatesOfRocket2Y)): Server.player2Lives = Server.player2Lives + 1 self.label3.setText("Player2 lives--->[" + Server.player2Lives.__str__() + "] score--->[" + Server.player2Score.__str__() + "]") self.bonus.hide() self.bonus.move(1234, 1234) Server.bonus_time = 0