Esempio n. 1
0
    def move(self, player):
        self.obstacleTimer += 1
        self.score += 1
        #print(self.score)

        if self.obstacleTimer > self.minObsInterval + random(50, 100):
            self.addObstacle()

        player.move()

        for obsInd in range(len(self.obstacles)):
            try:
                if self.obstacles[obsInd]:
                    self.obstacles[obsInd].move()
                    if self.obstacles[obsInd].pos.x + self.obstacles[
                            obsInd].objWidth < 0:
                        del (self.obstacles[obsInd])
            except IndexError as e:
                pass
            try:
                out = self.NeuralNet.drive([self.obstacles[0].pos.x])
                if out[0] < 1:
                    player.callback()
            except IndexError:
                pass
Esempio n. 2
0
def runPyGame():
  # Initialise PyGame.
  pygame.init()
  
  # Set up the clock. This will tick every frame and thus maintain a relatively constant framerate. Hopefully.
  fps = 60.0
  fpsClock = pygame.time.Clock()
  
  # Set up the window.
  width, height = 640, 480
  screen = pygame.display.set_mode((width, height))
  
  # screen is the surface representing the window.
  # PyGame surfaces can be thought of as screen sections that you can draw onto.
  # You can also draw surfaces onto other surfaces, rotate surfaces, and transform surfaces.
  
  # Main game loop.
  dt = 1/fps # dt is the time since last frame.
  while True: # Loop forever!
    if not player.gameOver:
      player.move()
      
    
      for tree in world.trees:
        tree.update()
    update(dt) # You can update/draw here, I've just moved the code for neatness.
    draw(screen)

    
    dt = fpsClock.tick(fps)
Esempio n. 3
0
def update():
    global player, food, clock, is_running

    clock.tick(60)

    # Keys
    player.press(pygame.key.get_pressed())

    # Events
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            is_running = False
        elif event.type == player_event:
            player.move()
            eating()
        elif event.type == food_event:
            food.create()

    # Draw
    window.fill(BACKGROUND_COLOR)

    player.draw(draw_rect)
    food.draw(draw_rect)

    pygame.display.update()
Esempio n. 4
0
def main():
    player = Player()
    globals.PLAYER = player
    globals.NAME = globals.NAME.get_value()
    globals.SCORE = score.Score(globals.NAME)
    save = s.Save()
    globals.NB_MORTS = globals.SCORE.get()
    if globals.LOGS:
        print("NB_morts", globals.NB_MORTS)
    globals.NUM_LVL = save.get_lvl(globals.NAME)
    lvl = globals.NUM_LVL
    run = True
    load_lvl(lvl)
    fonts.font_init()
    while run:
        globals.LT = clock.tick(60)
        gameIcon()

        if globals.LVL_CHANGED:
            load_lvl(globals.NUM_LVL)

        globals.WIN.fill(colors.GREY)  # background

        level.show(globals.MAP)  # tiles
        for m in mobs.mobs:
            m.drawMob()
        globals.PLAYER.draw()  # player
        if globals.Jour:  # day
            hud.draw_bar(globals.PLAYER.energie)
        else:  # night
            pygame.draw.polygon(globals.WIN, colors.BLACK, blindPoints)
        hud.draw_bar(globals.PLAYER.energie)
        hud.draw_lvl()
        hud.draw_deaths()

        if globals.NUM_LVL == 1:
            scenario.draw(0)
        elif globals.NUM_LVL == 2:
            scenario.draw(1)
        elif globals.NUM_LVL == 3:
            scenario.draw(2)

        pygame.display.flip()  # show

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
                globals.SCORE.add(globals.NB_MORTS)
                save.add(globals.NAME, globals.NUM_LVL)
        if not player.moving:
            player.move()
        else:
            player.moveAnim()
        player.checkState()
        for m in mobs.mobs:
            m.act()

    pygame.quit()
Esempio n. 5
0
File: game.py Progetto: kspi/tron
 def do_turn(self):
     self.turn += 1
     for num, player in enumerate(self.players):
         if player.alive:
             player.decide(self.board, self.players)
             player.move(self.board)
             self.check_winning_condition()
             if self.game_over:
                 return 
Esempio n. 6
0
def buyRound(player, endTime):
    global quickTiming
    global randomTime
    if time.time() + 1.5 / quickTiming >= endTime:
        return  # makes sure there is 1.5 seconds to move the piece
    player.move(report, quickTiming, randomTime)
    if time.time() + 1.5 / quickTiming >= endTime:
        return  # checks for time after the move - makes sure theres at least 1.5 seconds to make the move

    #tile action phase
    if player.tile == 24:  #on go to jail

        player.wait(
            0.5, 0.8, quickTiming, randomTime
        )  #-----------------------------------------------------------------------------

        player.tile = 8  #reset player position to jail
        player.path.append(8)
        player.timesJailed += 1  #record count

    elif player.tile == 0 or player.tile == 16 or player.tile == 8:  # if the player is on GO or Jail do nothing
        if player.tile == 0 or player.tile == 16:
            if report:
                sys.stdout.write("player " + str(player.id) +
                                 " landed on GO " + "\n")
        else:
            if report:
                sys.stdout.write("player " + str(player.id) +
                                 " is visiting jail " + "\n")

    elif player.tile > 0 and player.tile < 32:  #can purchase tile
        # sys.stdout.write("--player " + str(player.id) + " trying to acquire block " + "\n")
        block.acquire()  #mutex lock around board
        # sys.stdout.write("--player " + str(player.id) + " got block " + "\n")

        purResult = b.purchase(player)
        if purResult == 2:  # successful
            player.canPurchase(b, report, block, quickTiming, randomTime)
        elif purResult == 0:  # not enough money
            if report:
                sys.stdout.write("player " + str(player.id) +
                                 " does not have enough money to buy " +
                                 str(player.tile) + "\n")
            block.release()  #release mutex
            # sys.stdout.write("--player " + str(player.id) + " released block " + "\n")
        else:
            if report:
                sys.stdout.write("property " + str(player.tile) +
                                 " already owned " + "\n")
            block.release()  #release mutex
            # sys.stdout.write("--player " + str(player.id) + " released block " + "\n")

    else:
        print("something went very wrong -> player jumped the board")
