Пример #1
0
def endScreen(snabe1, snabe2):
    pygame.init()

    #settings object
    snabings = GlobalSettings()
    screen = pygame.display.set_mode((snabings.screen_width, snabings.screen_height))
    screen_rect = screen.get_rect()
    pygame.display.set_caption("Snabe")
    pygame.display.flip()

    while True:
        screen.blit(GlobalSettings().background_title, GlobalSettings().background_title_rect)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE:
                    run_game()
                elif event.key == pygame.K_ESCAPE:
                    startScreen()
        pygame.font.init()

        #########################################################################################
        #       Renders text prompts for end screen                                             #
        #########################################################################################

        #render play again prompy
        myfont = pygame.font.SysFont('Courier', 30)
        restartPrompt = myfont.render('Press Space to Play Again!', False, (0, 0, 0))
        restartRect = restartPrompt.get_rect()
        restartRect.centerx = screen_rect.centerx
        restartRect.centery = screen_rect.centery

        #Render main menu prompt
        myfont = pygame.font.SysFont('Courier', 20)
        menuPrompt = myfont.render('Press Esc to go back to the main menu', False, (0, 0, 0))
        menuRect = menuPrompt.get_rect()
        menuRect.centerx = screen_rect.centerx
        menuRect.top = restartRect.bottom

        #compare snake scores to determine the winner to announce
        if snabe1.score > snabe2.score:
            winner = "Green Wins!"
        elif snabe2.score > snabe1.score:
            winner = "Blue Wins!"
        elif snabe1.score == snabe2.score:
            winner = "It's a tie!"

        #Render winner text
        myfont = pygame.font.SysFont('Courier', 45)
        winnerPrompt = myfont.render(winner, False, (0, 0, 0))
        winnerRect = winnerPrompt.get_rect()
        winnerRect.centerx = screen_rect.centerx
        winnerRect.bottom = restartRect.top

        screen.blit(restartPrompt,restartRect)
        screen.blit(menuPrompt,menuRect)
        screen.blit(winnerPrompt, winnerRect)
        pygame.display.flip()
Пример #2
0
    def __init__(self, screen, int):
        self.screen = screen
        self.screen_rect = screen.get_rect()

        if int > 99:
            self.time = 99
        elif int <= 0:
            self.time = 1
        else:
            self.time = int

        # load timer image and set rect
        try:
            self.timer_body = pygame.image.load("images/timer/timerBody.png")
        except:
            print(
                "Failed to load timer body sprite. Falling back on dummy.bmp")
            self.timer_body = pygame.image.load("images/dummy.bmp")
        finally:
            self.rect = self.timer_body.get_rect()

        self.rect.centerx = self.screen_rect.centerx
        self.rect.bottom = GlobalSettings().play_area_height

        # load image and rect for left digit
        try:
            self.left_digit = pygame.image.load("images/timer/zero.png")
        except:
            print(
                "Failed to load timer left digit sprite. Falling back on dummy.bmp"
            )
            self.left_digit = pygame.image.load("images/dummy.bmp")
        finally:
            self.left_digit_rect = self.left_digit.get_rect()

        # offset the digit to the left side of timer
        self.left_digit_rect.centerx = self.rect.centerx - 15
        self.left_digit_rect.bottom = GlobalSettings(
        ).play_area_height - 10  #self.rect.top + 32

        # load image and rect for right digit
        try:
            self.right_digit = pygame.image.load("images/timer/zero.png")
        except:
            print(
                "Failed to load timer right digit sprite. Falling back on dummy.bmp"
            )
            self.right_digit = pygame.image.load("images/dummy.bmp")
        finally:
            self.right_digit_rect = self.right_digit.get_rect()

        # offset the digit to the right side of timer
        self.right_digit_rect.centerx = self.rect.centerx + 15
        self.right_digit_rect.bottom = GlobalSettings(
        ).play_area_height - 10  #self.rect.top + 32
        self.tick()
