def __init__(self,screen,camera,organizer):
     self.camera = camera
     self.screen = screen
     self.organizer = organizer
     self.backToHomeScreen = False
     self.firstCheck = False
     self.cursor = Cursor(0,0,20,self.organizer)
     self.upperLeftButton = CursorRecognition("1",30, [10,10,200,200],self.organizer)
 def __init__(self, screen, camera, organizer, controllernr, lastState):
     self.camera = camera
     self.screen = screen
     self.lastState = lastState
     self.backToLastState = False
     self.backToCalibration = False
     self.organizer = organizer
     self.firstCheck = False
     self.cursor = Cursor(0, 0, 20, self.organizer)
     self.upperLeftButton = CursorRecognition("1", 20, [50, 50, 200, 200],
                                              self.organizer)
     self.upperRightButton = CursorRecognition("2", 20,
                                               [1850 - 250, 50, 200, 200],
                                               self.organizer)
     self.lowerRightButton = CursorRecognition(
         "3", 20, [1850 - 250, 1080 - 250, 200, 200], self.organizer)
     self.lowerLeftButton = CursorRecognition(
         "4", 20, [50, 1080 - 250, 200, 200],
         self.organizer)  # I hate hardcoding, resolution is 1850,1080
     self.controllernr = controllernr
     self.objectCoordinates, self.cameraImage = OR.getCoords(
         self.camera, 0)  # Get the coordinates for controller '0'
     self.allowedTime = 15  # Time to complete the calibration
     self.startTime = time.time(
     )  # Starttime when the program gets initialized
     self.elapsedTime = time.time()  # gets updated every loop
     self.timer = self.elapsedTime - self.startTime  # Time left
Пример #3
0
 def __init__(self, organizer, screenSize, camera, clock, fps):
     self.organizer = organizer
     self.screenSize = screenSize
     self.width = screenSize[0]
     self.height = screenSize[1]
     self.closePlatform = False  #The main while loop looks if this is true or false to break out of the while loop
     self.clock = clock
     self.fps = fps
     self.cursor = Cursor(
         0, 0, 20, self.organizer
     )  # Initialize a cursor in coord (0,0) with radius 20
     self.pongButton = CursorRecognition(
         "Pong", 30, [100, 200, 200, 200], self.organizer
     )  # Make a button for the areaSurveillance with left corner coords (100,200) & length/width = 200
     self.spaceInvadersButton = CursorRecognition("Space Invaders", 30,
                                                  [500, 200, 400, 200],
                                                  self.organizer)
     self.calibrationButton = CursorRecognition(" Calibrate", 30,
                                                [1000, 200, 300, 200],
                                                self.organizer)
     self.closeButton = CursorRecognition("CLOSE", 30, [1500, 50, 200, 150],
                                          self.organizer)
     self.camera = camera
     OR.calibrate(self.screenSize, self.camera,
                  0)  # Initialize the color for controller '0'
     organizer.state = "calibrationTest"
     self.objectCoordinates, self.cameraImage = OR.getCoords(
         self.camera, 0)  # Get the coordinates for controller '0'
     self.controllernr = 0
class CalibrationModel():
    """This is the model for the calibration test after the color calibration"""
    def __init__(self,screen,camera,organizer):
        self.camera = camera
        self.screen = screen
        self.organizer = organizer
        self.backToHomeScreen = False
        self.firstCheck = False
        self.cursor = Cursor(0,0,20,self.organizer)
        self.upperLeftButton = CursorRecognition("1",30, [10,10,200,200],self.organizer)

    def update(self):

        self.upperLeftButton.areaSurveillance(self.cursor,"calibration",self,"firstCheck","True")

        if firstCheck == True:
            self.backToHomeScreen = True

    class CalibrationView():
        """This is the view class for the CalibrationTest""""
        def __init__(self,model):
            self.model = model
            self.myfont = pygame.font.SysFont("monospace", 42) #Font that is used in states "game" and "select_speed" to prompt the user
            self.numberfont = pygame.font.SysFont("monospace", 85, bold=True) #font is used for numbers in "select_speed" state
            self.ColorGreen = (0,250,0)

        def draw(self):
            if self.firstCheck == True:
                self.model.upperLeftButton.draw(self.model.screen, self.ColorGreen)
            else:
                self.model.upperLeftButton.draw(self.model.screen)
            instructions = self.myfont.render("Hover over all the squares before the time runs out", 1, self.ColorGreen)
            self.model.screen.blit(instructions, (400,20))
            pygame.display.update()

        def draw_background(self,screen): # draw the camera image to the background
            self.model.screen.fill(self.ColorBlack)
            newSurface = pygame.surfarray.make_surface(self.model.cameraImage) # Reads the stored camera image and makes a surface out of it
            self.model.screen.blit(newSurface,(0,0)) # Make background of the sufrace (so it becomes live video)
            pygame.display.update()

        class CalibrationController():
            def __init__(self,model):
                self.model = model

            def update(self):
                self.model.objectCoordinates, self.model.cameraImage = OR.getCoords(self,model,camera)