Esempio n. 7
0
 def sock(ws):
     connection = Connection(ws)
     connection.send(self.welcome)
     player = connection.handleLogin()
     connection.send(self.instructions)
     connection.receive()
     b = self.behaviourFactory.create(player, 'behaviours.player.DefaultPlayerBehaviour')
     player.attachBehaviour(b)
     self.addConnection(connection)
     player.move('hoofdingang')
     connection.handleMessages(self.callback)
     player.logout()
     self.removeConnection(connection)
Esempio n. 8
0
 def action(self, board):
     if self.isFirst:
         score, move = maxPlay(board, 0, self.MAX_DEPTH, -50, 50)
     else:
         score, move = minPlay(board, 0, self.MAX_DEPTH, -50, 50)
     newBoard, event = player.move(board, move)
     return newBoard, event, False, move
Esempio n. 9
0
def maxPlay(aiBoard, curDepth, maxDepth, alpha, beta):
    if isEnd(aiBoard) or (curDepth == maxDepth):
        return curState(aiBoard), -1

    maxScore, maxMove = -50, 0
    for i in range(6):

        if aiBoard[i] == 0:
            continue

        newAiBoard, event = player.move([aiBoard[j] for j in range(14)], i)

        if event:
            score, move = maxPlay(newAiBoard, curDepth + 1, maxDepth, alpha,
                                  beta)
        else:
            score, move = minPlay(newAiBoard, curDepth + 1, maxDepth, alpha,
                                  beta)

        if maxScore < score:
            maxScore = score
            maxMove = i

        alpha = max(alpha, maxScore)

        if maxScore > beta:
            break
    return maxScore, maxMove
Esempio n. 10
0
def minPlay(aiBoard, curDepth, maxDepth, alpha, beta):
    if isEnd(aiBoard) or (curDepth == maxDepth):
        return curState(aiBoard), -1

    minScore, minMove = 50, 0
    for i in range(7, 13):

        if aiBoard[i] == 0:
            continue

        newAiBoard, event = player.move([aiBoard[j] for j in range(14)], i)

        if event:
            score, move = minPlay(newAiBoard, curDepth + 1, maxDepth, alpha,
                                  beta)
        else:
            score, move = maxPlay(newAiBoard, curDepth + 1, maxDepth, alpha,
                                  beta)

        if minScore > score:
            minScore = score
            minMove = i

        beta = min(beta, minScore)

        if minScore < alpha:
            break
    return minScore, minMove
Esempio n. 11
0
    def main(self):
        """ Runs the main loop. """
        start = time.time()
        cps = 8  # Cycles per second to run simulation. Set to None for no limit.
        cycle = 0

        starting_players = self.players[::-1]

        while len(self.players) > 0:

            # Check keyboard inputs and window closing
            events = pygame.event.get()
            self.check_globals(events)

            dead_players = set()

            # Update players
            for player in self.players[::-1]:
                player.update(events)
                if player in self.players:
                    dead_players |= player.move()
                    self.last_active_player = player
                if Game.pickle_best_agent:
                    try:
                        player.controller.agent.pop.pickle_best_agent = Game.pickle_best_agent
                    except AttributeError as a:
                        pass

            for player in dead_players:
                player.die()

            if Game.simulate and self.render_enable:
                self.display.update(Game.vis_mode)
                self.render_settings()
                pygame.display.flip()

            # Run at a fixed number of cycles per second
            if Game.simulate:
                while time.time() < start + 1 / cps:
                    pass
                start += 1 / cps
            else:
                start = time.time()

            cycle += 1

        if Game.render_enable:
            self.display.update(Game.vis_mode)
            self.render_settings()
            pygame.display.flip()

        if len(starting_players):
            winner = max(starting_players, key=lambda p: p.age)
            false_winner = False
            for item in starting_players:
                if item.age >= winner.age and item is not winner:
                    false_winner = True
            if not false_winner:
                winner.age *= 2
        return [bot.age * SURVIVAL_SCORE for bot in self.bot_list]
Esempio n. 12
0
    def moveCheck(self, player, position):
        # next point is the point to move, but nothing happens so far
        # position like (0,-40)

        nextPoint = player.position.move(position)
        nextTile = self.superBoard.getTile(nextPoint)

        if nextTile.passableTotal():
            if player.type == "players" and nextTile.hasPower():
                player.getPower(nextTile.type)
                nextTile.destroy()

            player.move(position) ## consider it !!!!!!!!!!!!!!!!!!!!
            return True
        else:
            return False
Esempio n. 13
0
def talk_to_bot(
    statement
):  # this is the only way the player can interact with the game once they die, they enter a command and it goes to the bot
    if "move" in statement:
        dest = statement[statement.find("move") + 1]
        player.move(dest)
    elif "go" in statement:
        dest = statement[statement.find("go") + 1]
        player.move(dest)
    elif "pick" in statement:
        objects = item - set(statement)
        player.pick(item)
    elif "talk" in statement:
        player.talk()
    else:
        console("No, I don't understand that command, try again")
        show_help()
Esempio n. 14
0
def player_move_or_attack(dx, dy):
    """Figures out if the player is moving or attacking"""
    global fov_recompute
    global game_state

    game_state = 'playing'

    x = player.x + dx
    y = player.y + dy

    target = None
    for obj in objects:
        if obj.fighter and obj.x == x and obj.y == y:
            if obj != player:
                target = obj
            break

    if target is not None:
        player.fighter.attack(target)
    else:
        player.move(dx, dy)
        fov_recompute = True