Пример #3
0
    def __init__(self, screen, int, side):
        self.screen = screen
        self.screen_rect = screen.get_rect()

        leftDigit_loc = [0, GlobalSettings().play_area_height + -10]
        rightDigit_loc = [0, GlobalSettings().play_area_height + -10]
        if (side == "LEFT"):
            leftDigit_loc[0] = self.screen_rect.left + 15
            rightDigit_loc[0] = leftDigit_loc[0] + 30
        elif (side == "RIGHT"):
            rightDigit_loc[0] = self.screen_rect.right - 45
            leftDigit_loc[0] = rightDigit_loc[0] - 30

        if int > 99:
            self.time = 99
        elif int <= 0:
            self.time = 1
        else:
            self.time = int

        # load image and rect for left digit
        try:
            self.left_digit = pygame.image.load("images/timer/zero.png")
        except:
            print(
                "Failed to load timer left digit sprite. Falling back on dummy.bmp"
            )
            self.left_digit = pygame.image.load("images/dummy.bmp")
        finally:
            self.left_digit_rect = self.left_digit.get_rect()

        #position left digit on screen
        self.left_digit_rect.left = leftDigit_loc[0]
        self.left_digit_rect.bottom = leftDigit_loc[1]

        # load image and rect for right digit
        try:
            self.right_digit = pygame.image.load("images/timer/zero.png")
        except:
            print(
                "Failed to load timer right digit sprite. Falling back on dummy.bmp"
            )
            self.right_digit = pygame.image.load("images/dummy.bmp")
        finally:
            self.right_digit_rect = self.right_digit.get_rect()

        #position right digit on screen
        self.right_digit_rect.left = rightDigit_loc[0]
        self.right_digit_rect.bottom = rightDigit_loc[1]

        self.update(int)
Пример #4
0
    def __init__(self, screen, global_vars):
        self.screen = screen
        self.screen_rect = screen.get_rect()
        self.snabings = GlobalSettings()
        self.gv = global_vars

        #attempts ot load sprite for food
        try:
            self.food_sprite = pygame.image.load("images/items/food.png")
        except:
            print("Failed to load food sprite: falling back on dummy.bmp")
            self.food_sprite = pygame.image.load("images/dummy.bmp")
        finally:
            self.rect = self.food_sprite.get_rect()

        self.chooseLocation()
        self.gv.entities.append(self)
Пример #5
0
    def __init__(self, screen, head, global_vars, segment_number):
        # Useful game elements
        self.screen = screen
        self.screen_rect = self.screen.get_rect()
        self.snabings = GlobalSettings()
        self.gv = global_vars

        # Info and stats
        self.speed = head.speed
        self.head = head
        self.segment_number = segment_number
        self.is_last_segment = self.segment_number == self.head.score

        # store previous segment for future reference
        if self.segment_number == 0:
            self.previous_segment = head
        else:
            self.previous_segment = head.segments[segment_number - 1]
            self.previous_segment.is_last_segment = False

        # movement flags
        self.moving_up = self.previous_segment.moving_up
        self.moving_down = self.previous_segment.moving_down
        self.moving_left = self.previous_segment.moving_left
        self.moving_right = self.previous_segment.moving_right

        # Keeps track of player's last location
        # Given a real value when drawSegment is called for the first time
        self.lastLoc = (0, 0)
        # Keeps track of player's last direction of movement
        self.lastDirection = ""

        # Chooses the segment sprite and creates a rect
        self.drawSegment()

        # Appropriately connects this segment to the previous
        self.connect()

        # Float values for centers, allows us to do math easily
        self.centerx = float(self.rect.centerx)
        self.centery = float(self.rect.centery)

        # Stores segment in the global list
        self.gv.entities.append(self)
Пример #6
0
    def __init__(self, screen, global_vars):
        self.screen = screen
        self.screen_rect = screen.get_rect()
        self.snabings = GlobalSettings()
        self.gv = global_vars

        # default power-up state
        self.power_type = "NONE"
        # assigns power-up state
        self.set_type()

        # Attempts to load wafer image
        try:
            self.food_sprite = pygame.image.load("images/items/wafer.png")
        except:
            print("Failed to load wafer sprite. Falling back on dummy.bmp")
            self.food_sprite = pygame.image.load("images/dummy.bmp")
        finally:
            self.rect = self.food_sprite.get_rect()

        self.chooseLocation()
        self.gv.entities.append(self)