class CalibrationModel():
    """This is the model for the calibration test after the color calibration"""
    def __init__(self, screen, camera, organizer, controllernr, lastState):
        self.camera = camera
        self.screen = screen
        self.lastState = lastState
        self.backToLastState = False
        self.backToCalibration = False
        self.organizer = organizer
        self.firstCheck = False
        self.cursor = Cursor(0, 0, 20, self.organizer)
        self.upperLeftButton = CursorRecognition("1", 20, [50, 50, 200, 200],
                                                 self.organizer)
        self.upperRightButton = CursorRecognition("2", 20,
                                                  [1850 - 250, 50, 200, 200],
                                                  self.organizer)
        self.lowerRightButton = CursorRecognition(
            "3", 20, [1850 - 250, 1080 - 250, 200, 200], self.organizer)
        self.lowerLeftButton = CursorRecognition(
            "4", 20, [50, 1080 - 250, 200, 200],
            self.organizer)  # I hate hardcoding, resolution is 1850,1080
        self.controllernr = controllernr
        self.objectCoordinates, self.cameraImage = OR.getCoords(
            self.camera, 0)  # Get the coordinates for controller '0'
        self.allowedTime = 15  # Time to complete the calibration
        self.startTime = time.time(
        )  # Starttime when the program gets initialized
        self.elapsedTime = time.time()  # gets updated every loop
        self.timer = self.elapsedTime - self.startTime  # Time left

    def update(self):
        self.elapsedTime = time.time()
        self.timer = self.elapsedTime - self.startTime
        if self.timer > self.allowedTime:
            self.backToCalibration = True
        elif self.organizer.state == "first":
            self.upperLeftButton.areaSurveillance(self.cursor, "second",
                                                  self.organizer, "state",
                                                  "second")
        elif self.organizer.state == "second":
            self.upperRightButton.areaSurveillance(self.cursor, "third",
                                                   self.organizer, "state",
                                                   "third")
        elif self.organizer.state == "third":
            self.lowerRightButton.areaSurveillance(self.cursor, "fourth",
                                                   self.organizer, "state",
                                                   "fourth")
        elif self.organizer.state == "fourth":
            self.lowerLeftButton.areaSurveillance(self.cursor, "fourth", self,
                                                  "backToLastState", True)
 def __init__(self, organizer, screenSize, camera, clock, fps):
     self.organizer = organizer
     self.screenSize = screenSize
     self.width = screenSize[0]
     self.height = screenSize[1]
     self.closePlatform = False
     self.clock = clock
     self.fps = fps
     self.cursor = Cursor(
         0, 0, 20, self.organizer
     )  # Initialize a cursor in coord (0,0) with radius 20
     self.pongButton = CursorRecognition(
         "Pong", 30, [100, 200, 200, 200], self.organizer
     )  # Make a button for the areaSurveillance with left corner coords (100,200) & length/width = 200
     self.spaceInvadersButton = CursorRecognition("Space Invaders", 30,
                                                  [500, 200, 400, 200],
                                                  self.organizer)
     self.camera = camera
     OR.calibrate(screenSize, self.camera,
                  0)  # Initialize the color for controller '0'
     self.objectCoordinates, self.cameraImage = OR.getCoords(
         self.camera, 0)  # Get the coordinates for controller '0'
Пример #7
0
    def __init__(self,screen,camera,organizer):
        self.camera = camera
        self.screen = screen
        self.organizer = organizer
        self.backToHomeScreen = False  #If this goes to True, the while loop in which this game runs breaks.
        self.enemystartxcoord = 50
        self.distanceBetweenEnemiesx = 150
        self.enemystartycoord = 100
        self.distanceBetweenEnemiesy = 150
        #initialization of the sprite groups. These will contain all the sprite so they can generate collisions
        self.enemySpriteGroup = pygame.sprite.Group()
        self.enemyBulletSpriteGroup = pygame.sprite.Group()
        self.playerBulletSpriteGroup = pygame.sprite.Group()
        self.obstructionSpriteGroup = pygame.sprite.Group()
        #initialize all the variables we need for moving the enemies of the screen look at the moveEnemies-function for more info
        self.enemiesXposition = 0 #this keeps track of the current left or right movement of the enemies
        self.enemiesXMovement = 5 #this is the max number of horizontal movement
        self.moveRight = True
        self.enemyMoveLooper = 0 #this variable keep track of the current number of loops between every enemy movement

        self.enemyShootLooper = 0 #this variable keep track of the current number of loops until an enemy shoots again
        self.enemyShootMinimumLooper = 20 #this variable is the minimum amount of loops between enemy shots. this is dependent of the number of enemies left.

        self.generateEnemiesAndObstructions() #in this function all the enemies and obstructions are generated. We do it this way to be able to reuse is when a user wants to restart the game

        self.haveToResetGame = False

        self.player = Player(900,900,dir_path+"/data/spaceship.png") #initialize the player with x and y coordinate and the path of the picture
        self.enemyShootSound = pygame.mixer.Sound(dir_path +"/data/shoot.wav")
        self.playerShootSound = pygame.mixer.Sound(dir_path +"/data/playerShoot.wav")
        self.lastTimeShot = 0 #this variable remembers at what time the player shot last
        self.timeBetweenShots = 1 # this variable is the minimum time in ..... between shots
        self.score = Score()
        self.health = Health()

        self.cursor = Cursor(0,0,20,self.organizer)
        self.drawCursor = False
        #creating the buttons that this game will have
        self.startGameButton = CursorRecognition("Start",30, [500, 500, 200,200],self.organizer)
        self.homeScreenButton = CursorRecognition("Home Screen",30, [900,500, 350,150],self.organizer)
        self.restartButton = CursorRecognition("Restart",30, [500,500, 250,150],self.organizer)
        self.stopGameButton = CursorRecognition("STOP",30,[925,50,150,75],self.organizer)