Esempio n. 15
0
    def play_game(self, Q_VALUES_1, Q_VALUES_2):
        tk = Tk()
        canvas = Canvas(tk, width=window_size + 200, height=window_size)
        canvas.grid(row=0, column=0)

        player1_turn = True
        q_val = 0

        exists_winner = True

        def update():
            display(canvas, self.state, q_val)
            tk.update()
            sleep(sleep_time)

        print("---\nGame Start")

        while not self.state.is_game_over():
            previous_state = self.state
            if player1_turn:
                (self.state, self.move_info), q_val = player1.move(
                    True, self.state, Q_VALUES_1)
                player1_turn = False
            else:
                (self.state, self.move_info), q_val = player2.move(
                    False, self.state, Q_VALUES_2)
                player1_turn = True
            if ENABLE_GUI:
                update()
            if (clock() - self.start_time) > (sleep_time * 160):
                exists_winner = False
                break
        display(canvas, self.state, q_val)
        winner = "no winner"
        if exists_winner:
            winner = self.state.get_winner()
        canvas.create_text(window_size + 100, 20,
                           text="Winner: " + winner)
        print("Winner: " + winner)
Esempio n. 16
0
def Main():
    while True:
        for event in pi.event.get():
            if event.type == pi.QUIT():
                pi.quit()
                exit()
            if event.type == pi.KEYDOWN:
                if event.key == pi.K_SPACE:
                    player.jump()
                if event.key == pi.K_d:
                    player.right = True
                if event.key == pi.K_a:
                    player.left = True
            if event.type == pi.KEYUP:
                if event.key == pi.K_d:
                    player.right = False
                if event.key == pi.K_a:
                    player.left = False

        player.move()

        if player.jumping > 0:
            player.jump()
Esempio n. 17
0
    def moveUser(self, key):
        player = self.players.sprites()[0]
        gridX = player.gridX
        gridY = player.gridY

        if key == pygame.K_w:
            if not self.cells[self.cellIndex(gridX, gridY)].walls[0]:
                player.move("n")
        elif key == pygame.K_d:
            if not self.cells[self.cellIndex(gridX, gridY)].walls[1]:
                player.move("e")
        elif key == pygame.K_s:
            if not self.cells[self.cellIndex(gridX, gridY)].walls[2]:
                player.move("s")
        elif key == pygame.K_a:
            if not self.cells[self.cellIndex(gridX, gridY)].walls[3]:
                player.move("w")
Esempio n. 18
0
    def test_move_validity(self):

        current_player = 'g'
        pos1 = [8, 1] 
        pos2 = [8, 13]
        board = [['#','#','#','#','#','#','#','#','#','#','#','#','#','#','#'], 
                ['#','-','-','-','-','-','-','-','-','-','-','-','-','-','#'],
                ['#','-','-','-','-','-','-','-','-','-','-','-','-','-','#'],
                ['#','-','-','-','-','-','-','-','-','-','-','-','-','-','#'],
                ['#','-','-','-','-','-','-','-','-','-','-','-','-','-','#'],
                ['#','-','-','-','-','-','-','-','-','-','-','-','-','-','#'],
                ['#','-','-','-','-','-','-','-','-','-','-','-','-','-','#'],
                ['#','r','-','-','-','-','-','-','-','-','-','-','-','g','#'],
                ['#','r','-','-','-','-','-','-','-','-','-','-','-','g','#'],
                ['#','-','-','-','-','-','-','-','-','-','-','-','-','-','#'],
                ['#','-','-','-','-','-','-','-','-','-','-','-','-','-','#'],
                ['#','-','-','-','-','-','-','-','-','-','-','-','-','-','#'],
                ['#','-','-','-','-','-','-','-','-','-','-','-','-','-','#'],
                ['#','-','-','-','-','-','-','-','-','-','-','-','-','-','#'],
                ['#','#','#','#','#','#','#','#','#','#','#','#','#','#','#']]
    
        best_move = move(current_player, 'r', 'g', pos1, pos2, board)
        self.assertTrue(best_move != "RIGHT", msg=("Terrible move bro"))
Esempio n. 19
0
    # Set screen colour as yellow
    screen.fill(BACKGROUND)

    # Display player wealth, time elapsed and current level on the screen
    screen_manager.display_wealth_time_and_level(time_elapsed, level)

    # Place player, grass, enemies, barriers and coins on the screen
    screen.blit(player.image, (player.x, player.y))
    screen.blit(grass.image, (grass.x, grass.y))
    enemy_manager.draw(enemies)
    barrier_manager.draw(barriers)
    coin_manager.draw(coins)

    # Move the player
    player.move(barriers)

    # Update what is shown on the screen
    pygame.display.update()

    # Check if the player reaches a coin
    coin_manager.player_has_reached(coins)

    # Check if the player reaches an enemy
    if enemy_manager.player_has_reached(enemies):
        time_elapsed += 5

    # Increment the time elapsed each second
    if (start_time + 1) <= int(round(time.time())):
        time_elapsed += 1
        start_time = int(round(time.time()))