Пример #7
0
def startScreen():
    pygame.init()

    #settings/constants file
    snabings = GlobalSettings()

    screen = pygame.display.set_mode((snabings.screen_width, snabings.screen_height))
    screen_rect = screen.get_rect()
    pygame.display.set_caption("Snabe")

    #used to regulate the animation speed
    clock = pygame.time.Clock()

    #dict that contains the current frame used in the animation and image paths
    snabeSlither = {
        "frame": 1,
        1: "images/menu/snabeSlither1.png",
        2: "images/menu/snabeSlither2.png",
        3: "images/menu/snabeSlither3.png",
        4: "images/menu/snabeSlither4.png",
    }

    # creates the logo object that crawls into view
    # positions logo off screen
    # attempt to load image
    try:
        snabe_logo = pygame.image.load(snabeSlither[snabeSlither["frame"]])
    except:
        print("Failed to load logo sprite: falling back on dummy.bmp")
        snabe_logo = pygame.image.load("images/dummy.bmp")
    finally:
        logo_rect = snabe_logo.get_rect()
        logo_rect.right = screen_rect.left
        logo_rect.centery = snabings.screen_height // 6

    while True:
        #sets gamespeed(animation speed) to 14 FPS
        clock.tick(14)
        screen.blit(GlobalSettings().background_title, GlobalSettings().background_title_rect)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE:
                    run_game()

        #######################################################################
        # Snabe Slither Animation                                             #
        #######################################################################
        #shuffles through current frame and applies them to object
        if snabeSlither["frame"] == 4:
            snabeSlither["frame"] = 1
        else:
            snabeSlither["frame"] += 1
        if logo_rect.centerx >= screen_rect.centerx:
            logo_rect.centerx = screen_rect.centerx
        else:
            logo_rect.centerx += 10
        try:
            snabe_logo = pygame.image.load(snabeSlither[snabeSlither["frame"]])
        except:
            print("Failed to load frame in logo animation: falling back on dummy.bmp")
        finally:
            screen.blit(snabe_logo, logo_rect)
        #######################################################################
        # Renders text prompt to screen                                       #
        #######################################################################
        pygame.font.init()
        myfont = pygame.font.SysFont('Courier', 30)
        startPrompt = myfont.render('Welcome to Snabe! Press Space to Start!',False, (0,0,0))
        startRect = startPrompt.get_rect()
        startRect.centerx = screen_rect.centerx
        startRect.centery = screen_rect.centery
        screen.blit(startPrompt, startRect)

        #updates display
        pygame.display.flip()