class OverallModel():
    def __init__(self, organizer, screenSize, camera, clock, fps):
        self.organizer = organizer
        self.screenSize = screenSize
        self.width = screenSize[0]
        self.height = screenSize[1]
        self.closePlatform = False
        self.clock = clock
        self.fps = fps
        self.cursor = Cursor(
            0, 0, 20, self.organizer
        )  # Initialize a cursor in coord (0,0) with radius 20
        self.pongButton = CursorRecognition(
            "Pong", 30, [100, 200, 200, 200], self.organizer
        )  # Make a button for the areaSurveillance with left corner coords (100,200) & length/width = 200
        self.spaceInvadersButton = CursorRecognition("Space Invaders", 30,
                                                     [500, 200, 400, 200],
                                                     self.organizer)
        self.camera = camera
        OR.calibrate(screenSize, self.camera,
                     0)  # Initialize the color for controller '0'
        self.objectCoordinates, self.cameraImage = OR.getCoords(
            self.camera, 0)  # Get the coordinates for controller '0'

    def update(self):
        if self.organizer.state == "homeScreen":
            self.pongButton.areaSurveillance(self.cursor, "pong",
                                             self.organizer, "state", "pong")
            self.spaceInvadersButton.areaSurveillance(self.cursor,
                                                      "spaceInvaders",
                                                      self.organizer, "state",
                                                      "spaceInvaders")

        if self.organizer.state == "pong":
            self.pongPhaseKeeper = Organizer(
            )  #create state machine for inside the pong game
            self.pongPhaseKeeper.state = "menu"  # First phase of the game in the state machine is the menu
            self.pongModel = PongModel(self.screen, self.camera,
                                       self.pongPhaseKeeper)
            #TODO give existing screen to newly initialized view, because i think pygame can't handle multiple screens
            #TODO Kill the old screen?
            self.pongView = PongView(self.pongModel)
            self.pongController = PongObjectRecogController(self.pongModel)
            running = True
            while running:  # The program will stay in this while loop while running pong, until it gets closed
                for event in pygame.event.get():
                    if event.type is pygame.QUIT:
                        running = False
                        self.spaceInvadersModel.backToHomeScreen = True
                        self.closePlatform = True
                if self.pongModel.backToHomeScreen == False:  # If backToHomeScreen is false (game is still running), update everything
                    self.pongController.update()
                    self.pongModel.update()
                    self.pongView.draw()
                    self.clock.tick(self.fps / 2)
                else:  # if backToHomeScreen is true (game ended, program got closed), stop the while loop and go back to the homeScreen state
                    running = False
                    self.organizer.state == "homeScreen"

        if self.organizer.state == "spaceInvaders":
            self.spaceInvadersPhaseKeeper = Organizer(
            )  #create state machine for inside the pong game
            self.spaceInvadersPhaseKeeper.state = "menu"
            self.spaceInvadersModel = SpaceInvadersModel(
                self.screen, self.camera, self.spaceInvadersPhaseKeeper)
            self.spaceInvadersView = SpaceInvadersView(self.spaceInvadersModel)
            self.spaceInvadersController = SpaceInvadersController(
                self.spaceInvadersModel)
            running = True
            while running:
                for event in pygame.event.get():
                    if event.type is pygame.QUIT:
                        running = False
                        self.spaceInvadersModel.backToHomeScreen = True
                        self.closePlatform = True
                if self.spaceInvadersModel.backToHomeScreen == False:
                    self.spaceInvadersController.update()
                    self.spaceInvadersModel.update()
                    self.spaceInvadersView.draw()
                    self.clock.tick(self.fps / 2)
                else:
                    running = False
                    self.organizer.state == "homeScreen"

        if self.organizer.state == "calibrationTest":
            self.calibrationModel
    def __init__(self, screen, camera, organizer):
        boundaryOffset = [50, 50]
        boundaryThickness = 10
        self.screen = screen
        self.width = screen.get_width()
        self.height = screen.get_height()

        self.backToHomeScreen = False
        boundaryLength = self.width - 2 * boundaryOffset[0]
        self.upperboundary = Boundary(boundaryOffset[0], boundaryOffset[1],
                                      boundaryThickness, boundaryLength)
        self.lowerboundary = Boundary(boundaryOffset[0],
                                      self.height - boundaryOffset[1],
                                      boundaryThickness, boundaryLength)
        self.organizer = organizer
        self.ball = Ball(int(self.width / 5), int(self.height / 5), 20)

        paddleWidth = 10
        paddleHeight = 100
        cursorRadius = 20
        self.leftPaddle = Paddle(10, self.height / 2, paddleHeight,
                                 paddleWidth)
        self.rightPaddle = Paddle(self.width - 10 - paddleWidth,
                                  self.height / 2, paddleHeight, paddleWidth)
        self.score = Score(self)

        self.components = (self.upperboundary, self.lowerboundary, self.ball,
                           self.leftPaddle, self.rightPaddle, self.score)

        self.cursor = Cursor(int(self.width / 2), int(self.height / 2),
                             cursorRadius, self.organizer)
        #Buttons
        self.selectSpeedButton = CursorRecognition(
            "Select speed", 30, [50, self.height / 2 - 50, 200, 500],
            self.organizer)  #Triggerare in state "menu" - yellow square
        self.speedOneButton = CursorRecognition(
            "1", 30, [
                int((self.width / 6) * 1) - 50,
                int(self.height / 2) - 150, 150, 150
            ], self.organizer
        )  # Number 1 to 5: square to select speed in state "select_speed"
        self.speedTwoButton = CursorRecognition("2", 30, [
            int((self.width / 6) * 2) - 50,
            int(self.height / 2) + 150, 150, 150
        ], self.organizer)
        self.speedThreeButton = CursorRecognition("3", 30, [
            int((self.width / 6) * 3) - 50,
            int(self.height / 2) - 150, 150, 150
        ], self.organizer)
        self.speedFourButton = CursorRecognition("4", 30, [
            int((self.width / 6) * 4) - 50,
            int(self.height / 2) + 150, 150, 150
        ], self.organizer)
        self.speedFiveButton = CursorRecognition(
            "5", 30, [
                int((self.width / 6) * 5) - 50,
                int(self.height / 2) - 150, 150, 150
            ], self.organizer
        )  # Triggers square to repeat the game in state "endgame"
        self.restartButton = CursorRecognition(
            "Restart", 30,
            [int((self.width / 6) * 5),
             int((self.width / 6) * 2), 200, 150], self.organizer)
        self.homeScreenButton = CursorRecognition(
            "Home screen", 30,
            [int((self.width / 6) * 1),
             int((self.width / 6) * 2), 250, 150], self.organizer)
        self.startButton = CursorRecognition(
            "Start", 30,
            [int((self.width / 6) * 1),
             int((self.width / 6) * 2), 150, 150], self.organizer)

        #camera and objectrecognition
        self.camera = camera
        OR.calibrate([self.width, self.height], self.camera,
                     1)  # Initialize the color for controller '1'
        self.objectCoordinatesRight, self.cameraImage = OR.getCoords(
            self.camera, 0
        )  #gets coordinates of the two objects from the python file ObjectRecogImplementation.py

        #initialize the sprite groups for collision detection
        self.boundaryGroup = pygame.sprite.Group()
        self.boundaryGroup.add(self.upperboundary)
        self.boundaryGroup.add(self.lowerboundary)

        self.paddleGroup = pygame.sprite.Group()
        self.paddleGroup.add(self.leftPaddle)
        self.paddleGroup.add(self.rightPaddle)

        #Initialize the sounds
        dir_path = os.path.dirname(os.path.realpath(__file__))
        self.boundarySound = pygame.mixer.Sound(dir_path +
                                                "/data/boundaryBounce.wav")
        self.paddleSound = pygame.mixer.Sound(dir_path +
                                              "/data/paddleBounce.wav")
        self.deathSound = pygame.mixer.Sound(dir_path + "/data/death.wav")