Esempio n. 20
0
    def gameLoop(self):
        
        tab_bombs      = []
        tab_chests     = []
        tab_explosion  = []
        tab_extras     = []
        tmp_map        = []
        direction      = 0
        newStr         = ''
        bomb_explosion = True
        
        pygame.mouse.set_visible( 0 )
   
        self.readyTime( self.image, [ self.center_map_x,self.center_map_y ] )
        
        avatar_path  =  self.p1 + '/avatar_min.gif'
        avatar2_path =  self.p2 + '/avatar_min.gif'
        
        for y, line in enumerate( self.mapa ):
            for x, key in enumerate( line ):
                if key == '#':
                    chest = items.Chest( x, y, self.center_map_x, self.center_map_y, self.path, WINDOW )
                    tab_chests.append( chest )
                    
        pygame.mixer.music.load('res/sounds/bgfightsound2.mp3')
        pygame.mixer.music.play(-1, 3.0)
        
        while 1:
            
            WINDOW.blit( self.hud.update( self.tab_players ), ( 0, 0 ) )
            for event in pygame.event.get():
                if event.type == KEYDOWN and event.key == K_ESCAPE or event.type == QUIT:
                    
                    x = self.pause( self.image, [ self.center_map_x, self.center_map_y ] )
                    if x == 2:
                        menu.optionsMenu()
                        for i, player in enumerate( self.tab_players ):
                            player.updateKeys( menu.tab_keys[ 0 + 5 * i : 5 + 5 * i ] )
                            
                    if x == 3:
                        self.option = 0
                        return 0
                    
                    elif x == 4: exitGame()
                    
            
            for player in self.tab_players:
                
                key = pygame.key.get_pressed()
              
                if    key[ player.key_right ] and key[ player.key_up   ]: player.move( 1,-1,  player.speed, self.walls, tab_chests, tab_bombs )
                elif  key[ player.key_left  ] and key[ player.key_up   ]: player.move(-1,-1,  player.speed, self.walls, tab_chests, tab_bombs )
                elif  key[ player.key_right ] and key[ player.key_down ]: player.move( 1, 1,  player.speed, self.walls, tab_chests, tab_bombs )
                elif  key[ player.key_left  ] and key[ player.key_down ]: player.move(-1, 1,  player.speed, self.walls, tab_chests, tab_bombs )
                elif  key[ player.key_right ]:
                    player.move(  1, 0, player.speed, self.walls, tab_chests, tab_bombs )
                    direction = 2
                    
                elif  key[ player.key_left  ]:
                    player.move( -1, 0, player.speed, self.walls, tab_chests, tab_bombs )
                    direction = 0
                    
                elif  key[player.key_up]:
                    player.move( 0, -1, player.speed, self.walls, tab_chests, tab_bombs )
                    direction = 3
                    
                elif  key[player.key_down]:
                    player.move( 0,  1, player.speed, self.walls, tab_chests, tab_bombs )
                    direction = 1
                    
                elif  not ( player.image in ( player.stand ) ): player.image = player.stand[ direction ]
                
                if key[ player.key_use ] and player.counter_bomb < player.bombs and player.min_rect.collidelist( tab_bombs ) == -1:
                    bomb = bombs.Bomb( player.x, player.y, player.speed_exp_bomb, player.range, self.tab_players.index( player ), WINDOW )
                    tab_bombs.append( bomb )
                    player.counter_bomb += 1
                        
            WINDOW.blit( self.image,( self.center_map_x, self.center_map_y ) )

            for chest in tab_chests:
                chest.update()
                for explosion in tab_explosion: 
                    if not chest.rect.collidelist( explosion.tab_rect ) == -1:
                        try:
                            tab_chests.remove( chest )
                            if random.choice( [ 1, 0, 0, 0 ] ) == 1:
                                extras = items.Extras( chest.x, chest.y, WINDOW )
                                tab_extras.append( extras )
                        except ValueError:
                            continue
                        
                        for y, line in enumerate( self.mapa ):
                            if y == chest.tab_y:    
                                for x, key in enumerate( line ):
                                    if x == chest.tab_x and y == chest.tab_y:
                                        newStr += '0'
                                    else:
                                        newStr += key
                                break
                            
                        self.mapa[ chest.tab_y ] = newStr
                        newStr = ''
                
            for bomb in tab_bombs:
                bomb.update()
                if bomb.rect.collidelist( self.tab_players ) == -1 and bomb.set == False:
                    bomb.set = True
                
                if bomb.explosion:
                    explosion = explosions.Explosion( bomb.x, bomb.y, bomb.range, self.mapa, WINDOW )
                    tab_explosion.append( explosion )
                    tab_bombs.remove( bomb )
                    
                    try:
                        if   bomb.player == 0: self.tab_players[ 0 ].counter_bomb -= 1
                        elif bomb.player == 1: self.tab_players[ 1 ].counter_bomb -= 1
                    except IndexError:
                        continue
                    
                for explosion in tab_explosion:
                    if not bomb.rect.collidelist( explosion.tab_rect ) == -1:
                        bomb.time = 0
           
            
            for i, player in enumerate( self.tab_players ):
                WINDOW.blit( player.image, ( player.x-2, player.y-5 ) )
                if  player.life == 0:
                    player.life =  2
                    for j, player in enumerate( self.tab_players ):
                        if player.life == 1:
                            _score[j] += 1
                    pygame.mixer.music.fadeout( 1400 )
                    time.sleep( 1 )
                    x = self.endRound(self.image, [ self.center_map_x, self.center_map_y ], self.tab_players )
                    self.option = x
                    return 0
                    
            for extras in tab_extras:
                extras.update()
                for player in self.tab_players:      
                    if player.rect.colliderect(extras.rect):
            
                        if    0 <= extras.choice <= 29 and player.range <= player.max_range: player.range += 1
                        elif 30 <= extras.choice <= 59 and player.speed <= player.max_speed: player.speed += 0.1
                        elif 60 <= extras.choice <= 84 and player.bombs <= player.max_bombs: player.bombs += 1
                        elif 85 <= extras.choice <= 89 :   player.buf_immortal = True
                        elif 90 <= extras.choice <= 100:   player.life = 0
                        tab_extras.remove( extras )
                        
            for explosion in tab_explosion:
                explosion.update( 1 )
                
                for player in self.tab_players:      
                    if not player.rect.collidelist( explosion.tab_rect ) == -1 and player.buf_immortal == False:
                        player.life = 0
                for extra in tab_extras:
                    if not  extra.rect.collidelist( explosion.tab_rect ) == -1 and extra.time_spawn == 0:
                        tab_extras.remove( extra ) 
                if explosion.exp_time:
                    tab_explosion.remove( explosion )
       
            pygame.display.flip()
            CLOCK.tick(60)
Esempio n. 21
0
done = False

player = player.Player()
while not done:
    constants.display_surface.blit(background, (0, 0))
    if state == 0:
        battle.battle_gui('dingo')
        camera.camera_movement(camera.camera(player, temp), player, temp)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                done = True

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    player.move("left")
                elif event.key == pygame.K_RIGHT:
                    player.move("right")
                elif event.key == pygame.K_UP:
                    player.move("up")
                elif event.key == pygame.K_DOWN:
                    player.move("down")
                elif event.key == pygame.K_p:
                    menus.pause()
                elif event.key == pygame.K_w:
                    done = True

            if event.type == pygame.KEYUP:
                if event.key == pygame.K_LEFT:
                    player.stop("left")
                elif event.key == pygame.K_RIGHT:
