Files
flippr-game/GameState.py
Jonas Zeunert 00122949c2 einrücken
2022-09-01 00:47:40 +02:00

123 lines
3.7 KiB
Python

import logging
import config
from lamps.Lamp import CREDIT
from itertools import cycle
from lamps.LampGroup import *
import asyncio
import threading
class GameState:
playerCount = 0
players = None
credits = config.BALLS_PER_GAME
isPlaying = False
isStarted = False
isIdle = True
idleThread = None
def __init__(self, playerStateFactory, highscore, specialDisplay, currentPlayerID = 0):
CREDIT.activate()
self.highscore = highscore
self.playerStateFactory = playerStateFactory
self.dummyPlayer = playerStateFactory.createDummyPlayerState()
self._currentPlayer = self.dummyPlayer
self.gameStateID = currentPlayerID
self.highscore = highscore
self.specialDisplay = specialDisplay
self.specialDisplay.printCredits(self.credits)
self.startIdleLoop()
def nextPlayer(self):
if not self.isStarted:
return
self.currentPlayer = next(self.players)
def startGame(self, playerCount):
self.isStarted = True
self.isPlaying = True
self.createPlayers(playerCount)
self.nextPlayer()
logging.info("Game Started")
def endGame(self):
self.writeHighscore()
self.players = None
self.playerCount = 0
self._currentPlayer = self.dummyPlayer
self.isPlaying = False
self.isStarted = False
logging.info("Game ended")
self.startIdleLoop()
def startIdleLoop(self):
logging.info("Starting Idle Loop")
PLAYER_LAMPS.deactivate()
self.isIdle = True
self.idleThread = threading.Thread(target=self.idleLoop)
self.idleThread.start()
def stopIdleLoop(self):
logging.info("Stopping Idle Loop")
self.isIdle = False
self.idleThread.join()
self.deactivate_all()
def deactivate_all(self):
all_cabinet_lamps = [BONUS_LAMPS, BONUS_MULTIPLIER_LAMPS, CHAMP_LAMPS,
UPPER_PLAYFIELD_TIME_LAMPS, TUNNEL_NUMBER_LAMPS,
TUNNEL_LAMPS, TUNNEL_SCORE_LAMPS]
for lamp_group in all_cabinet_lamps:
lamp_group.deactivate()
def idleLoop(self):
all_cabinet_lamps = [BONUS_LAMPS, BONUS_MULTIPLIER_LAMPS, CHAMP_LAMPS,
UPPER_PLAYFIELD_TIME_LAMPS, TUNNEL_NUMBER_LAMPS,
TUNNEL_LAMPS, TUNNEL_SCORE_LAMPS]
while True:
for _ in range(20):
random_group = random.choice(all_cabinet_lamps)
random_group.toggleRandom(0.2)
if not self.isIdle:
return
for lamps in all_cabinet_lamps:
for lamp in lamps.lamps:
lamp.activate()
if not self.isIdle:
return
time.sleep(0.1)
self.deactivate_all()
def createPlayers(self, playerCount):
self.playerCount = playerCount
players = []
for i in range(playerCount):
player = self.playerStateFactory.createPlayerState(i)
players.append(player)
self.players = cycle(players)
@property
def currentPlayer(self):
return self._currentPlayer
@currentPlayer.setter
def currentPlayer(self, player):
logging.info("Set active player to player " + str(player.id))
self._currentPlayer = self.dummyPlayer
player.activate()
self._currentPlayer = player
def writeHighscore(self):
for player in self.players:
if player.hasHighscore:
with open(config.HIGHSCORE_FILE, "w+") as file:
file.write(player.score)
file.flush()
file.close()