class PongModel():
    """encodes a model of the game state
    screen --   This is a pygame screen object
    camera --   This is a VideoCapture-object that the getCoords-function needs as input
    organizer --    This is the internal phaseKeeper object from the Organizer class
    """
    def __init__(self, screen, camera, organizer):
        boundaryOffset = [50, 50]
        boundaryThickness = 10
        self.screen = screen
        self.width = screen.get_width()
        self.height = screen.get_height()

        self.backToHomeScreen = False
        boundaryLength = self.width - 2 * boundaryOffset[0]
        self.upperboundary = Boundary(boundaryOffset[0], boundaryOffset[1],
                                      boundaryThickness, boundaryLength)
        self.lowerboundary = Boundary(boundaryOffset[0],
                                      self.height - boundaryOffset[1],
                                      boundaryThickness, boundaryLength)
        self.organizer = organizer
        self.ball = Ball(int(self.width / 5), int(self.height / 5), 20)

        paddleWidth = 10
        paddleHeight = 100
        cursorRadius = 20
        self.leftPaddle = Paddle(10, self.height / 2, paddleHeight,
                                 paddleWidth)
        self.rightPaddle = Paddle(self.width - 10 - paddleWidth,
                                  self.height / 2, paddleHeight, paddleWidth)
        self.score = Score(self)

        self.components = (self.upperboundary, self.lowerboundary, self.ball,
                           self.leftPaddle, self.rightPaddle, self.score)

        self.cursor = Cursor(int(self.width / 2), int(self.height / 2),
                             cursorRadius, self.organizer)
        #Buttons
        self.selectSpeedButton = CursorRecognition(
            "Select speed", 30, [50, self.height / 2 - 50, 200, 500],
            self.organizer)  #Triggerare in state "menu" - yellow square
        self.speedOneButton = CursorRecognition(
            "1", 30, [
                int((self.width / 6) * 1) - 50,
                int(self.height / 2) - 150, 150, 150
            ], self.organizer
        )  # Number 1 to 5: square to select speed in state "select_speed"
        self.speedTwoButton = CursorRecognition("2", 30, [
            int((self.width / 6) * 2) - 50,
            int(self.height / 2) + 150, 150, 150
        ], self.organizer)
        self.speedThreeButton = CursorRecognition("3", 30, [
            int((self.width / 6) * 3) - 50,
            int(self.height / 2) - 150, 150, 150
        ], self.organizer)
        self.speedFourButton = CursorRecognition("4", 30, [
            int((self.width / 6) * 4) - 50,
            int(self.height / 2) + 150, 150, 150
        ], self.organizer)
        self.speedFiveButton = CursorRecognition(
            "5", 30, [
                int((self.width / 6) * 5) - 50,
                int(self.height / 2) - 150, 150, 150
            ], self.organizer
        )  # Triggers square to repeat the game in state "endgame"
        self.restartButton = CursorRecognition(
            "Restart", 30,
            [int((self.width / 6) * 5),
             int((self.width / 6) * 2), 200, 150], self.organizer)
        self.homeScreenButton = CursorRecognition(
            "Home screen", 30,
            [int((self.width / 6) * 1),
             int((self.width / 6) * 2), 250, 150], self.organizer)
        self.startButton = CursorRecognition(
            "Start", 30,
            [int((self.width / 6) * 1),
             int((self.width / 6) * 2), 150, 150], self.organizer)

        #camera and objectrecognition
        self.camera = camera
        OR.calibrate([self.width, self.height], self.camera,
                     1)  # Initialize the color for controller '1'
        self.objectCoordinatesRight, self.cameraImage = OR.getCoords(
            self.camera, 0
        )  #gets coordinates of the two objects from the python file ObjectRecogImplementation.py

        #initialize the sprite groups for collision detection
        self.boundaryGroup = pygame.sprite.Group()
        self.boundaryGroup.add(self.upperboundary)
        self.boundaryGroup.add(self.lowerboundary)

        self.paddleGroup = pygame.sprite.Group()
        self.paddleGroup.add(self.leftPaddle)
        self.paddleGroup.add(self.rightPaddle)

        #Initialize the sounds
        dir_path = os.path.dirname(os.path.realpath(__file__))
        self.boundarySound = pygame.mixer.Sound(dir_path +
                                                "/data/boundaryBounce.wav")
        self.paddleSound = pygame.mixer.Sound(dir_path +
                                              "/data/paddleBounce.wav")
        self.deathSound = pygame.mixer.Sound(dir_path + "/data/death.wav")

    def update(self):
        """updates all the components the model has dependent on what state Organizer.state is in"""
        if self.organizer.state == "menu":
            self.selectSpeedButton.areaSurveillance(self.cursor,
                                                    "select_speed",
                                                    self.organizer, "state",
                                                    "select_speed")

        elif self.organizer.state == "select_speed":  # Set 5 areas to click on, each mapped to a different ball speed
            self.speedOneButton.areaSurveillance(self.cursor, "pong_game",
                                                 self.organizer,
                                                 "settings_ballSpeed", 5)
            self.speedTwoButton.areaSurveillance(self.cursor, "pong_game",
                                                 self.organizer,
                                                 "settings_ballSpeed", 10)
            self.speedThreeButton.areaSurveillance(self.cursor, "pong_game",
                                                   self.organizer,
                                                   "settings_ballSpeed", 15)
            self.speedFourButton.areaSurveillance(self.cursor, "pong_game",
                                                  self.organizer,
                                                  "settings_ballSpeed", 22)
            self.speedFiveButton.areaSurveillance(self.cursor, "pong_game",
                                                  self.organizer,
                                                  "settings_ballSpeed", 28)

        elif self.organizer.state == "pong_game":
            self.ball.update(self.organizer)
            #first update the position of the ball and then check if there has been a collision
            boundaryBounce = pygame.sprite.spritecollide(
                self.ball, self.boundaryGroup, False)
            if len(boundaryBounce) > 0:  # In case of bounce on boundary
                self.ball.movingDirection[1] = -self.ball.movingDirection[
                    1]  # Change the x-direction of the its opposite after the bounce
                pygame.mixer.Sound.play(self.boundarySound)

            paddleBounce = pygame.sprite.spritecollide(self.ball,
                                                       self.paddleGroup, False)
            if len(paddleBounce) > 0:
                self.ball.movingDirection[0] = -self.ball.movingDirection[0]
                pygame.mixer.Sound.play(self.paddleSound)

            if self.ball.x < 5:  #When ball goes in the left goal
                self.score.update(1)  #Update the scores( give player2 a point)
                pygame.mixer.Sound.play(self.deathSound)
                self.ball.x = int(self.width /
                                  5)  #move the ball to its new start position
                self.ball.rect.x = self.ball.x  #as well as its attribute rect to it can collide
                self.ball.y = int(self.height / 5)
                self.ball.rect.y = self.ball.y
                self.ball.movingDirection = [
                    1, 1
                ]  #Makes the ball go to right down again

            if self.ball.x > self.width - 5:  #when ball goes in the right goal
                self.score.update(0)  #update scores(give player 1 a point)
                pygame.mixer.Sound.play(self.deathSound)
                self.ball.x = int(4 * self.width / 5)
                self.ball.rect.x = self.ball.x
                self.ball.y = int(self.height / 5)
                self.ball.rect.y = self.ball.y
                self.ball.movingDirection = [-1, 1]

        elif self.organizer.state == "endgame":  #this state is entered when one of the players reaches 5 points
            self.restartButton.areaSurveillance(self.cursor, "menu",
                                                self.organizer, "state",
                                                "menu")
            self.homeScreenButton.areaSurveillance(self.cursor, "True", self,
                                                   "backToHomeScreen", "True")
            self.score.reset()