Esempio n. 22
0
def levelTwo():

    global currentLevel
    
    #Defining the color white to be used later
    BACKGROUNDCOLOR = (0, 0, 255)
    
    player.rect.x = 24
    player.rect.y = 24
    
    #Creating object     to test tiles 
    print (currentLevel)             
    tileTest = tile(0, 0, 23 , 23, 0, 0, "tileSheet") 
    tileTest.loadTiles() #Loading information for tiles/walls

    #Setting the width and height of the screen before creating the 
    #screen surface
    SCREEN_X = 500
    SCREEN_Y = 500
    SIZE = (SCREEN_X, SCREEN_Y)
    screen = pygame.display.set_mode(SIZE)
    
    #Setting the text to be displayed at the top of the pygame_cal window
    pygame.display.set_caption("Level Two Title")


    done = False
    while not done:
    
        controls()
        
        screen.fill(BACKGROUNDCOLOR)
        
        player.move(level_walls)
        level_tiles.draw(screen) 
        level_walls.draw(screen)
        player_sprite.draw(screen)
        player_sprite.update()
    
        pygame.display.flip()
        
        #Victory conditions for level
        if player.rect.x >= 399 and player.rect.y >= 169:
            print ("yay")
            
            #Empty all levels/tile groups from this level
            #Then remove them from the screen/game surface
            level_tiles.empty()
            level_tiles.remove()
            level_walls.empty()
            level_walls.remove()
            pygame.display.flip() #Update change
            
            #Sets the next level
            currentLevel = 3
            
            #Loads the next level and quits/exits current one
            levelThree()
            pygame.quit()
            
        clock.tick(60)
Esempio n. 23
0
def levelOne():
    
    #Keeps track of current Level
    global currentLevel
    
    #Defining the color to be used "behind" the tiles
    BACKGROUNDCOLOR = (255,255,255)
    
    #Creating object to test tiles                
    tileTest = tile(0, 0, 23 , 23, 0, 0, "tileSheet") 
    tileTest.loadTiles() #Loading information for tiles/walls
    
    #Setting the width and height of the the current level 
    SCREEN_X = 500
    SCREEN_Y = 500
    SIZE = (SCREEN_X, SCREEN_Y)
    screen = pygame.display.set_mode(SIZE)
    
    #Setting the text to be displayed at the top of the pygame_cal window
    pygame.display.set_caption("Level One Title")


    done = False
    while not done:
    
        controls()
        
        #Setting the background of the screen (as white)
        screen.fill(BACKGROUNDCOLOR)
    
        #Setting which tiles will be the player's walls
        player.move(level_walls)
        
        """Actually drawing the walls and tiles on-screen.
        Unlike the player, they do not need to be updated because
        they are static and do not change throught the entirety of 
        a level """
        level_tiles.draw(screen) 
        level_walls.draw(screen)
    
        #Drawing and updating the player
        player_sprite.draw(screen)
        player_sprite.update() #Update is required to "move"
    
  
        #Updates/applies changes the game window/screen surface
        pygame.display.flip()
        
        #Victory conditions for level
        if player.rect.x >= 399 and player.rect.y >= 169:
            print ("yay")
            
            #Empty all levels/tile groups from this level
            #Then remove them from the screen/game surface
            level_tiles.empty()
            level_tiles.remove()
            level_walls.empty()
            level_walls.remove()
            pygame.display.flip() #Update change
            
            #Sets the next level
            currentLevel = 2
            
            #Loads the next level and quits/exits current one
            levelTwo()
            pygame.quit()
            
    
        #Setting FPS for the games
        clock.tick(60)
Esempio n. 24
0
def forwardMove(player, time_delta, holding):
    forwardKeys = [0, 0, 0, 0]
    normal = 0
    up = 0
    down = 0
    dx = ball1.x - player.x
    dy = ball1.y - player.y
    distance = math.hypot(dx, dy)
    if distance < 60:
        normal = 1
    randomMove = random.randint(0, 5)
    if ball1.x <= 210:
        if ball1.y < 200:
            if player.y < 175:
                if player.x < 205:
                    normal = 1
                elif player.x > ball1.x:
                    forwardKeys[2] = 1
                    if randomMove == 1:
                        forwardKeys[0] = 1
                    if randomMove == 3:
                        forwardKeys[1] = 1
                else:
                    forwardKeys[3] = 1
                    if randomMove == 1:
                        forwardKeys[0] = 1
                    if randomMove == 3:
                        forwardKeys[1] = 1
            elif player.y > 425:
                if player.x > 412:
                    forwardKeys[0] = 1
                    forwardKeys[2] = 1
                elif player.x > 205:
                    forwardKeys[0] = 1
                    if randomMove == 2:
                        forwardKeys[2] = 1
                elif player.x > 40:
                    forwardKeys[2] = 1
                    if randomMove == 1:
                        forwardKeys[0] = 1
                else:
                    forwardKeys[0] = 1
            else:
                forwardKeys[0] = 1
                if randomMove == 3:
                    forwardKeys[1] = 1
        elif ball1.y > 373:
            if player.y > 425:
                if player.x < 205:
                    normal = 1
                elif player.x > ball1.x:
                    forwardKeys[2] = 1
                    if randomMove == 1:
                        forwardKeys[1] = 1
                    if randomMove == 3:
                        forwardKeys[0] = 1
                else:
                    forwardKeys[3] = 1
                    if randomMove == 1:
                        forwardKeys[1] = 1
                    if randomMove == 3:
                        forwardKeys[0] = 1
            elif player.y < 175:
                if player.x > 412:
                    forwardKeys[1] = 1
                    forwardKeys[2] = 1
                elif player.x > 205:
                    forwardKeys[1] = 1
                elif player.x > 40:
                    forwardKeys[2] = 1
                else:
                    forwardKeys[1] = 1
            else:
                forwardKeys[1] = 1
        else:
            if player.x > 350:
                forwardKeys[2] = 1
            elif player.x > 205:
                if player.y < 175 or player.y > 425:
                    forwardKeys[2] = 1
                else:
                    if player.y > ball1.y:
                        forwardKeys[0] = 1
                    else:
                        forwardKeys[1] = 1
            elif player.x > 30:
                forwardKeys[2] = 1
                if randomMove == 3:
                    forwardKeys[1] = 1
            else:
                if player.y > ball1.y:
                    forwardKeys[0] = 1
                    if randomMove == 2:
                        forwardKeys[0] = 0
                        forwardKeys[1] = 1
                else:
                    forwardKeys[1] = 1
                    if randomMove == 2:
                        forwardKeys[1] = 0
                        forwardKeys[0] = 1

    elif ball1.x <= 780:
        if player.x <= 780 and player.x >= 205:
            if player.y <= 155 and ball1.y <= 205 and ball1.x > player.x:
                normal = 1
                up = 1
            elif player.y >= 450 and ball1.y >= 450 and ball1.x > player.x:
                normal = 1
                down = 1
            else:
                normal = 1
        elif player.x < 205:
            if player.y < 120:
                forwardKeys[3] = 1
            elif player.y < 300:
                forwardKeys[0] = 1
            elif player.y < 440:
                forwardKeys[1] = 1
            else:
                forwardKeys[3] = 1
        else:
            if player.y < 205 or player.y > 373:
                forwardKeys[2] = 1
    else:
        if holding == 0:
            if player.x < 610:
                forwardKeys[3] = 1
            elif player.x < 720:
                if ball1.y < 210 and player.y < 175:
                    forwardKeys[0] = 1
                elif ball1.y > 373 and player.y > 425:
                    forwardKeys[1] = 1
                elif ball1.y > player.y:
                    forwardKeys[1] = 1
                elif ball1.y < player.y:
                    forwardKeys[0] = 1
            if player.x > 620:
                forwardKeys[2] = 1

    if player.x > 780:
        normal = 0
    if normal:
        forwardKeys = [0, 0, 0, 0]
        if ball1.x - 30 < player.x:
            forwardKeys[2] = 1
        if ball1.x - 30 > player.x:
            forwardKeys[3] = 1
        if ball1.y - 30 > player.y:
            forwardKeys[1] = 1
        if ball1.y - 30 < player.y:
            forwardKeys[0] = 1
    if up:
        forwardKeys[0] = 1
        forwardKeys[1] = 0
    if down:
        forwardKeys[1] = 1
        forwardKeys[0] = 0

    player.move(forwardKeys[0], forwardKeys[1], forwardKeys[2], forwardKeys[3],
                time_delta)