Пример #8
0
def run_game():
    pygame.init()

    # Creates instances of global information classes
    snabings = GlobalSettings()
    gv = GlobalVars()
    gf = GlobalFunctions(gv)

    # Sets up the display window
    screen = pygame.display.set_mode((snabings.screen_width, snabings.screen_height))
    pygame.display.set_caption("Snabe")
    pygame.display.set_icon(pygame.image.load("images/menu/snabeSlither4.png"))

    # Creates an instance of the Snabe class for each player
    snabe1 = Snabe(screen, gv, 1)
    snabe2 = Snabe(screen, gv, 2)

    # List of food pellets to be displayed
    gv.food_list.append(Food(screen, gv))
    gv.food_list[0].setLocation(snabings.screen_width//2, snabings.screen_height//2)

    # Timer class object
    game_timer = Timer(screen, snabings.game_length)

    # Score objects
    scoreboard = [Score(screen,snabe1.score, "LEFT"),Score(screen,snabe2.score, "RIGHT")]

    # Established to regulate game speed
    clock = pygame.time.Clock()

    # Global tick rate established in settings.py
    tick_rate = snabings.tick_rate

    # Keeps track of tick counts
    ticks = {
        "initial": gv.timer_value,
        "timer": 0,
        "food": -1,
        "wafer": -1,
    }

    # The game's main loop: repeats until the timer runs out, or one player loses.
    while gv.timer_value != 0 and snabe1.score != 0 and snabe2.score != 0:
        # establishes tick rate for game
        clock.tick(tick_rate)

        gf.check_events(snabe1, snabe2)
        gf.update_screen(screen, game_timer, scoreboard)

        snabe1.update()
        snabe2.update()
        scoreboard[0].update(snabe1.score)
        scoreboard[1].update(snabe2.score)

        ####################################
        # Accounts for the amount of ticks #
        # needed to correctly time actions #
        ####################################
        ticks["timer"]+=1
        if ticks["timer"] == tick_rate:
            game_timer.tick()
            ticks["food"] += 1
            ticks["wafer"] += 1
            ticks["timer"] = 0
            ticks["initial"] = gv.timer_value

        if gv.timer_value >= 1:
            gv.timer_value -= 1
        else:
            gv.timer_value = 0

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

        # this segment is responsible for spawning food
        # every n seconds
        if ticks["food"] == snabings.food_spawn_rate:
            gv.food_list.append((Food(screen, gv)))
            ticks["food"] = 0

        # this segment spawns a power-up wafer
        # every n seconds
        if ticks["wafer"] == snabings.wafer_spawn_rate:
            gv.wafer_list.append(Wafer(screen, gv))
            ticks["wafer"] = 0
    endScreen(snabe1, snabe2)
Пример #9
0
    def __init__(self, screen, global_vars, player_num):
        # Useful game elements
        self.screen = screen
        self.snabings = GlobalSettings()
        self.gv = global_vars
        # Allows us to calculate locations based on the screen edges
        self.screen_rect = screen.get_rect()

        # Adjust screen rect to encompass only the playable area
        self.screen_rect.height = self.snabings.screen_height - self.snabings.play_area_height
        self.screen_rect.top = self.snabings.play_area_height
        self.screen_rect.bottom = self.snabings.screen_height

        #Info and stats
        self.player_num = player_num
        self.speed = self.snabings.base_speed
        self.score = 5  # all players will start with base score of 5

        # Flipped to True when sword powerup is active
        self.canDamage = False
        # Flipped to False while shield powerup is active
        self.isVulnerable = True
        # Flipped to True while canDamage = False and player is colliding with opponent
        self.stunned = False

        # Used when a powerup is activated, stores the time at which it is picked up
        self.power_start_time = -1

        # movement flags
        # only one flag should be "True" at a time: this keeps movement locked to a grid
        self.moving_up = False
        self.moving_down = False
        self.moving_left = False
        self.moving_right = False

        # Keeps track of turning points
        self.turns = dict()

        # Proper sprite and rect are assigned at first call of drawSprite
        # This merely creates the fields for later use
        self.head_sprite = pygame.image.load("images/dummy.bmp")
        self.rect = self.head_sprite.get_rect()

        # Sets initial locations
        # Both will be in the same y plane, but x plane will depend on player_num
        if self.player_num == 1:
            self.rect.centerx = 100
        else:
            self.rect.centerx = self.screen_rect.right - 100
        self.rect.bottom = self.screen_rect.centery

        # Float values for centers, allows us to do math easily
        self.centerx = float(self.rect.centerx)
        self.centery = float(self.rect.centery)

        # Values that help keep track of the head
        # Useful when recovering from a stun
        self.lastLoc = (self.rect.centerx, self.rect.centery)
        self.lastDirection = "UP"

        # Picks the correct sprite for the snabe and creates the rect
        self.drawSnabe()

        # Add head to the global entity list
        self.gv.entities.append(self)

        # Creates a list to keep track of body segments
        self.segments = list()
        # Creates one extra, so the tail is always present
        for x in range(self.score + 1):
            self.segments.append(Body(self.screen, self, self.gv, x))