Пример #11
0
class OverallModel():
    """This is the class for the model that runs the homeScreen and the other games inside of it
    - organizer --  object of the organizer class. This keeps track of the state
    - screenSize -- list containing width and height of the desired screen size of the screen
    - camera -- cv.2 VideoCapture(0) object
    - clock --  a pygame clock
    - fps --    frames per second to run the pygame
    """
    def __init__(self, organizer, screenSize, camera, clock, fps):
        self.organizer = organizer
        self.screenSize = screenSize
        self.width = screenSize[0]
        self.height = screenSize[1]
        self.closePlatform = False  #The main while loop looks if this is true or false to break out of the while loop
        self.clock = clock
        self.fps = fps
        self.cursor = Cursor(
            0, 0, 20, self.organizer
        )  # Initialize a cursor in coord (0,0) with radius 20
        self.pongButton = CursorRecognition(
            "Pong", 30, [100, 200, 200, 200], self.organizer
        )  # Make a button for the areaSurveillance with left corner coords (100,200) & length/width = 200
        self.spaceInvadersButton = CursorRecognition("Space Invaders", 30,
                                                     [500, 200, 400, 200],
                                                     self.organizer)
        self.calibrationButton = CursorRecognition(" Calibrate", 30,
                                                   [1000, 200, 300, 200],
                                                   self.organizer)
        self.closeButton = CursorRecognition("CLOSE", 30, [1500, 50, 200, 150],
                                             self.organizer)
        self.camera = camera
        OR.calibrate(self.screenSize, self.camera,
                     0)  # Initialize the color for controller '0'
        organizer.state = "calibrationTest"
        self.objectCoordinates, self.cameraImage = OR.getCoords(
            self.camera, 0)  # Get the coordinates for controller '0'
        self.controllernr = 0

    def update(self):
        """updates all the components of the model corresponding to their state"""
        if self.organizer.state == "homeScreen":
            self.pongButton.areaSurveillance(self.cursor, "pong",
                                             self.organizer, "state", "pong")
            self.spaceInvadersButton.areaSurveillance(self.cursor,
                                                      "spaceInvaders",
                                                      self.organizer, "state",
                                                      "spaceInvaders")
            self.closeButton.areaSurveillance(self.cursor, "homeScreen", self,
                                              "closePlatform", True)
            self.calibrationButton.areaSurveillance(self.cursor,
                                                    "calibrationTest",
                                                    self.organizer, "state",
                                                    "calibrationTest")

        elif self.organizer.state == "pong":
            self.pongPhaseKeeper = Organizer(
            )  #create state machine for inside the pong game
            self.pongPhaseKeeper.state = "menu"  # First phase of the game in the state machine is the menu
            self.pongModel = PongModel(self.screen, self.camera,
                                       self.pongPhaseKeeper)
            self.pongView = PongView(self.pongModel)
            self.pongController = PongObjectRecogController(self.pongModel)
            pongRunning = True
            while pongRunning:  # The program will stay in this while loop while running pong, until it gets closed
                for event in pygame.event.get():
                    if event.type is pygame.QUIT:
                        pongRunning = False
                        self.pongModel.backToHomeScreen = True
                        self.closePlatform = True
                if self.pongModel.backToHomeScreen == False:  # If backToHomeScreen is false (game is still running), update everything
                    self.pongController.update()
                    self.pongModel.update()
                    self.pongView.draw()
                    self.clock.tick(self.fps / 2)
                else:  # if backToHomeScreen is true (game ended, program got closed), stop the while loop and go back to the homeScreen state
                    pongRunning = False
                    self.organizer.state = "homeScreen"

        elif self.organizer.state == "spaceInvaders":
            self.spaceInvadersPhaseKeeper = Organizer(
            )  #create state machine for inside the pong game
            self.spaceInvadersPhaseKeeper.state = "menu"
            self.spaceInvadersModel = SpaceInvadersModel(
                self.screen, self.camera, self.spaceInvadersPhaseKeeper)
            self.spaceInvadersView = SpaceInvadersView(self.spaceInvadersModel)
            self.spaceInvadersController = SpaceInvadersController(
                self.spaceInvadersModel)
            spaceRunning = True
            while spaceRunning:
                for event in pygame.event.get():
                    if event.type is pygame.QUIT:
                        spaceRunning = False
                        self.spaceInvadersModel.backToHomeScreen = True
                        self.closePlatform = True
                if self.spaceInvadersModel.backToHomeScreen == False:
                    self.spaceInvadersController.update()
                    self.spaceInvadersModel.update()
                    self.spaceInvadersView.draw()
                    self.clock.tick(self.fps / 2)  #TODO What is this??
                else:
                    spaceRunning = False
                    self.organizer.state = "homeScreen"

        elif self.organizer.state == "calibrationTest":
            self.calibrationPhaseKeeper = Organizer()
            self.calibrationPhaseKeeper.state = "first"
            self.calibrationModel = CalibrationModel(
                self.screen, self.camera, self.calibrationPhaseKeeper,
                self.controllernr, self.organizer.lastState)
            self.calibrationView = CalibrationView(self.calibrationModel)
            self.calibrationController = CalibrationController(
                self.calibrationModel)
            calibrationRunning = True
            while calibrationRunning:
                for event in pygame.event.get():
                    if event.type is pygame.QUIT:
                        calibrationRunning = False
                        self.calibrationModel.backToHomeScreen = True
                        self.closePlatform = True
                if self.calibrationModel.backToCalibration == False:
                    self.calibrationController.update()
                    self.calibrationModel.update()
                    self.calibrationView.draw()
                    self.clock.tick(self.fps / 2)
                else:
                    calibrationRunning = False
                    OR.calibrate(self.screenSize, self.camera,
                                 self.controllernr)
                    self.organizer.state = "calibrationTest"
                if self.calibrationModel.backToLastState == True:
                    calibrationRunning = False
                    self.organizer.state = self.calibrationModel.lastState

            self.lastState = self.organizer.state