Esempio n. 25
0
attic.set_item(items.SmallPotion)

roof.set_default_exits(None, None, None, None, None, attic)

basement.set_default_exits(None, None, None, None, staircase, None)

############################################################################################

#Start game
functions.print_home()
functions.press_enter()

functions.print_controlls()
functions.press_enter()

player.move(2)

# Player needs to fine the Black Rose and go to the attic to trigger the first event, which then opens the secret room 1..
while True:
    if player.get_room() is attic and BlackRose in player.get_inventory():
        break
    player.p_input()

functions.clear()
print("Hmm, something is different in here..")
time.sleep(3)
print("You see a writing on the wall.")
time.sleep(3)
print(
    """As you get closer, you can finally see, that the writing says: "why?" """
)
Esempio n. 26
0
DISPLAYSURF = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption('AGDQ Game Jam!')

player = player.Player(DISPLAYSURF)
bullets = []
enemies = []

start = False
while True:
    DISPLAYSURF.fill(BLACK)

    keys = pygame.key.get_pressed()
    if keys[K_UP]:
        bullets.append(bullet.Bullet(DISPLAYSURF, player, UP))
    elif keys[K_w]:
        player.move(UP)
    elif keys[K_DOWN]:
        bullets.append(bullet.Bullet(DISPLAYSURF, player, DOWN))
    elif keys[K_s]:
        player.move(DOWN)
    elif keys[K_LEFT]:
        bullets.append(bullet.Bullet(DISPLAYSURF, player, LEFT))
    elif keys[K_a]:
        player.move(LEFT)
    elif keys[K_RIGHT]:
        bullets.append(bullet.Bullet(DISPLAYSURF, player, RIGHT))
    elif keys[K_d]:
        player.move(RIGHT)
    elif keys[K_RETURN]:
        start = True
Esempio n. 27
0
import turtle
import player

wn = turtle.Screen()
wn.bgcolor("red")

playerImg = "saucer.gif"
wn.register_shape(playerImg)

player = player.Player(playerImg)

## wn.onkey(functionName, "key")
wn.onkey(player.goLeft, "Left")
wn.onkey(player.goRight, "Right")
wn.onkey(player.speedUpSlowPoke, "Up")
wn.onkey(player.slowYourRoll, "Down")

while True:
    player.move()
Esempio n. 28
0
font = pygame.font.Font(None, SCALE)
game = Game(font, updateList)
clock = pygame.time.Clock()
startTime = pygame.time.get_ticks()


running = True
#MAIN LOOP
while True:
	keys = pygame.key.get_pressed()
	# WHILE PLAYING THE GAME
	if running == True:
		#KEYPRESSES
		#PLAYER: CHANGE LANES
		if keys[pygame.K_UP]:
			player.move(0)		
		if keys[pygame.K_DOWN]:
			player.move(2)
		if (not keys[pygame.K_UP]) and (not keys[pygame.K_DOWN]):
			player.move(1)
		#PLAYER: CHANGE X
		if keys[pygame.K_SPACE]:
			player.jumping = True
			player.x = SCALE * 2
	
		#PLAYER: OTHER
		player.jump()
		player.checkHealth()
		#LEVEL RELATED
		game.changeDelay()
		game.randomLevel(level)
Esempio n. 29
0
symbolDict[0] = " "  #default case is empty box being a space


#function to check if the game is over
def isGameOver(board):
    return board.horizontalScore() or board.verticalScore(
    ) or board.diagonalScore()


while moves < area and not isGameOver(playingBoard):
    #player makes their move
    for player in players:
        if player.isTurn:
            print("It is {}\'s turn.".format(player.name))
            playingBoard.render(symbolDict)
            player.move(playingBoard)
            moves += 1
            player.isTurn = not player.isTurn
        else:
            player.isTurn = not player.isTurn

    #program checks if one player is victorious
    if isGameOver(playingBoard):
        winnerID = playingBoard.winner
        for player in players:
            if player.id == winnerID:
                print("Congratulations, {}! You have won the game!".format(
                    player.name))

        break
    elif moves == area:
Esempio n. 30
0
def gameLoop():

    # initialize exit condition
    game = True
    # user inputs
    press_W = False
    press_S = False
    press_A = False
    press_D = False
    press_left = False
    press_right = False
    press_up = False
    # Variables for display
    Round = 1
    score = 0
    # List of bullet instances
    bullets = []

    # game loop
    while game:
        # resets movement inputs so player stops when there is no input.
        x = 0
        y = 0
        # variables to be drawn on display
        scoreTxt = myfont.render('Score: ', False, grey)
        scoreNum = myfont.render((str(score)), False, grey)
        roundTxt = myfont.render('Round: ', False, grey)
        roundNum = myfont.render((str(Round)), False, grey)
        # Collects user inputs and exit condition.
        for event in pygame.event.get():
            if (event.type == pygame.QUIT
                ):  # exit condition / X button in corner
                game = False
            # Checks for key presses from 'W' 'A' 'S' 'D' and arrow keys.
            elif ((event.type == pygame.KEYDOWN)
                  and (event.key == pygame.K_w)):
                press_W = True
            elif ((event.type == pygame.KEYUP) and (event.key == pygame.K_w)):
                press_W = False
            elif ((event.type == pygame.KEYDOWN)
                  and (event.key == pygame.K_s)):
                press_S = True
            elif ((event.type == pygame.KEYUP) and (event.key == pygame.K_s)):
                press_S = False
            elif ((event.type == pygame.KEYDOWN)
                  and (event.key == pygame.K_a)):
                press_A = True
            elif ((event.type == pygame.KEYUP) and (event.key == pygame.K_a)):
                press_A = False
            elif ((event.type == pygame.KEYDOWN)
                  and (event.key == pygame.K_d)):
                press_D = True
            elif ((event.type == pygame.KEYUP) and (event.key == pygame.K_d)):
                press_D = False
            elif ((event.type == pygame.KEYDOWN)
                  and (event.key == pygame.K_LEFT)):
                press_left = True
            elif ((event.type == pygame.KEYUP)
                  and (event.key == pygame.K_LEFT)):
                press_left = False
            elif ((event.type == pygame.KEYDOWN)
                  and (event.key == pygame.K_RIGHT)):
                press_right = True
            elif ((event.type == pygame.KEYUP)
                  and (event.key == pygame.K_RIGHT)):
                press_right = False
            elif ((event.type == pygame.KEYDOWN)
                  and (event.key == pygame.K_UP)):
                press_up = True
            elif ((event.type == pygame.KEYUP) and (event.key == pygame.K_UP)):
                press_up = False

        # These inputs change player location
        if (press_W):
            y -= 3
        elif (press_S):
            y += 3
        if (press_A):
            x -= 3
        elif (press_D):
            x += 3
        player.move(x, y)

        # These inputs rotate the player.
        if (press_left):
            player.turnLeft()
        elif (press_right):
            player.turnRight()
        # Up arrow fires bullets. (because the spacebar felt to awkward)
        if (press_up) and player.health != 0:
            bullets.append(
                bullet.Bullet(player.oriX, player.oriY, player.locX,
                              player.locY))
        # Delete bullets after they have moved 60 times
        if len(bullets) > 0:
            for x in range(len(bullets)):
                bullets[x].move()
                if (bullets[x].count > 60):
                    remove = bullets[x]
                    del bullets[x]
                    remove.kill()
                    break
        # Stop inputs if player dies.
        if player.collision(enemies):
            player.health = 0
        # If bullets hit enemies, enemies die.
        if (len(enemies) > 0):
            for x in range(len(enemies)):
                enemies[x].move(player.locX, player.locY)
            for x in range(len(enemies)):
                for b in range(len(bullets)):
                    if (math.sqrt((abs(bullets[b].x - enemies[x].x)**2) +
                                  abs(bullets[b].y - enemies[x].y)**2) < 10):
                        score += 1
                        remove = enemies[x]
                        del enemies[x]
                        remove.kill()
                        break
                break
        # If all the enemies are dead increase
        # round by 1 and add more enemies.
        elif (len(enemies) < 1):
            nextRound(Round, enemies)
            Round += 1

        # Draw everything.
        DISPLAYSURF.fill(black)  # Draw new background
        DISPLAYSURF.blit(scoreTxt, (5, 5))  # Draw score
        DISPLAYSURF.blit(scoreNum, (100, 5))
        DISPLAYSURF.blit(roundTxt, (5, 55))  # Draw round
        DISPLAYSURF.blit(roundNum, (100, 55))
        if len(bullets) > 0:  # Draw all the bullets.
            for x in range(len(bullets)):
                bullets[x].draw(DISPLAYSURF)
        if len(enemies) > 0:  # Draw all the enemies.
            for x in range(len(enemies)):
                enemies[x].draw(DISPLAYSURF)
        player.draw(DISPLAYSURF)  # Draw the player.
        pygame.display.update()
        FPS.tick(45)  # Refresh rate.
Esempio n. 31
0
Grid = ['', '', '', '', '', '', '', '', '']

MoveHistory = ''
PlayerHistory = ''
COMHistory = ''
# Data is of the winning positions

while endGame.PlayAgain:
    currentPath = ''
    COMHistory = ''
    PlayerHistory = ''
    GameOver = False
    Grid = startGame.StartGame(Grid)
    EmptyFile, Data = startGame.GetWinningPositions()
    display.ShowGrid(Grid)
    while not GameOver:
        PlayerHistory = player.move(PlayerHistory, Grid)
        GameOver = endGame.HasGameEnded(Grid, GameOver)
        print(GameOver)
        if not GameOver:
            COMHistory = computer.COMMove2(COMHistory, EmptyFile, Grid, Data)
        GameOver = endGame.HasGameEnded(Grid, GameOver)
        display.ShowGrid(Grid)

    MoveHistory = COMHistory + '-' + PlayerHistory
    endGame.GameOverMessage()
    endGame.StoreDetails(GameOver, MoveHistory, EmptyFile)

    endGame.PlayAgain = endGame.newGame()