Пример #12
0
    def __init__(self, screen, camera, organizer):
        self.camera = camera
        self.screen = screen
        self.organizer = organizer
        self.backToHomeScreen = False  #If this goes to True, the while loop in which this game runs breaks.
        self.enemystartxcoord = 50
        self.distanceBetweenEnemiesx = 150
        self.enemystartycoord = 100
        self.distanceBetweenEnemiesy = 150
        #initialization of the sprite groups. These will contain all the sprite so they can generate collisions
        self.enemySpriteGroup = pygame.sprite.Group()
        self.enemyBulletSpriteGroup = pygame.sprite.Group()
        self.playerBulletSpriteGroup = pygame.sprite.Group()
        self.obstructionSpriteGroup = pygame.sprite.Group()
        #initialize all the variables we need for moving the enemies of the screen look at the moveEnemies-function for more info
        self.enemiesXposition = 0  #this keeps track of the current left or right movement of the enemies
        self.enemiesXMovement = 5  #this is the max number of horizontal movement
        self.moveRight = True
        self.enemyMoveLooper = 0  #this variable keep track of the current number of loops between every enemy movement

        self.enemyShootLooper = 0  #this variable keep track of the current number of loops until an enemy shoots again
        self.enemyShootMinimumLooper = 20  #this variable is the minimum amount of loops between enemy shots. this is dependent of the number of enemies left.
        #initialization of all the enemies and adding them to their respective spriteGroups
        for i in range(10):
            enemy = Enemy(
                self.enemystartxcoord + self.distanceBetweenEnemiesx * i,
                self.enemystartycoord, dir_path + "/data/level3monster.png",
                15)
            self.enemySpriteGroup.add(enemy)
        for i in range(10):
            enemy = Enemy(
                self.enemystartxcoord + self.distanceBetweenEnemiesx * i,
                self.enemystartycoord + self.distanceBetweenEnemiesy,
                dir_path + "/data/level2monster.png", 10)
            self.enemySpriteGroup.add(enemy)
        for i in range(10):
            for j in range(2, 4):
                enemy = Enemy(
                    self.enemystartxcoord + self.distanceBetweenEnemiesx * i,
                    self.enemystartycoord + self.distanceBetweenEnemiesy * j,
                    dir_path + "/data/level1monster.png", 5)
                self.enemySpriteGroup.add(enemy)
        #initialization of the obstructinos at there fixed spot and adding them to the obstructionSpriteGroup
        for i in range(3):
            obstruction = Obstruction(300 + 500 * i, 700)
            self.obstructionSpriteGroup.add(obstruction)

        self.player = Player(
            900, 900, dir_path + "/data/spaceship.png"
        )  #initialize the player with x and y coordinate and the path of the picture
        self.score = Score()
        self.health = Health()

        self.cursor = Cursor(0, 0, 20, self.organizer)
        #creating the buttons that this game will have
        self.startGameButton = CursorRecognition("Start", 30,
                                                 [500, 500, 200, 200],
                                                 self.organizer)
        self.homeScreenButton = CursorRecognition("Home Screen", 30,
                                                  [500, 500, 300, 150],
                                                  self.organizer)
        self.restartButton = CursorRecognition("Restart", 30,
                                               [500, 700, 200, 150],
                                               self.organizer)