Esempio n. 32
0
def goalieMove(player, time_delta, team1, team2):
    if ball1.y - 30 < player.y and player.y > 228:
        player.move(1, 0, 0, 0, time_delta)
    if ball1.y - 30 > player.y and player.y < 348:
        player.move(0, 1, 0, 0, time_delta)
    if team1 and ball1.x > 662 and player.x < player.initX + 100:
        player.move(0, 0, 0, 1, time_delta)
    if team2 and ball1.x < 362 and player.x > player.initX - 100:
        player.move(0, 0, 1, 0, time_delta)
    if team1 and ball1.x < 662 and player.x > player.initX:
        player.move(0, 0, 1, 0, time_delta)
    if team2 and ball1.x > 362 and player.x < player.initX:
        player.move(0, 0, 0, 1, time_delta)
Esempio n. 33
0
def main():

	walk = False
	a_shot = False
	numzomb = 10 
	cont_zomb = 10
	end = False
	pygame.mixer.init()
	level = 1
	bala = pygame.rect.Rect((0,0), (5,5))
	zsound = pygame.mixer.Sound("sound_data/zombies.wav")
	
	while not end:
		vx,vy = 0,0

		for event in pygame.event.get():
			
			if event.type == pygame.QUIT:sys.exit(0)

			keys = pygame.key.get_pressed()

			if keys[K_ESCAPE]:sys.exit(0)
			if keys[K_w]:vy = -speed
			if keys[K_s]:vy = speed
			if keys[K_a]:vx = -speed
			if keys[K_d]:vx = speed

			if keys[K_SPACE]:
				pygame.mixer.music.load("sound_data/shot.wav")
				pygame.mixer.music.play()
				pos = player.pos()
				a_shot = True
				for i in range (0,20):
					bala = pygame.rect.Rect((0,0), (5,5))
					bala.left = pos[2] - 10
					bala.top = pos[1] - 10
					bala.right = pos[3] - 10

		player.move(vx,vy)
		background = load("background.png",0,0)
		vel = { }
		for i in range(0,numzomb):
			vel[i] = random.randrange(0,2)
			screen.blit(zombie_img, cantzomb[i])
			if player.col(cantzomb[i]):
				handle('lose', level, numzomb)
				end = True
			if bala.colliderect(cantzomb[i]):
				cantzomb[i].inflate_ip(-99999,-999999)
				cont_zomb -= 1
			if cantzomb[i].bottom >= HEIGHT:
				handle('lose', level, numzomb)
				end = True
			if cont_zomb <= 0:
				handle('win', level, numzomb)
				level += 1			
				numzomb += 2
				add_zombies(cantzomb,zombie_img, numzomb)
				cont_zomb = numzomb
			cantzomb[i].move_ip(0, vel[i])
		
		if numzomb > 0:	zsound.play()

   		if a_shot:
			bala.top -= 15
			pygame.draw.rect(screen, (255,255,255), bala)
		

		kills = numzomb - cont_zomb
		fps = str(clock.get_time())
		time = fps.split(".")[0]
		player.hud(screen,kills,level,time,numzomb)
		player.update(screen,walk)
		pygame.display.flip()
		clock.tick(70)
		pos = player.pos()

	sys.exit()
Esempio n. 34
0
                 currentMoment = GAME_TIME.get_ticks()
             elif princess == 2:
                 selector = pygame.image.load(
                     "assets/titleScreens/selector3(1).png")
                 princess = 1
                 currentMoment = GAME_TIME.get_ticks()
     surface.blit(selector, (173, 0))
 if combat:
     if roundFinished or triforceWaiting:
         surface.fill((0, 0, 0))
     else:
         surface.blit(battleField, (0, 0))
     for idx, player in enumerate(playersFighting):
         player.atackMoment(GAME_TIME)
         player.drawLives(surface)
         player.move(GAME_TIME)
         player.drawSword(surface)
         player.drawPlayer(surface, GAME_TIME, roundFinished)
         if idx == 1:
             otherPlayerIndex = 0
         else:
             otherPlayerIndex = 1
         player.receiveArrow(playersFighting[otherPlayerIndex])
         if player.imDead():
             roundFinished = True
             player.stop('True')
             if triforceWaiting == 0:
                 triforceWaiting = 1
         if roundFinished == True and player.imDead() == False:
             player.stop('True')
             if triforceWaiting == 1 and roundFinished:
Esempio n. 35
0
 wui = 0
 # enemy actions
 for enemy in enemy_manager.enemies:
     enemy.move()
 try:
     user_input = getch()
 # catches if the user inputs an arrow key or something
 except UnicodeDecodeError as e:
     user_input = ""
     log("Error occured during get_input: {}".format(e))
 # action: quit
 if user_input == 'q':
     playing = False
 # action: move
 elif user_input in move_commands:
     next_room = player.move(user_input)
     # action: change room
     if next_room:
         map.change(next_room)
         player.change_rooms(next_room)
 # action: inspect object
 elif user_input == 'e':
     o = object_manager.search_objects(player)
     if o is None:
         o = enemy_manager.search_enemies(player, map.current_map.name)
     try:
         if o.room == map.current_map.name:
             result = o.get_info(player)
         # if a door is opened
         if result:
             map.delete(result)
Esempio n. 36
0
                              player.hitbox[3])

    if enemy_rect.colliderect(player_rect):
        player.hit(screen)
        enemy.restart_position()


def collision_projectile_enemy():
    enemy_rect = pygame.Rect(enemy.hitbox[0] + enemy.x,
                             enemy.hitbox[1] + enemy.y, enemy.hitbox[2],
                             enemy.hitbox[3])

    if enemy_rect.collidepoint(projectile_motion.x + 25,
                               projectile_motion.y + 25):
        projectile_motion.restart_shoot()
        enemy.hit()


while 1:
    clock.tick(27)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            exit()

    keys = pygame.key.get_pressed()

    projectile_motion.calculate_motion(keys, player)
    player.move(keys, SCREEN_WIDTH)

    redraw_screen()