Пример #13
0
class SpaceInvadersModel():
    """This is the model for the space invaders game
    - pygame screen object,
    - cv2.VideoCapture(0) object
    - In-game phaseKeeper of the Organizer class"""
    def __init__(self, screen, camera, organizer):
        self.camera = camera
        self.screen = screen
        self.organizer = organizer
        self.backToHomeScreen = False  #If this goes to True, the while loop in which this game runs breaks.
        self.enemystartxcoord = 50
        self.distanceBetweenEnemiesx = 150
        self.enemystartycoord = 100
        self.distanceBetweenEnemiesy = 150
        #initialization of the sprite groups. These will contain all the sprite so they can generate collisions
        self.enemySpriteGroup = pygame.sprite.Group()
        self.enemyBulletSpriteGroup = pygame.sprite.Group()
        self.playerBulletSpriteGroup = pygame.sprite.Group()
        self.obstructionSpriteGroup = pygame.sprite.Group()
        #initialize all the variables we need for moving the enemies of the screen look at the moveEnemies-function for more info
        self.enemiesXposition = 0  #this keeps track of the current left or right movement of the enemies
        self.enemiesXMovement = 5  #this is the max number of horizontal movement
        self.moveRight = True
        self.enemyMoveLooper = 0  #this variable keep track of the current number of loops between every enemy movement

        self.enemyShootLooper = 0  #this variable keep track of the current number of loops until an enemy shoots again
        self.enemyShootMinimumLooper = 20  #this variable is the minimum amount of loops between enemy shots. this is dependent of the number of enemies left.
        #initialization of all the enemies and adding them to their respective spriteGroups
        for i in range(10):
            enemy = Enemy(
                self.enemystartxcoord + self.distanceBetweenEnemiesx * i,
                self.enemystartycoord, dir_path + "/data/level3monster.png",
                15)
            self.enemySpriteGroup.add(enemy)
        for i in range(10):
            enemy = Enemy(
                self.enemystartxcoord + self.distanceBetweenEnemiesx * i,
                self.enemystartycoord + self.distanceBetweenEnemiesy,
                dir_path + "/data/level2monster.png", 10)
            self.enemySpriteGroup.add(enemy)
        for i in range(10):
            for j in range(2, 4):
                enemy = Enemy(
                    self.enemystartxcoord + self.distanceBetweenEnemiesx * i,
                    self.enemystartycoord + self.distanceBetweenEnemiesy * j,
                    dir_path + "/data/level1monster.png", 5)
                self.enemySpriteGroup.add(enemy)
        #initialization of the obstructinos at there fixed spot and adding them to the obstructionSpriteGroup
        for i in range(3):
            obstruction = Obstruction(300 + 500 * i, 700)
            self.obstructionSpriteGroup.add(obstruction)

        self.player = Player(
            900, 900, dir_path + "/data/spaceship.png"
        )  #initialize the player with x and y coordinate and the path of the picture
        self.score = Score()
        self.health = Health()

        self.cursor = Cursor(0, 0, 20, self.organizer)
        #creating the buttons that this game will have
        self.startGameButton = CursorRecognition("Start", 30,
                                                 [500, 500, 200, 200],
                                                 self.organizer)
        self.homeScreenButton = CursorRecognition("Home Screen", 30,
                                                  [500, 500, 300, 150],
                                                  self.organizer)
        self.restartButton = CursorRecognition("Restart", 30,
                                               [500, 700, 200, 150],
                                               self.organizer)

    def update(self):
        """This update function is divide for the different states of the organizer
        inside the different states different components have to be updated
        """
        if self.organizer.state == "game":
            #Inside the "game"-state we update all the components the game has:
            # - the player
            # - the bullets that are in the enemyBulletSpriteGroup and in the playerBulletSpriteGroup
            # - the Obstructions that are in their obstructionSpriteGroup
            # - the enemies in their enemySpriteGroup
            self.player.update()
            for bullet in self.playerBulletSpriteGroup:
                bullet.update()
            for obstr in self.obstructionSpriteGroup:
                obstr.update()
            self.moveEnemies()
            self.enemyShoot()
            for bullet in self.enemyBulletSpriteGroup:
                bullet.update()

            #In this sectin we look for collisions between the spriteGroups
            #These collision-functions return a dictionary.
            #The values of the dictionary are lists containing all the colliding sprites from the seconds spritegroup you enter in the function
            bulletbulletCollideDict = pygame.sprite.groupcollide(
                self.enemyBulletSpriteGroup, self.playerBulletSpriteGroup,
                True, True)
            bulletAndEnemyCollideDict = pygame.sprite.groupcollide(
                self.playerBulletSpriteGroup, self.enemySpriteGroup, True,
                False)
            for element in bulletAndEnemyCollideDict:
                self.score.add(bulletAndEnemyCollideDict[element]
                               [0].received_points_when_killed)
                bulletAndEnemyCollideDict[element][0].die()
            # TODO: change the picture of the enemy to dead for some amount of loops
            bulletAndObstructionCollideDict = pygame.sprite.groupcollide(
                self.enemyBulletSpriteGroup, self.obstructionSpriteGroup, True,
                False)
            for element in bulletAndObstructionCollideDict:
                bulletAndObstructionCollideDict[element][0].shot()
            playerBulletAndObstructionCollideDict = pygame.sprite.groupcollide(
                self.playerBulletSpriteGroup, self.obstructionSpriteGroup,
                True, False)
            for element in playerBulletAndObstructionCollideDict:
                playerBulletAndObstructionCollideDict[element][0].shot()
            bulletAndPlayerCollideList = pygame.sprite.spritecollide(
                self.player, self.enemyBulletSpriteGroup, True)
            if len(bulletAndPlayerCollideList) > 0:
                self.health.gotShot()

            #Transitions to the next state:--------------------------------------------------
            if len(self.enemySpriteGroup.sprites()
                   ) == 0:  #all the enemy are deathSound
                self.organizer.win = True
                self.organizer.state = "endgame"

            elif self.health.healthLevel == 0:
                self.organizer.win = False
                self.organizer.state = "endgame"

        elif self.organizer.state == "menu":  #this state is the first state when we enter this game
            #areaSurveillance over the start button of the game
            self.startGameButton.areaSurveillance(self.cursor, "game",
                                                  self.organizer, "state",
                                                  "game")

        elif self.organizer.state == "endgame":  #this state occurs when the game ends
            self.homeScreenButton.areaSurveillance(self.cursor, "True", self,
                                                   "backToHomeScreen", "True")
            self.restartButton.areaSurveillance(self.cursor, "menu",
                                                self.organizer, "state",
                                                "menu")
            #areaSurveillance over the "restart button" of the game
            #areaSurveillance over the "go back to homeScreen button"

    def playerShoot(self):
        """This makes the player shoot from its current position
        """
        #TODO : make a looper so the player can't shoot constantly
        playerbullet = Bullet(10, 1, self.player.x, self.player.y)
        playerbullet.add(self.playerBulletSpriteGroup)

    def moveEnemies(self):
        """this function makes the enemies move across the screen starting from left to right and then down
        The enemies are only moved once every 10 loops. So the first thing the function does is checking if the looper is 10.
        If so then it moves the enemies. If not then it increments the looper by one.
        So the enemies move left and right for 5 steps (self.enemiesXMovement) of 10 pixels each.
        """
        if self.enemyMoveLooper == 10:
            if self.moveRight:
                self.enemiesXposition += 1
                for enemy in self.enemySpriteGroup:
                    enemy.move(10, 0)
            else:
                self.enemiesXposition -= 1
                for enemy in self.enemySpriteGroup:
                    enemy.move(-10, 0)

            if self.enemiesXposition > self.enemiesXMovement:
                self.moveRight = False
            if self.enemiesXposition == 0:
                self.moveRight = True

            if self.enemiesXposition == self.enemiesXMovement:
                for enemy in self.enemySpriteGroup:
                    enemy.move(0, 1)

            self.enemyMoveLooper = 0
        else:
            self.enemyMoveLooper += 1

    def enemyShoot(self):
        """Makes the enemies shoot after once every so many loops"""
        if self.enemyShootLooper == self.enemyShootMinimumLooper:
            enemyList = self.enemySpriteGroup.sprites()
            randomEnemy = random.choice(enemyList)
            enemyBullet = Bullet(10, -1, randomEnemy.x, randomEnemy.y)
            enemyBullet.add(self.enemyBulletSpriteGroup)
            #make the frequency of enemy shooting dependent of number of enemies
            self.enemyShootMinimumLooper = 60 - len(enemyList)
            self.enemyShootLooper = 0  #if one of the enemies shot, set the enemyShootLooper back to zero
            pass
        else:
            self.enemyShootLooper += 1  # if none of the enemies didn't shoot this loop, increment the enemyShootLooper