Ejemplo n.º 1
0
import math
import pygame as pg
from tank import Tank
from bullet import Bullet
from obstacle import Obstacle
from base import Base
from flag import Flag
from scoreboard import Scoreboard
from artificialIntelligence import AI
import gameConsts

pg.init()
screen = gameConsts.screen
selectLast = -gameConsts.SELECT_ADD_TIME  # negative to allow immediate select
selectedTanks = set()
scoreboard = Scoreboard(gameConsts.players)

bg = pg.image.load(gameConsts.MAP_BACKGROUND)
bg = pg.transform.scale(
    bg, (gameConsts.BACKGROUND_SIZE, gameConsts.BACKGROUND_SIZE))


def selectTank(tank):
    global selectLast
    global selectedTanks
    gameTime = pg.time.get_ticks()
    if gameTime - selectLast > gameConsts.SELECT_ADD_TIME:
        selectLast = gameTime
        for t in selectedTanks:
            t.unselect()
        selectedTanks.clear()
Ejemplo n.º 2
0
def move(screen, x, image1, rect1, image2, rect2, grid):
    pygame.key.set_repeat(200, 50)
    count = 0
    scoreboard = Scoreboard(screen, count)
    move_right = False
    move_left = False
    move_up = False
    move_down = False
    rect1.center = [grid + (grid / 2), grid + (grid / 2)]

    while True:

        screen_init.screen_init(screen, image2, rect2, x, grid)

        # 画出发点和终点
        pygame.draw.rect(screen, [0, 0, 255], [grid, grid, grid, grid], 0)
        pygame.draw.rect(
            screen, [255, 0, 0],
            [grid * (x.shape[1] - 2), grid * (x.shape[0] - 2), grid, grid], 0)

        # 判定撞墙
        if x[int((rect1.centery - (grid / 2)) / grid)][int(
            (rect1.centerx + (grid / 2)) / grid)] == 1:  # 右
            move_right = False

        if x[int((rect1.centery - (grid / 2)) / grid)][int(
            (rect1.centerx - (grid / 2)) / grid)] == 1:  # 左
            move_left = False

        if x[int((rect1.centery - (grid / 2)) / grid)][int(
            (rect1.centerx - (grid / 2)) / grid)] == 1:  # 上
            move_up = False

        if x[int((rect1.centery + (grid / 2)) / grid)][int(
            (rect1.centerx - (grid / 2)) / grid)] == 1:  # 下
            move_down = False

        count = move_update(rect1, move_right, move_left, move_up, move_down,
                            count)

        score = int(count / grid)
        scoreboard.prep_count(score)
        screen.blit(image1, rect1)
        scoreboard.show_count()

        pygame.display.flip()

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

            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_RIGHT:
                    move_right = True

                elif event.key == pygame.K_LEFT:
                    move_left = True

                elif event.key == pygame.K_UP:
                    move_up = True

                elif event.key == pygame.K_DOWN:
                    move_down = True

            elif event.type == pygame.KEYUP:
                if event.key == pygame.K_RIGHT:
                    move_right = False
                    flag = False
                    for m in range(1, x.shape[0]):
                        for n in range(1, x.shape[1]):
                            if (abs(rect1.centerx - grid * n - (grid / 2)) <=
                                (grid / 2)) & (abs(rect1.centery - grid * m -
                                                   (grid / 2)) <= (grid / 2)):
                                rect1.center = [
                                    grid * n + (grid / 2),
                                    grid * m + (grid / 2)
                                ]
                                flag = True
                        if flag:
                            break

                elif event.key == pygame.K_LEFT:
                    move_left = False
                    flag = False
                    for m in range(1, x.shape[0]):
                        for n in range(1, x.shape[1]):
                            if (abs(rect1.centerx - grid * n - (grid / 2)) <=
                                (grid / 2)) & (abs(rect1.centery - grid * m -
                                                   (grid / 2)) <= (grid / 2)):
                                rect1.center = [
                                    grid * n + (grid / 2),
                                    grid * m + (grid / 2)
                                ]
                                flag = True
                        if flag:
                            break

                elif event.key == pygame.K_UP:
                    move_up = False
                    flag = False
                    for m in range(1, x.shape[0]):
                        for n in range(1, x.shape[1]):
                            if (abs(rect1.centerx - grid * n - (grid / 2)) <=
                                (grid / 2)) & (abs(rect1.centery - grid * m -
                                                   (grid / 2)) <= (grid / 2)):
                                rect1.center = [
                                    grid * n + (grid / 2),
                                    grid * m + (grid / 2)
                                ]
                                flag = True
                        if flag:
                            break

                elif event.key == pygame.K_DOWN:
                    move_down = False
                    flag = False
                    for m in range(1, x.shape[0]):
                        for n in range(1, x.shape[1]):
                            if (abs(rect1.centerx - grid * n - (grid / 2)) <=
                                (grid / 2)) & (abs(rect1.centery - grid * m -
                                                   (grid / 2)) <= (grid / 2)):
                                rect1.center = [
                                    grid * n + (grid / 2),
                                    grid * m + (grid / 2)
                                ]
                                flag = True
                        if flag:
                            break

        if (int((rect1.centery - (grid / 2)) / grid) == x.shape[0] - 2) & (int(
            (rect1.centerx - (grid / 2)) / grid) == x.shape[1] - 2):
            # print(x)
            break

    return True
Ejemplo n.º 3
0
from turtle import Screen, Turtle
from paddle import Paddle
from ball import Ball
from scoreboard import Scoreboard
import time

screen = Screen()
screen.bgcolor("black")
screen.setup(width=800, height=600)
screen.title("Pong")
screen.tracer(0)

r_paddle = Paddle((350, 0))
l_paddle = Paddle((-350, 0))
ball = Ball()
scoreboard = Scoreboard()

screen.listen()
screen.onkey(r_paddle.go_up, "Up")
screen.onkey(r_paddle.go_down, "Down")
screen.onkey(l_paddle.go_up, "w")
screen.onkey(l_paddle.go_down, "s")

game_is_on = True
while game_is_on:
    time.sleep(0.01)
    screen.update()
    ball.move()

    #Detect collision with wall
    if ball.ycor() > 280 or ball.ycor() < -280:
Ejemplo n.º 4
0
        mouse_press = pygame.mouse.get_pressed()
        mouse_pos = pygame.mouse.get_pos()
        left = img_srcpos.left + 550
        right = img_srcpos.right + 550
        top = img_srcpos.top + 600
        bottom = img_srcpos.bottom + 600

        if left < mouse_pos[0] < right and top < mouse_pos[
                1] < bottom:  #[0]表示左右(x轴)
            img_re = pygame.image.load(".\\image\\key2.png")
            if mouse_press[0]:  #当鼠标点击了右键
                select_sound.play(0)
                main()

        screen.blit(img_re, (550, 600))
        pygame.display.update()


fclock = pygame.time.Clock()
size = width, height = 1280, 850
screen = pygame.display.set_mode(size)
trivia = Trivia(screen, "temp//problems.txt")  # load the trivia data file
bg = pygame.image.load(".\\image\\bg.jpg")
sb = Scoreboard(screen, 0)
M = Mask(screen)
init()

while 1:
    Start()
Ejemplo n.º 5
0
def runGame():
    # Initialize game and create a window
    pg.init()
    # create a new object using the settings class
    setting = Settings()
    # creaete a new object from pygame display
    screen = pg.display.set_mode((setting.screenWidth, setting.screenHeight))

    # intro
    intro.introimages()

    # set window caption using settings obj
    pg.display.set_caption(setting.windowCaption)

    bMenu = ButtonMenu(screen)
    bMenu.addButton("play", "PLAY")
    bMenu.addButton("menu", "BACK")
    bMenu.addButton("twoPlay", "2PVS")
    bMenu.addButton("settings", "SETTINGS")
    bMenu.addButton("invert", "INVERT")
    bMenu.addButton("about", "ABOUT")
    bMenu.addButton("quit", "QUIT")
    bMenu.addButton("grey", "GREY")
    bMenu.addButton("red", "RED")
    bMenu.addButton("blue", "BLUE")
    bMenu.addButton("retry", "RETRY")
    bMenu.addButton("hard", "HARD")
    bMenu.addButton("normal", "NORMAL")
    bMenu.addButton("back", "MENU")
    bMenu.addButton("speed setting", "SPEED")
    bMenu.addButton("fast", "FAST")
    bMenu.addButton("middle", "MIDDLE")
    bMenu.addButton("slow", "SLOW")
    bMenu.addButton("yes", "YES")
    bMenu.addButton("no", "NO")
    bMenu.addButton("interception", "INTERCEPT")

    bMenu.addButton("sound", "SOUND")
    bMenu.addButton("loud", "LOUD")
    bMenu.addButton("low", "LOW")

    mainMenuButtons = ["play", "about", "settings", "quit"]  # delete "twoPlay"
    playMenuButtons = ["grey", "red", "blue", "menu", "quit"]
    levelMenuButtons = ["hard", "normal", "back", "quit"]

    mainGameButtons = ["play", "menu", "quit"]
    aboutButtons = ["menu", "quit"]

    soundButtons = ["loud", "low", "menu"]

    settingsMenuButtons = [
        "menu", "invert", "speed setting", "interception", "quit"
    ]
    speedButtons = ["menu", "fast", "middle", "slow"]

    bgManager = BackgroundManager(screen)
    bgManager.setFillColor((0, 0, 0))
    bgManager.addBackground("universe_1", "gfx/backgrounds/stars_back.png", 0,
                            1)
    bgManager.addBackground("universe_1", "gfx/backgrounds/stars_front.png", 0,
                            1.5)
    bgManager.selectBackground("universe_1")

    # Create an instance to stor game stats
    stats = GameStats(setting)
    sb = Scoreboard(setting, screen, stats)

    # Make a ship
    ship = Ship(setting, screen)
    # Ships for two player
    ship1 = Ship(setting, screen)
    ship2 = Ship(setting, screen)

    # make a group of items to store
    items = Group()

    # make a group of bullets to store
    bullets = Group()
    charged_bullets = Group()
    eBullets = Group()
    setting.explosions = Explosions()

    # Make an alien
    aliens = Group()
    gf.createFleet(setting, stats, screen, ship, aliens)
    pg.display.set_icon(pg.transform.scale(ship.image, (32, 32)))

    bgImage = pg.image.load('gfx/title_c.png')
    bgImage = pg.transform.scale(bgImage,
                                 (setting.screenWidth, setting.screenHeight))
    bgImageRect = bgImage.get_rect()

    aboutImage = pg.image.load('gfx/About_modify2.png')
    aboutImage = pg.transform.scale(
        aboutImage, (setting.screenWidth, setting.screenHeight))
    aboutImageRect = aboutImage.get_rect()

    # plays bgm
    pg.mixer.music.load('sound_bgms/galtron.mp3')
    pg.mixer.music.set_volume(0.25)
    pg.mixer.music.play(-1)

    rungame = True

    sounds.stage_clear.play()
    # Set the two while loops to start mainMenu first
    while rungame:
        # Set to true to run main game loop
        bMenu.setMenuButtons(mainMenuButtons)
        while stats.mainMenu:
            if not stats.gameActive and stats.paused:
                setting.initDynamicSettings()
                stats.resetStats()
                ##stats.gameActive = True

                # Reset the alien and the bullets
                aliens.empty()
                bullets.empty()
                eBullets.empty()

                # Create a new fleet and center the ship
                gf.createFleet(setting, stats, screen, ship, aliens)
                ship.centerShip()

            mm.checkEvents(setting, screen, stats, sb, bMenu, ship, aliens,
                           bullets, eBullets)
            mm.drawMenu(setting, screen, sb, bMenu, bgImage, bgImageRect)

        bMenu.setMenuButtons(levelMenuButtons)
        while stats.levelMenu:
            lm.checkEvents(setting, screen, stats, sb, bMenu, ship, aliens,
                           bullets, eBullets)
            lm.drawMenu(setting, screen, sb, bMenu, bgImage, bgImageRect)

        bMenu.setMenuButtons(playMenuButtons)
        while stats.playMenu:
            pm.checkEvents(setting, screen, stats, sb, bMenu, ship, aliens,
                           bullets, eBullets)
            pm.drawMenu(setting, screen, sb, bMenu)

        bMenu.setMenuButtons(mainGameButtons)

        while stats.mainGame:
            # Game functions
            gf.checkEvents(setting, screen, stats, sb, bMenu, ship, aliens,
                           bullets, eBullets,
                           charged_bullets)  # Check for events
            # Reset Game
            if gf.reset == 1:
                gf.reset = 0
                pg.register_quit(runGame())
            if stats.gameActive:
                gf.updateAliens(setting, stats, sb, screen, ship, aliens,
                                bullets, eBullets)  # Update aliens
                gf.updateBullets(setting, screen, stats, sb, ship, aliens,
                                 bullets, eBullets, charged_bullets,
                                 items)  # Update collisions
                gf.updateItems(setting, screen, stats, sb, ship, aliens,
                               bullets, eBullets, items)
                ship.update(bullets, aliens)  # update the ship
                # Update the screen
            gf.updateScreen(setting, screen, stats, sb, ship, aliens, bullets,
                            eBullets, charged_bullets, bMenu, bgManager, items)

        bMenu.setMenuButtons(aboutButtons)
        bMenu.setPos(None, 500)

        while stats.mainAbout:
            About.checkEvents(setting, screen, stats, sb, bMenu, ship, aliens,
                              bullets, eBullets)
            About.drawMenu(setting, screen, sb, bMenu, aboutImage,
                           aboutImageRect)

        while stats.twoPlayer:
            tp.checkEvents(setting, screen, stats, sb, bMenu, bullets, aliens,
                           eBullets, ship1, ship2)
            if stats.gameActive:
                ship1.update(bullets, aliens)
                ship2.update(bullets, aliens)
                tp.updateBullets(setting, screen, stats, sb, ship1, ship2,
                                 aliens, bullets, eBullets, items)
            tp.updateScreen(setting, screen, stats, sb, ship1, ship2, aliens,
                            bullets, eBullets, bMenu, items)

        bMenu.setMenuButtons(settingsMenuButtons)

        while stats.settingsMenu:
            sm.checkEvents1(setting, screen, stats, sb, bMenu, ship, aliens,
                            bullets, eBullets)
            sm.drawMenu(setting, screen, sb, bMenu)

        bMenu.setMenuButtons(speedButtons)
        while stats.speedMenu:
            spm.checkEvents(setting, screen, stats, sb, bMenu, ship, aliens,
                            bullets, eBullets)
            spm.drawMenu(setting, screen, sb, bMenu)

        while stats.mainGame:
            if rungame == True:
                print("test")
Ejemplo n.º 6
0
def game_run():
    file = r'activation.mp3'
    # Initialize
    pygame.mixer.init()
    # Load the file pf music
    pygame.mixer.music.load(file)
    pygame.mixer.music.play()

    # Initialize and create screen.
    pygame.init()
    setting = Setting()
    screen = pygame.display.set_mode(
        (setting.screen_width, setting.screen_height))
    pygame.display.set_caption("Aircraft war")

    # Create play button
    play_button = Button(setting, screen, 'Play', 200)
    help_button = Button(setting, screen, 'Help', 400)

    # Draw a rocket.
    rocket = Rocket(setting, screen)

    # Set a Group for bullets.
    bullets = Group()

    # Set a Group for alien bullets.
    alien_bullets = Group()

    # Set a Group for aliens.
    aliens = Group()

    # Create aliens.
    functions.create_aliens(setting, screen, rocket, aliens, alien_bullets)

    # Create States.
    states = States(setting)

    # Create Scoreboard.
    scoreboard = Scoreboard(setting, screen, states)

    # Create Textbox.
    textbox = Textbox(setting, screen)

    # Create Incidents.
    incidents = Group()

    # Create Background.
    BackGround = Background('background.jpg', [0, 0])

    # Main loop.
    while True:
        functions.respond_events(setting, screen, states, scoreboard, rocket,
                                 aliens, bullets, alien_bullets, play_button,
                                 help_button, textbox, incidents)
        if states.game_active:
            rocket.update_rocket()
            bullets.update(rocket)
            alien_bullets.update(setting)
            incidents.update(states)
            functions.update_bullets(setting, screen, states, scoreboard,
                                     rocket, aliens, bullets, alien_bullets)
            functions.update_aliens(setting, screen, states, scoreboard,
                                    rocket, aliens, bullets, alien_bullets,
                                    incidents)
            functions.update_alien_bullets(setting, screen, states, scoreboard,
                                           rocket, aliens, bullets,
                                           alien_bullets, incidents)
            functions.update_incidents(setting, screen, states, scoreboard,
                                       rocket, aliens, bullets, alien_bullets,
                                       incidents)
        functions.screen_update(setting, screen, states, scoreboard, rocket,
                                aliens, bullets, alien_bullets, play_button,
                                help_button, textbox, incidents)
        screen.fill([255, 255, 255])
        screen.blit(BackGround.image, BackGround.rect)
Ejemplo n.º 7
0
def run_game():
    BLACK = (0, 0, 0)
    pygame.init()
    screen = pygame.display.set_mode((700, 780))
    pygame.display.set_caption("Pacman Portal")
    clock = pygame.time.Clock()
    start_tick = pygame.time.get_ticks()
    random.seed()
    play_button = Button(screen, "Play")
    sb = Scoreboard(screen)

    # create pacman
    pacman = Pacman(screen)

    # create ghosts
    ghost1 = Ghost(screen, 1)
    ghost2 = Ghost(screen, 2)
    ghost3 = Ghost(screen, 3)
    ghost4 = Ghost(screen, 4)
    ghosts = Group(ghost1, ghost2, ghost3, ghost4)

    # create a group for the pills
    pills = Group()

    # create the maze
    maze = Maze(screen,
                pills,
                mazefile='images/pacmanportalmaze.txt',
                brickfile='blue_square',
                shieldfile='shield',
                portalfile='portal2',
                powerpill='powerpill',
                powerpill2='powerpill')

    # def __str__(self): return 'Game(Pacman Portal), maze=' + str(self.maze) + ')'

    # pacman intro sound
    intro_music = pygame.mixer.Sound('music/pacman_beginning.wav')
    intro_music.play()

    # show the start screen
    ss.Start_Screen(screen, play_button, sb)

    # game main loop
    while True:

        if sb.game_active:
            screen.fill(BLACK)
            # seconds = int((pygame.time.get_ticks() - start_tick) / 500)
            rand_num = random.randint(0, 100)
            pacman.check_events()
            pacman.update()
            pacman.blitme()
            maze.blitme()

            for ghost in ghosts:
                ghost.get_direction(rand_num)
                ghost.update()
                ghost.blitme()

            gf.check_pill_collision(pacman, pills, sb, maze)
            gf.check_ghost_collision(pacman, ghosts, sb)
            sb.show_score()
            pygame.display.flip()

            # checks if no lives are left and displays the "game over" screen
            if sb.lives_left == 0:
                sb.game_active = False
                sleep(1)
                go.Game_Over(screen, play_button, sb)
                sb.reset_stats()
                maze.build()
                pacman.reset()
                for ghost in ghosts:
                    ghost.reset()
                sb.prep_score()
                sb.prep_high_score()
                sb.prep_level()
                sb.prep_lives()
                pygame.display.flip()
            # print("Game Active")

        else:
            pygame.mouse.set_visible(True)
            pacman.reset()
            for ghost in ghosts:
                ghost.reset()

            play_button.draw_button()
            pygame.display.flip()
            while not sb.game_active:
                gf.check_button(play_button, sb)

        # print("seconds = " + str(seconds))

        # set the fps
        clock.tick(60)
from scoreboard import Scoreboard
import game_functions as gf

# Define some colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)

# Initialize pygame, settings, and screen object.
pygame.init()
settings = Settings()
screen = pygame.display.set_mode(
    (settings.screen_width, settings.screen_height))

sb = Scoreboard(settings, screen)

player = Ship(
    screen, settings
)  # Create the player; Player is a ship; Draw the ship on the screen

# Make a group to store bullets in.
bullets = Group()

# Make a group to store enemies in.
enemies = Group()

# Make a group to store enemy bullets in
enemy_bullets = Group()

# Make an enemy.
Ejemplo n.º 9
0
def run_game(frame, set_music):
    # init game
    hard = 1
    ele_time = 0
    clock = pygame.time.Clock()
    pygame.init()
    settings = Settings()
    gs = GameStats()
    gs.reset()
    if sys.platform == "win32" or sys.platform == "cygwin":
        my_font = pygame.font.SysFont("kaiti", 100)
    else:
        my_font = pygame.font.SysFont("kaitif", 100)
    tnts = Group()

    # init bgm
    if set_music is not None:
        pygame.mixer.music.load(f"game_music/background/{set_music}")
        pygame.mixer.music.play(-1)

    # init window
    screen = pygame.display.set_mode((settings.width, settings.height))
    screen_rect = screen.get_rect()
    icon = pygame.image.load("icon.ico")
    pygame.display.set_icon(icon)
    pygame.display.set_caption("dodge tnt")

    # init player
    steve = Steve(screen, skin)

    # heal instruction
    h1 = Health(screen, 1)
    h2 = Health(screen, 2)
    h3 = Health(screen, 3)
    magic = Magic(screen)
    t1 = time.time()
    start_rec = t1
    tnt_num = 0

    pygame.mouse.set_visible(False)
    heal = 3
    # main loop
    while True:
        clock.tick(frame)
        h1.update(heal)
        h2.update(heal)
        h3.update(heal)
        t2 = time.time()
        nowrec = t2
        nhard = int((nowrec + 20 - start_rec) / (19 + int(hard / 2)))
        if nhard > hard:
            hard = nhard
        tntw = int(nowrec + 140 - start_rec) / (hard * 90)
        steve_tnt = False
        if random.randint(1, 10) == 5:
            steve_tnt = True
        sb = Scoreboard(screen, gs, hard)
        cool_down = CoolDown(screen, steve)
        steve.speed = hard * 0.5
        if t2 - t1 > tntw:
            if tnt_num < 10:
                tnt_num += 1
                new_tnt = TNT(screen)
                new_tnt.speed += hard * 0.1
                if steve_tnt:
                    new_tnt.rect.centerx = steve.rect.centerx
                tnts.add(new_tnt)
                t1 = t2

        func_return = gf.check_events(steve, start_rec, screen, my_font, hard,
                                      ele_time)
        start_rec = func_return[0]
        ele_time = func_return[1]
        steve.update()

        tnts.update()
        gf.kick_minus(steve)
        gf.check_kick(steve, hard)
        steve.magic = gf.magic_return(steve.magic, hard)
        steve.speed = gf.speed_check(steve, hard)
        ctcsl = gf.check_tnt_c_steve(tnts, steve, heal, tnt_num, screen,
                                     gs.score, hard, steve.magic)
        heal = ctcsl[0]
        tnt_num = ctcsl[1]
        gs.score = ctcsl[2]
        steve.magic = ctcsl[3]
        gf.check_die(heal, gs.score, hard, ele_time, start_rec, nowrec)
        for tnt in tnts.copy():
            if tnt.rect.top >= screen_rect.bottom:
                tnt_num -= 1
                tnts.remove(tnt)
                gs.score += hard
        gf.update_screen(screen, steve, tnts, sb, h1, h2, h3, cool_down, magic,
                         hard, heal)
Ejemplo n.º 10
0
from turtle import Turtle, Screen
import random
import time
from scoreboard import Scoreboard
from setup import Setup
from paddle import Paddle
from ball import Ball

screen = Setup()
player_1_score = Scoreboard(-100)
player_2_score = Scoreboard(100)
p1_paddle = Paddle(350)
p2_paddle = Paddle(-350)
ball = Ball()

screen.onkey(p1_paddle.up, 'Up')
screen.onkey(p1_paddle.down, 'Down')
screen.onkey(p2_paddle.up, 'w')
screen.onkey(p2_paddle.down, 's')

screen.onkey(screen.quit, 'q')
game = True

while game:
    screen.update()
    ball.move()
    player_1_score.display_score()
    player_2_score.display_score()
    x_cor_p1 = [(piece.xcor() - 10, piece.ycor() - 10)
                for piece in p1_paddle.body]
    x_cor_p2 = [(piece.xcor() + 10, piece.ycor() + 10)
Ejemplo n.º 11
0
def play():
    pygame.init()
    settings = Settings()
    screen = pygame.display.set_mode((settings.scr_width, settings.scr_height))
    pygame.display.set_caption('Alien Invasion')
    main_clock = pygame.time.Clock()

    stats = GameStats(settings, screen)
    sb = Scoreboard(settings, screen, stats)
    sscreen = StartScreen(settings, screen)

    # Make a ship
    ship = Ship(settings, screen)

    # Make bunkers
    bunkers = [Bunker(screen, 400, 480)]

    # Make bullets and aliens group
    bullets = Group()
    aliens = Group()
    enemy_bullets = Group()
    # gf.create_fleet(settings, screen, ship, aliens)

    # Make buttons
    play_button = Button(screen, 'PLAY', screen.get_rect().centerx, 400)
    score_button = Button(screen, 'HIGH SCORE', screen.get_rect().centerx, 480)
    buttons = [play_button, score_button]

    # Set up music
    bg_music1 = pygame.mixer.Sound('audio/background_1.wav')
    bg_music2 = pygame.mixer.Sound('audio/background_2.wav')
    is_playing_music = False
    is_playing_music2 = False
    game_over_sound = pygame.mixer.Sound('audio/gameover.wav')

    # Boss timer
    boss_respawn_time = randint(10, 18) * 1000  # 10-18s at level 1
    boss_timer = boss_respawn_time
    delta_time = 0

    # Enemy fire timer
    enemy_fire_time = randint(2, 6) * 1000  # 2-6s at level 1
    fire_timer = enemy_fire_time

    # Main game loop
    game_over = False
    while not game_over:
        gf.check_events(settings, screen, stats, sb, buttons, ship, aliens, bullets, enemy_bullets, bunkers)
        if stats.game_status == 2:
            # update bg music
            if not is_playing_music:
                bg_music1.play(-1)
                is_playing_music = True
                is_playing_music2 = False
            if len(aliens) - settings.boss_number <= 10 and not is_playing_music2:
                bg_music1.stop()
                bg_music2.play(-1)
                is_playing_music2 = True
            if is_playing_music2 and len(aliens) - settings.boss_number > 10:
                bg_music2.stop()
                bg_music1.play(-1)
                is_playing_music = True
                is_playing_music2 = False
            if ship.dead and ship.die_anim.finished and stats.ships_left > 0:
                pygame.mixer.stop()
                is_playing_music, is_playing_music2 = False, False
                # reset boss and fire timer when ship explodes
                boss_respawn_time = randint(10, 18) * 1000
                boss_timer = int(boss_respawn_time / settings.enemy_timer_scale)
                enemy_fire_time = randint(2, 6) * 1000
                fire_timer = int(enemy_fire_time / settings.enemy_timer_scale)

            for b in bunkers:
                b.update(bullets, enemy_bullets)
            ship.update()
            gf.update_ship(settings, screen, stats, sb, ship, aliens, bullets, enemy_bullets)
            gf.update_bullets(settings, screen, stats, sb, aliens, bullets, enemy_bullets)

            # Spawn boss
            if settings.boss_number < settings.boss_number_limit:
                if boss_timer <= 0:
                    gf.create_boss(settings, screen, aliens)
                    boss_respawn_time = randint(10, 18) * 1000
                    boss_timer = int(boss_respawn_time / settings.enemy_timer_scale)
                else:
                    boss_timer -= delta_time

            gf.update_aliens(settings, screen, ship, aliens)

            # Enemy fire
            if fire_timer <= 0 and len(enemy_bullets) < settings.bullets_allowed:
                new_bullet = EnemyBullet(settings, screen, aliens)
                enemy_bullets.add(new_bullet)
                enemy_fire_time = randint(2, 6) * 1000
                fire_timer = int(enemy_fire_time / settings.enemy_timer_scale)
            elif fire_timer > 0:
                fire_timer -= delta_time
            gf.update_enemy_bullets(settings, ship, bullets, enemy_bullets)

        else:
            # update music
            if is_playing_music or is_playing_music2:
                pygame.mixer.stop()
                is_playing_music, is_playing_music2 = False, False
                if stats.ships_left == 0:
                    game_over_sound.play()
                    # reset boss and fire timer to level 1
                    boss_respawn_time = randint(10, 18) * 1000
                    boss_timer = boss_respawn_time
                    enemy_fire_time = randint(2, 6) * 1000
                    fire_timer = enemy_fire_time

        gf.update_screen(settings, screen, stats, sb, ship, aliens, bullets, enemy_bullets, bunkers, buttons, sscreen)
        delta_time = main_clock.tick(FPS)
Ejemplo n.º 12
0
from snake import Snake
from scoreboard import Scoreboard
from food import Food
import time

screen=Screen()
screen.setup(width=600,height=600)
screen.bgcolor("black")
screen.title("Snake Game")
screen.tracer(0)
game_is_on=True
score=0

snake=Snake()

scoreboard=Scoreboard(score)

food=Food(score)

""" actions """

screen.listen()
screen.onkey(snake.up,"w")
screen.onkey(snake.down,"s")
screen.onkey(snake.left,"a")
screen.onkey(snake.right,"d")

while game_is_on:

    screen.update()
    snake.move()
def run_game():
    #  Initialize game, screen settings and screen project.
    pygame.init()
    ai_settings = Settings()
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption("Space Invasion")

    pygame.mixer_music.load('Sounds/background_music.mp3')
    pygame.mixer_music.play(-1, 0)

    #  Make the buttons.
    play_button = Button(ai_settings, screen, "Play")
    high_score_button = Button(ai_settings, screen, "High Scores")
    quit_button = Button(ai_settings, screen, "Quit")
    back_button = Button(ai_settings, screen, "Back")
    start_button = Button(ai_settings, screen, "Start!")
    play_button.rect.centery -= 150
    play_button.msg_image_rect.centery = play_button.rect.centery
    high_score_button.rect.bottom = play_button.rect.bottom + 100
    high_score_button.msg_image_rect.center = high_score_button.rect.center
    quit_button.rect.bottom = screen.get_rect().bottom
    quit_button.rect.right = screen.get_rect().right
    quit_button.msg_image_rect.center = quit_button.rect.center
    back_button.rect.center = quit_button.rect.center
    back_button.msg_image_rect.center = back_button.rect.center
    start_button.rect.bottom = screen.get_rect().bottom
    start_button.rect.right = screen.get_rect().right
    start_button.msg_image_rect.center = start_button.rect.center

    #  Create an instance to store game statistics and create a scoreboard
    stats = GameStats(ai_settings)
    sb = Scoreboard(ai_settings, screen, stats)

    #  Make a ship.
    ship = Ship(ai_settings, screen)
    #  Make a group to store bullets in.
    bullets = Group()
    aliens = Group()
    alien_bullets = Group()
    bunkers = Group()

    #  Create a fleet of aliens
    gf.create_fleet(ai_settings, screen, ship, aliens, bunkers)

    #  Start the main loop for the game
    while True:
        #  Watch for keyboard and mouse events.
        gf.check_events(ai_settings, screen, stats, sb, play_button,
                        high_score_button, quit_button, back_button, ship,
                        aliens, bullets, bunkers)

        if stats.game_active:
            ship.update()
            gf.update_bullets(ai_settings, screen, stats, sb, ship, aliens,
                              bullets, alien_bullets, bunkers)
            gf.update_aliens(ai_settings, stats, screen, sb, ship, aliens,
                             bullets, alien_bullets, bunkers)
        gf.update_screen(ai_settings, screen, stats, sb, ship, aliens, bullets,
                         play_button, high_score_button, quit_button,
                         back_button, alien_bullets, bunkers)
Ejemplo n.º 14
0
 def _inti_scores(self):
     for i in range(1, 11):
         score = Scoreboard(self)
         score.place = i
         self.scores.append(score)
Ejemplo n.º 15
0
def run_game():
    #initialize game and create a screen object.
    pygame.init()
    ai_settings = Settings()
    screen = pygame.display.set_mode((ai_settings.screen_width, ai_settings.screen_height))
    # screen = pygame.display.set_mode((1200,800))
    #
    # #set the background color
    # bg_color = (230, 230, 230)

    pygame.display.set_caption("Alien Invasion")

    #create 'play' buttotn
    play_button =Button(ai_settings, screen, "Play")

    #create an object use to storage the statistical imformation
    stats = GameStats(ai_settings)

    #create an instance to store game statistics
    sb = Scoreboard(ai_settings, screen, stats)

    #create a ship, a bullet group and a alien group
    #create a ship
    ship = Ship(ai_settings, screen)
    #create a group to storage bullet
    bullets = Group()
    aliens =Group()

    #create alien object
    #alien = Alien(ai_settings, screen)
    gf.create_fleet(ai_settings, screen, ship, aliens)

    #start the game main loop.
    while True:
        #Monitor the keyboard and mouse event.

        # for event in pygame.event.get():
        #     if event.type == pygame.QUIT:
        #         sys.exit()
        gf.check_events(ai_settings, screen, stats, sb, play_button, ship, aliens, bullets)
        ship.update()
        if stats.game_active:
            # center = ship.center
            # cenerx = ship.rect.centerx
            #redraw srcreen
            # screen.fill(ai_settings.bg_color)
            # ship.blitme()
            #
            # #display the screen which was drew recently.
            # pygame.display.flip()
            gf.update_bullets(ai_settings, screen, stats, sb, ship, aliens, bullets)
            # bullets.update()
            # #delete missing bullets
            # #for bullet in bullets:
            # for bullet in bullets.copy():
            #     if bullet.rect.bottom <= 0:
            #         bullets.remove(bullet)
            #print(len(bullets))
            gf.update_aliens(ai_settings, screen, stats, sb, ship, aliens, bullets)

        gf.update_screen(ai_settings, screen, stats, sb, ship, aliens, bullets, play_button)
Ejemplo n.º 16
0
def main():
    # initialize the game and create a screen object
    pygame.init()
    screen = pygame.display.set_mode((266, 838))
    pygame.display.set_caption('settai tetris')

    # instantiate the objects
    block = Block(screen)
    settings = Settings(screen)
    stats = GameStats()
    sb = Scoreboard(screen, settings, stats)

    # create the Sound objects
    move_sound = pygame.mixer.Sound("sounds/move.wav")
    rotate_sound = pygame.mixer.Sound("sounds/rotate.wav")
    aeon_open = pygame.mixer.Sound("sounds/aeon_opening.wav")
    aeon_close = pygame.mixer.Sound("sounds/aeon_closing.wav")
    bottom_down = pygame.mixer.Sound("sounds/bottom_down.wav")

    # set the initial block and the position
    block.draw_outer(settings.white, settings.black)
    x_pos = 5
    y_pos = 1
    timing = 0
    rotate = 0
    type_ = random.randrange(0, 7)

    while True:
        block.x_move = 0
        block.r_move = 0

        gf.check_events(block)
        x_pos += block.x_move
        rotate += block.r_move

        block.figure_sub_squares(x_pos, y_pos, rotate, type_)
        # if collisions, put the pos back to previous one
        if block.check_macros(x_pos, y_pos):
            if block.x_move != 0:
                x_pos -= block.x_move
            elif block.r_move != 0:
                rotate -= block.r_move
        # otherwise ping a sound
        else:
            if block.x_move != 0:
                move_sound.play()
            elif block.r_move != 0:
                rotate_sound.play()

        timing += 1  # adjust the speed of falling blocks.
        if timing % 10 == 0 or block.push_down:
            y_pos += 1

            block.figure_sub_squares(x_pos, y_pos, rotate, type_)
            if block.check_macros(x_pos, y_pos):
                y_pos = y_pos - 1
                block.figure_sub_squares(x_pos, y_pos, rotate, type_)
                block.draw_squares(x_pos, y_pos, settings.white)
                block.fill_macros(x_pos, y_pos)
                block.remove_n_slide(settings, stats, sb, aeon_open,
                                     aeon_close)

                # prepare for the next block
                x_pos = 5
                y_pos = 1
                rotate = 0
                type_ = random.randrange(0, 7)

        # adjusting the level
        if block.any_of_macro():
            stats.level += 1
            if stats.level == 2:
                bottom_down.play()
                block.bottom_down(settings)
            elif stats.level <= 3:
                # polite way to gave over
                import pdb
                pdb.set_trace()

        # draw the active block in red.
        block.figure_sub_squares(x_pos, y_pos, rotate, type_)
        block.draw_squares(x_pos, y_pos, settings.red)

        sb.show_score()
        pygame.display.update()

        # then paint it back to black.
        block.draw_squares(x_pos, y_pos, settings.black)
Ejemplo n.º 17
0
import time
from turtle import Screen
from player import Player
from car_manager import CarManager
from scoreboard import Scoreboard

# Screen setup
screen = Screen()
screen.setup(width=600, height=600)
screen.tracer(0)

# Game setup
player = Player(screen.window_height())
cars = CarManager(screen.window_height(), screen.window_width())
score = Scoreboard(screen.window_height(), screen.window_width())
game_is_on = True

# Gameplay setup
screen.listen()
screen.onkeypress(player.go_up, 'Up')
screen.onkeypress(player.go_down, 'Down')


def detect_collision():
    """detects if the player has come into contact with any of the cars and triggers the game_over sequence if so"""
    global game_is_on
    for car in cars.all_cars:
        if car.distance(player) < 20:
            game_is_on = False
            score.game_over()
Ejemplo n.º 18
0
def run_game():
    # # 初始化游戏并创建一个屏幕对象
    # pygame.init()
    # screen = pygame.display.set_mode((1200, 800))  # (1200, 800) 是一个元组
    # pygame.display.set_caption("Alien Invasion")

    # 初始化 pygame、设置和屏幕对象
    pygame.init()
    ai_settings = Settings()
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption("Alien Invasion")

    # 创建一个 Play 按钮
    play_button = Button(ai_settings, screen, 'Play')

    # 创建一个用于存储游戏统计信息的实例 , 并创建记分牌
    stats = Gamestats(ai_settings)
    sb = Scoreboard(ai_settings, screen, stats)

    # # pygame 创建窗口默认是黑色的  不过可以更改颜色  且颜色是以 RGB 指定的
    # bg_color = (230, 230, 230)

    # 创建一艘飞船
    ship = Ship(ai_settings, screen)

    # 创建一个外星人
    # alien = Alien(ai_settings, screen)
    aliens = Group()

    # 创建一个用于存储子弹的编组
    bullets = Group()

    # 创建外星人群
    gf.create_fleet(ai_settings, screen, ship, aliens)

    # 开始游戏的主循环
    while True:

        # 监视键盘和鼠标事件
        # for event in pygame.event.get():
        #     if event.type == pygame.QUIT:
        #         sys.exit()
        gf.check_events(ai_settings, screen, stats, sb, play_button, ship,
                        aliens, bullets)

        if stats.game_active:

            # 根据移动标志调整飞船的位置
            ship.update()

            gf.update_bullets(ai_settings, screen, stats, sb, ship, aliens,
                              bullets)

            #
            # # 删除已消失的子弹   因为子弹只是无法在屏幕外显示  当数量越来越多 就会占用内存 从而运行会越来越慢
            # for bullet in bullets.copy():
            #     if bullet.rect.bottom <= 0:
            #         bullets.remove(bullet)
            # # print(len(bullets))

            # 更新子弹位置,并删除已消失的子弹
            # gf.update_bullets(bullets)

            gf.update_aliens(ai_settings, stats, screen, sb, ship, aliens,
                             bullets)

            # # 每次循环时都重新绘制屏幕
            # screen.fill(ai_settings.bg_color)  # 用背景色填充屏幕  screen.fill 只接受一个实参:一种颜色
            # ship.blitme()
            #
            # # 让最近绘制的屏幕可见
            # pygame.display.flip()

        gf.update_screen(ai_settings, screen, stats, sb, ship, aliens, bullets,
                         play_button)
Ejemplo n.º 19
0
def run_game():
    # Initialize game and create a screen object

    pygame.init()
    ai_settings = Settings()
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption("Space Invaders")

    # instance to store game statistics and create a scoreboard
    stats = GameStats(ai_settings=ai_settings)
    sb = Scoreboard(ai_settings=ai_settings, screen=screen, stats=stats)
    # MAKE A SHIP
    ship = Ship(ai_settings, screen)

    # Make a group to store the bullets in
    bullets = Group()
    aliens = Group()

    # Make an alien
    gf.create_fleet(ai_settings=ai_settings,
                    screen=screen,
                    ship=ship,
                    aliens=aliens)

    # MAIN LOOP FOR THE GAME
    while True:

        gf.check_events(ai_settings=ai_settings,
                        screen=screen,
                        stats=stats,
                        sb=sb,
                        play_button=play_button,
                        ship=ship,
                        aliens=aliens,
                        bullets=bullets)
        if stats.game_active:
            ship.update()
            gf.update_bullets(ai_settings=ai_settings,
                              screen=screen,
                              stats=stats,
                              sb=sb,
                              ship=ship,
                              aliens=aliens,
                              bullets=bullets)
            gf.update_aliens(ai_settings=ai_settings,
                             screen=screen,
                             stats=stats,
                             sb=sb,
                             ship=ship,
                             aliens=aliens,
                             bullets=bullets)

        gf.update_screen(ai_settings=ai_settings,
                         screen=screen,
                         stats=stats,
                         sb=sb,
                         ship=ship,
                         aliens=aliens,
                         bullets=bullets,
                         play_button=play_button)
Ejemplo n.º 20
0
def run_game():
    pygame.init()

    ai_settings = Settings()
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))

    pygame.display.set_caption("Alien Invasion!")

    # Make the play button and high scores button
    play_button = Button(ai_settings, screen, "Play!")
    high_scores_button = HighScoresButton(ai_settings, screen, "High Scores")

    # Create an instance to store game statistics and create a scoreboard
    stats = GameStats(ai_settings)
    sb = Scoreboard(ai_settings, screen, stats)

    # Make a ship, a group of bullets, and a group of aliens, a group of barriers, and a UFO
    ship = Ship(ai_settings, screen)
    bullets = Group()
    aliens = Group()
    barrier = Barrier(ai_settings, screen)
    ufo = UFO(ai_settings, screen)
    hs_init = open("high_scores.txt", "r+")
    stats.high_score = int(hs_init.readline())
    stats.high_score_2 = int(hs_init.readline())
    stats.high_score_3 = int(hs_init.readline())
    hs_init.close()

    # Make the start screen
    start_screen = StartScreen(
        ai_settings, screen, aliens, "Alien Invasion!", "= 50", "= 100",
        "= 150", "= 300",
        "Gabriel Magallanes | For CPSC 386 (Video Game Design) | Cal State Fullerton | 2019"
    )

    # Make the high score window
    high_score_window = HighScoreWindow(ai_settings, screen, stats)

    # Create the fleet of aliens
    gf.create_fleet(ai_settings, screen, ship, aliens)

    # Create a way to keep track of time (for the ufo spawn)
    time_elapsed = 0
    clock = pygame.time.Clock()

    # Start the main loop for the game
    while True:

        gf.check_events(ai_settings, screen, stats, sb, play_button, ship,
                        aliens, bullets, high_scores_button)

        if stats.game_active:
            ship.update()
            gf.update_ufo(ai_settings, screen, ufo)
            gf.update_bullets(ai_settings, screen, stats, sb, ship, aliens,
                              bullets, high_score_window)
            gf.update_aliens(ai_settings, screen, stats, sb, ship, aliens,
                             bullets, high_score_window)

        gf.update_screen(ai_settings, screen, stats, sb, ship, aliens, bullets,
                         start_screen, play_button, ufo, barrier,
                         high_scores_button)
Ejemplo n.º 21
0
 def __init__(self):
     self.scoreboard = Scoreboard()
     self.enemies = []
     self.create_enemies()
Ejemplo n.º 22
0
import time
from turtle import Screen
from player import Player
from car_manager import CarManager
from scoreboard import Scoreboard

screen = Screen()
screen.setup(width=600, height=600)
screen.tracer(0)

car_manager = CarManager()
screen.update()
time.sleep(.5)
player = Player()
sb = Scoreboard()

screen.listen()
screen.onkey(player.up, "Up")

game_is_on = True
while game_is_on:
    time.sleep(0.1)
    screen.update()
    car_manager.move()
    screen.update()

    if player.ycor() >= 290:
        sb.increase_level()
        player.reset()
        car_manager.increase_level()
Ejemplo n.º 23
0
from pygame.sprite import Group

from scoreboard import Scoreboard
from settings import Settings
from game_objects import Player, Background
import game_fuction as gf
from stats import GameStats
from button import Button

pygame.init()
pygame.display.set_caption('Catch This')
ct_settings = Settings()
screen = pygame.display.set_mode((ct_settings.width, ct_settings.height))
clock = pygame.time.Clock()
stats = GameStats(ct_settings)
sb = Scoreboard(ct_settings, stats, screen)
play_button = Button(screen, 'Play')

#Groups
friends = Group()
enemies = Group()
bonus = Group()

#Game objects
player = Player(ct_settings, screen)
background = Background(ct_settings, screen)

while True:
    gf.check_events(bonus, ct_settings, enemies, friends, play_button, player, sb, stats)
    if stats.game_active:
        player.update()
Ejemplo n.º 24
0
def run_game():
    # 初始化混音器模块
    pygame.mixer.init()

    # 无线循环的背景音乐
    pygame.mixer.music.load('voice/123.mp3')
    # -1代表无限循环(背景音乐)
    pygame.mixer.music.play(-1)

    # 枪声
    fireSound = pygame.mixer.Sound('voice/5313.wav')

    # 爆炸声
    explosiveSound = pygame.mixer.Sound('voice/9730.wav')

    # 初始化游戏并创建一个屏幕对象
    pygame.init()
    ai_settings = Settings()
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption("plane go!")

    # 创建Play按钮
    play_button = Button(ai_settings, screen, 'Play', 50, 50)

    # 创建exit按钮
    exit_button = Button(ai_settings, screen, 'exit game', 50, 200)

    # 创建一艘飞船,创建一个用于存储子弹的编组,创建一个外星人编组
    ship = Ship(screen, ai_settings)
    bullets = Group()
    aliens = Group()
    die_aliens = Group()

    # 创建一个用于存储游戏统计信息的实例,并创建记分牌
    stats = GameStats(ai_settings)
    sb = Scoreboard(ai_settings, screen, stats)

    # 创建背景图片
    start_background = Background(screen, ai_settings, 'images/background.jpg')
    end_background = Background(screen, ai_settings, 'images/background.jpg')

    pygame.time.set_timer(pygame.USEREVENT, 3000)
    # 游戏循环帧率设置
    clock = pygame.time.Clock()

    # 开始游戏的主循环
    while True:

        clock.tick(200)
        # 监视键盘和鼠标事件
        gf.check_events(ai_settings, screen, stats, sb, play_button,
                        exit_button, ship, aliens, bullets, fireSound)
        if stats.game_active:
            ship.update()
            gf.update_bullets(ai_settings, screen, stats, sb, ship, aliens,
                              bullets, die_aliens, explosiveSound)
            gf.update_aliens(ai_settings, stats, screen, sb, ship, aliens,
                             bullets, play_button)
            gf.update_screen(ai_settings, screen, stats, sb, ship, aliens,
                             bullets, play_button, exit_button,
                             start_background, die_aliens)
        elif not stats.game_active and stats.level == 0:
            gf.start_meun(ai_settings, screen, stats, sb, ship, aliens,
                          bullets, play_button, exit_button, start_background)
        elif not stats.game_active and stats.level == 5:
            gf.end_meun(ai_settings, screen, stats, sb, ship, aliens, bullets,
                        play_button, exit_button, end_background)
Ejemplo n.º 25
0
def run_game():
    seconds = 0
    pygame.init()
    bulletCollidedWithBunker = False
    alienCollidedWithBullet = False
    ai_settings = Settings()
    bunkerRect = 0

    screen = pygame.display.set_mode((ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption("Alien Invasion")
    play_button = Button(ai_settings,screen,"Play")
    stats = GameStats(ai_settings)
    sb = Scoreboard(ai_settings,screen,stats)
    ship = Ship(ai_settings,screen)
    bullets = Group()
    aliens = Group()
    numberOfTicks = 0








    bunker = pygame.image.load("images/bunker1.png")
    bunkerCopy = bunker
    del bunker


    print("bunker clipping area")
















    print("bunker's size")





































    gf.create_fleet(ai_settings, screen,ship, aliens)

    bg_color = (230, 230, 230)

    while True:








        pygame.display.update()


































        gf.check_events(ai_settings,screen,stats,sb,play_button,ship,aliens,bullets,bunkerCopy)



        gf.update_screen(ai_settings, screen,stats,sb, ship, aliens, bullets, play_button,bunkerCopy)








        if stats.game_active:

          pygame.draw.circle(screen,(0,0,255),(130,242 ),5,5)

          pygame.display.update()

          ship.update()


          if bulletCollidedWithBunker == False:
           gf.update_bullets(ai_settings,screen,stats,sb,ship,aliens,bullets,bunkerGroup,bunkerCopy)
           gf.update_aliens(ai_settings,screen,stats,sb,ship,aliens, bullets)



        if bulletCollidedWithBunker == False:
          bullets.update()




         #118,255,3,255


        for bunker12 in bunkerGroup:







































         for bullet in bullets.copy():
            if bullet.rect.bottom <= 0:
                 bullets.remove(bullet)
Ejemplo n.º 26
0
def run_game():
    # Initialize game and create a screen object.
    frequency = 42050
    pygame.mixer.init(frequency)
    pygame.mixer.music.load('audio/OST.mp3')
    pygame.mixer.music.play(-1)
    pygame.init()
    ufo_effect = pygame.mixer.Sound('audio/ufo.wav')
    ai_settings = Settings()
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption("Alien Invasion")

    # Make the Play button.
    play_button = Button(ai_settings, screen, "Play")
    highscore_button = Button2(ai_settings, screen, "High Score")
    back_button = Button2(ai_settings, screen, "Back")

    # Make a ship.
    ship = Ship(ai_settings, screen)

    # Make a ufo
    ufo = Ufo(ai_settings, screen)

    # Make a group to store bullets in.
    bullets = Group()
    bullets2 = Group()

    # Make an alien
    aliens = Group()

    # Make barriers
    barriers = Group()

    # Create the fleet of aliens.
    gf.create_fleet(ai_settings, screen, ship, aliens)

    # Create a group of barriers
    gf.create_barriers(ai_settings, screen, ship, barriers)

    # Create an instance to store game statistics and create a scoreboard.
    stats = GameStats(ai_settings)
    highScoreFile = open("highscore.txt", "r")
    stats.high_score = int(highScoreFile.readline())
    highScoreFile.close()
    sb = Scoreboard(ai_settings, screen, stats)
    spaceText = Text(ai_settings, screen, "SPACE", 200, 40,
                     ai_settings.screen_width / 2 - 50, 40, (255, 255, 255))
    invadersText = Text(ai_settings, screen, "INVADERS", 200, 40,
                        ai_settings.screen_width / 2 - 75, 80, (0, 255, 0))
    pinkyPicture = Picture(ai_settings, screen,
                           ai_settings.screen_width / 2 - 75, 190,
                           pygame.image.load('images/pinky_2.png'))
    pinkyText = Text(ai_settings, screen, "= 10 PTS     PINKY", 200, 40,
                     ai_settings.screen_width / 2, 190, (255, 255, 255))
    blueyPicture = Picture(ai_settings, screen,
                           ai_settings.screen_width / 2 - 75, 240,
                           pygame.image.load('images/bluey_2.png'))
    blueyText = Text(ai_settings, screen, "= 20 PTS     BLUEY", 200, 40,
                     ai_settings.screen_width / 2, 240, (255, 255, 255))
    greenyPicture = Picture(ai_settings, screen,
                            ai_settings.screen_width / 2 - 75, 290,
                            pygame.image.load('images/greeny_2.png'))
    greenyText = Text(ai_settings, screen, "= 40 PTS     GREENY", 200, 40,
                      ai_settings.screen_width / 2, 290, (255, 255, 255))
    oscarPicture = Picture(ai_settings, screen,
                           ai_settings.screen_width / 2 - 75, 340,
                           pygame.image.load('images/oscar.png'))
    oscarText = Text(ai_settings, screen, "= ???           OSCAR", 200, 40,
                     ai_settings.screen_width / 2, 340, (255, 255, 255))
    list = None
    animation_clock = ai_settings.animation_clock

    while True:
        highscoreText = Text(ai_settings, screen,
                             "HIGH SCORE: " + str(stats.high_score), 200, 40,
                             ai_settings.screen_width / 2 - 100, 40,
                             (255, 255, 255))
        menu_loop = True
        pygame.mixer.quit()
        pygame.mixer.init(frequency)
        pygame.mixer.music.load('audio/OST.mp3')
        pygame.mixer.music.play(-1)
        pygame

        while menu_loop:
            menu_loop = gf.check_menu_events(ai_settings, screen, stats, sb,
                                             play_button, ship, aliens,
                                             bullets, highscore_button,
                                             back_button, highscoreText,
                                             bullets2)
            gf.update_menu_screen(ai_settings, screen, play_button,
                                  highscore_button, spaceText, invadersText,
                                  pinkyPicture, blueyPicture, greenyPicture,
                                  oscarPicture, pinkyText, blueyText,
                                  greenyText, oscarText)

        # Start the main loop for the game.
        while stats.game_active:
            gf.check_events(ai_settings, screen, stats, sb, play_button, ship,
                            aliens, bullets)
            if stats.game_active:
                ship.update()
                gf.update_barriers(ai_settings, screen, barriers, aliens, ship)
                temp = gf.update_bullets(ai_settings, screen, stats, sb, ship,
                                         aliens, bullets, bullets2, ufo,
                                         barriers)
                if temp is not None:
                    list = temp
                gf.update_aliens(ai_settings, stats, screen, sb, ship, aliens,
                                 bullets, bullets2, ufo)

            animation_clock = gf.update_screen(ai_settings, screen, stats, sb,
                                               ship, aliens, bullets,
                                               play_button, bullets2, ufo,
                                               barriers, list, animation_clock)
Ejemplo n.º 27
0
def campaign(c, background, stock, store):

    debug(c.DEBUG, "ENTERING: campaign")
    load_song(c, "It's Melting.ogg")

    versionID = stock.getVersion()

    #    pygame.key.set_repeat(0, 0)

    allSprites = pygame.sprite.Group()
    ringSprite = pygame.sprite.GroupSingle()
    circSprites = pygame.sprite.LayeredUpdates()
    buttonSprites = pygame.sprite.Group()  # @UnusedVariable
    starSprites = pygame.sprite.LayeredUpdates()
    caughtSprite = pygame.sprite.GroupSingle()
    dieingSprites = pygame.sprite.GroupSingle()
    scoreSprite = pygame.sprite.GroupSingle()
    pBox = playBox()  # a jukebox for handling music settings.

    ring = Ring(c.CENTER, stock.campaign["Ring"], stock.campaign["Ring Glow"],
                c.FULLSCREEN)
    '''CREATE IMAGES'''
    ring.add(ringSprite, allSprites)
    scoreboard = Scoreboard(c.DISPLAY_W, c.DISPLAY_H)
    scoreboard.add(scoreSprite, allSprites)
    box_img = stock.campaign["RGB Light"]
    background_rect = background.get_rect()
    background_rect.center = c.CENTER
    OGBackground = background.copy()
    '''INSTANTIATING OTHER VARIABLES'''
    rotAngle = 0  # background rotation angle
    waitCounterCirc = 0
    waitCounterStar = 0
    circleWaitStart = 0
    circleWaitMade = 0
    starWaitStart = 0
    starWaitMade = 0
    finishedCircleActions = False
    finishedStarActions = False
    circleAction = '_'
    starAction = '_'
    counter = 0
    starWaiting = False
    circleWaiting = False
    pauseStartTime = None  #datetime variable
    pauseEndTime = None  #datetime variable
    r = 0
    g = 0
    b = 0
    pause_selection = 0
    gamePaused = False
    total_input = 0
    fpsList = []
    toggle_color_r = False
    toggle_color_g = False
    toggle_color_b = False
    display_sprites = True
    controls = c.CONTROL_LIST
    leftHold = False
    rightHold = False
    upHold = False
    downHold = False
    #quitGame = False  # if user returns a True from pause, we quit game, etc.
    startTime = 0
    genList = os.path.join(c.DATA_DIR, 'campaign_commands/genCommands.txt')
    circleList = os.path.join(c.DATA_DIR,
                              'campaign_commands/circleCommands.txt')
    starList = os.path.join(c.DATA_DIR, 'campaign_commands/starCommands.txt')
    genList, circleList, starList = commander(c, genList, circleList,
                                              starList)  # commander takes the
    #                     commands.txt and converts it into a formatted list.
    circleList, starList = iter(circleList), iter(starList)

    # take in the genList parameters now, before the level begins.
    for loop in range(len(genList)):
        setting = genList[loop]
        if setting[0] == 'B':
            # if the command is BPM, set the proper variables.
            pBox.cWait = setting[1]
            pBox.fWait = setting[2]
            pBox.cSpeed = setting[3]
            pBox.fSpeed = setting[4]
        elif setting[0] == 'J':
            __startTime = setting[1]  #different startTime, unused
        # change the general speed for circles/stars
        elif setting[0][0] == 'W':
            if setting[0] == 'WG':
                pBox.cWait = setting[1]
                pBox.fWait = setting[1]
            elif setting[0] == 'WC':
                pBox.cWait = setting[1]
            elif setting[0] == 'WF':
                pBox.fWait = setting[1]
    """BUTTON / SPRITE RENDERING"""
    r_letter = c.FONT_LARGE.render('R', True, c.RED)
    r_letter.scroll(2, 0)
    r_letter_rect = r_letter.get_rect()
    r_letter_rect.center = (c.CENTER_X - 50, (c.CENTER_Y * 2) - 20)
    box_rectR = r_letter_rect

    g_letter = c.FONT_LARGE.render('G', True, c.GREEN)
    g_letter.scroll(1, 0)
    g_letter_rect = g_letter.get_rect()
    g_letter_rect.center = (c.CENTER_X, (c.CENTER_Y * 2) - 20)
    box_rectG = g_letter_rect

    b_letter = c.FONT_LARGE.render('B', True, c.BLUE)
    b_letter.scroll(2, 0)
    b_letter_rect = b_letter.get_rect()
    b_letter_rect.center = (c.CENTER_X + 50, (c.CENTER_Y * 2) - 20)
    box_rectB = b_letter_rect

    debug(c.DEBUG, "Variable and object instantiating successful.")
    showSplashScreen(c, stock)
    songLength = store.music["Spicy Chips"].get_length()
    #pygame.mixer.music.set_endevent(USEREVENT)
    debug(c.DEBUG, "Song loading successful, main game loop about to begin.")
    # --Main Game Loop//--
    playing_campaign = True
    startTime = datetime.datetime.now()
    pygame.mixer.music.play()
    while playing_campaign:
        counter += 1
        waitCounterCirc += 1
        waitCounterStar += 1
        # Paint the background
        c.DISPLAYSURFACE.fill((0, 0, 0))
        #c.DISPLAYSURFACE.blit(background, background_rect)
        #if not c.FULLSCREEN:
        #   if counter%2 == 0:
        #      background, background_rect, rotAngle = \
        #     rotateBackground(c.CENTER, OGBackground, counter, rotAngle)
        """LOGGING output information: FPS, event info, AA, etc."""
        # for every 30 or FPS number of frames, print an average fps.
        fpsList.append(c.FPSCLOCK.get_fps())
        if counter == (c.FPS):
            AverageFPS = mean(fpsList)
            debug(c.DEBUG, ("Average FPS: {0}".format(AverageFPS)))
            debug(c.DEBUG,
                  ("Current Score: {0}".format(scoreboard.scoreString)))
            counter = 0
            pygame.display.set_caption('RGB. FPS: {0}'.format(mean(fpsList)))
            fpsList = []

            #===================================================================
            # this includes other things that i feel like should only be done
            # once a second, to save computation time, such as song ending check
            #===================================================================
            # test real quick to see if the song is over.
            deltaTime = (datetime.datetime.now() - startTime).total_seconds()
            if deltaTime > songLength:
                timeMessage = "SongTime: {0}, GameTIme: {1}".format(
                    songLength, deltaTime)
                debug(c.DEBUG, timeMessage)
                pygame.mixer.music.stop()
                playing_campaign = False
                debug(c.DEBUG, "MUSIC ENDED, CAMPAIGN SESSION OVER")
        """TAKE ACTION COMMAND LIST"""
        # for every new action, if the wait was long enough, perform the action
        if not circleWaiting:
            if not finishedCircleActions:
                try:
                    circleAction = circleList.next()
                except:
                    finishedCircleActions = True
            # if the circleAction is to spawn a circle/star, gotta que it up.
            if circleAction[0] == 'C':
                circleWaiting = True
            # change the general speed for circles/stars
            elif circleAction[0] == 'CS':
                if circleAction[0] == 'CS':
                    pBox.cSpeed = circleAction[1]
            elif circleAction[0][0] == 'W':
                if circleAction[0] == 'W':
                    circleWaitStart = datetime.datetime.now()
                    circleWaiting = True
                    circleWaitMade = datetime.datetime.now(
                    )  # time started waiting
                elif circleAction[0] == 'WC':
                    pBox.cWait = circleAction[1]
            elif circleAction[0] == 'S':
                pygame.mixer.music.stop()
                playing_campaign = False
        if circleWaiting:
            # All main actions have to wait before they can be performed,
            # so once an action is read, waiting becomes True, and we test to
            # see if the time passed is valid for the given wait time.
            if circleAction[0] == 'C':
                if waitCounterCirc >= pBox.cWait:
                    if circleAction[2] == '':
                        # if there is no given speed, then it's the global
                        # speed. . .
                        tempSpeed = pBox.cSpeed
                    else:
                        tempSpeed = circleAction[2]
                    tempColor = circleAction[1]
                    debug(c.DEBUG,
                          ("{0}'s speed: {1}".format(tempColor, tempSpeed)))
                    tempCirc = Circle(stock.campaign['Circle'], c.CENTER,
                                      tempSpeed, tempColor, pBox.layer)
                    tempCirc.add(circSprites, allSprites)
                    circMade = datetime.datetime.now()  #for debugging
                    pBox.layer += 1  #determines which get drawn on top
                    circleWaiting = False
                    waitCounterCirc = 0
            elif circleAction[0] == 'W':
                change = datetime.datetime.now() - circleWaitStart
                # if the action is to JUST wait x amount of time
                if change.total_seconds() >= circleAction[1] / c.FPS:
                    circleWaiting = False
                    totalWaitTime = datetime.datetime.now() - circleWaitMade
                    debug(c.DEBUG,
                          ("Wait Time: ", totalWaitTime.total_seconds()))
                    waitCounterCirc = 0

        if not starWaiting:
            if not finishedStarActions:
                try:
                    starAction = starList.next()
                except:
                    finishedStarActions = True
            if starAction[0] == 'F':
                starWaiting = True
            # change the general speed for circles/stars
            elif starAction[0] == 'FS':
                pBox.fSpeed = starAction[1]
            elif starAction[0][0] == 'W':
                if starAction[0] == 'W':
                    starWaitStart = datetime.datetime.now()
                    starWaiting = True
                    starWaitMade = datetime.datetime.now(
                    )  # for debug purposes
                elif starAction[0] == 'WF':
                    pBox.fWait = starAction[1]
            elif starAction[0] == 'S':
                pygame.mixer.music.stop()
                playing_campaign = False
        if starWaiting:
            if starAction[0] == 'F':
                if waitCounterStar >= pBox.fWait:
                    if starAction[2] == '':
                        tempSpeed = pBox.fSpeed
                    else:
                        tempSpeed = starAction[2]
                    tempAngle = starAction[1]
                    images = (stock.campaign['Star Lit'],
                              stock.campaign['Star Unlit'])
                    tempStar = Star(images, c.CENTER, tempSpeed, tempAngle)
                    tempStar.add(starSprites, allSprites)
                    # no longer waiting, bring on the next starAction!
                    starWaiting = False
                    waitCounterStar = 0
            elif starAction[0] == 'W':
                change = datetime.datetime.now() - starWaitStart
                # if the starAction is to JUST wait x amount of time
                if change.total_seconds() >= starAction[1] / c.FPS:
                    starWaiting = False
                    totalWaitTime = datetime.datetime.now() - starWaitMade
                    debug(c.DEBUG,
                          ("Wait Time: ", totalWaitTime.total_seconds()))
                    waitCounterStar = 0
                    # we must also set the wait for the next starAction to 0,
                    # or else the wait would be Wx + Wcircle/star.
        """EVENT HANDLING INPUT"""
        # grab all the latest input
        latest_events = pygame.event.get()
        for event in latest_events:
            if event.type == QUIT:
                playing_campaign = False
                pygame.quit()
                sys.exit()
            elif event.type == KEYDOWN and event.key == K_ESCAPE:
                if c.DEBUG:
                    # quit game
                    playing_campaign = False
                    pygame.mixer.music.stop()
                else:
                    # have to time how long pause takes, for the wait.
                    pauseStartTime = datetime.datetime.now()
                    pause_selection = pause(c, stock, c.DISPLAYSURFACE)
                    pauseEndTime = datetime.datetime.now()
                    pauseTotalTime = (pauseEndTime - pauseStartTime)
                    starWaitStart += pauseTotalTime
                    circleWaitStart += pauseTotalTime
            # --game-play events//--
            elif event.type == KEYDOWN and event.key == controls[0]:
                r = 255
                toggle_color_r = True
                total_input += 1
                ring.glowColor((r, g, b))
            elif event.type == KEYUP and event.key == controls[0]:
                r = 0
                toggle_color_r = False
                total_input += -1
                ring.glowColor((r, g, b))
            elif event.type == KEYDOWN and event.key == controls[1]:
                g = 255
                toggle_color_g = True
                total_input += 1
                ring.glowColor((r, g, b))
            elif event.type == KEYUP and event.key == controls[1]:
                g = 0
                toggle_color_g = False
                total_input += -1
                ring.glowColor((r, g, b))
            elif event.type == KEYDOWN and event.key == controls[2]:
                b = 255
                toggle_color_b = True
                total_input += 1
                ring.glowColor((r, g, b))
            elif event.type == KEYUP and event.key == controls[2]:
                b = 0
                toggle_color_b = False
                total_input += -1
                ring.glowColor((r, g, b))
            # Ring Spinning
            elif event.type == KEYDOWN and event.key == controls[5]:
                leftHold = True
                if upHold:
                    ring.spin('upleft')
                elif downHold:
                    ring.spin('downleft')
                else:
                    ring.spin('left')
            elif event.type == KEYUP and event.key == controls[5]:
                leftHold = False
            elif event.type == KEYDOWN and event.key == controls[6]:
                rightHold = True
                if upHold:
                    ring.spin('upright')
                elif downHold:
                    ring.spin('downright')
                else:
                    ring.spin('right')
            elif event.type == KEYUP and event.key == controls[6]:
                rightHold = False
            elif event.type == KEYDOWN and event.key == controls[3]:
                upHold = True
                if leftHold:
                    ring.spin('upleft')
                elif rightHold:
                    ring.spin('upright')
                else:
                    ring.spin('up')
            elif event.type == KEYUP and event.key == controls[3]:
                upHold = False
            elif event.type == KEYDOWN and event.key == controls[4]:
                downHold = True
                if leftHold:
                    ring.spin('downleft')
                elif rightHold:
                    ring.spin('downright')
                else:
                    ring.spin('down')
            elif event.type == KEYUP and event.key == controls[4]:
                downHold = False

            #====================================
            # --non-game-play events//--
            #====================================
            # if O is pressed, toggle context display -------TO BE REMOVED SOON
            elif event.type == KEYDOWN and event.key == K_o:
                if display_sprites == True:
                    display_sprites = False
                else:
                    display_sprites = True
            # if P is pressed, pause game.
            elif event.type == KEYUP and event.key == controls[7]:
                gamePaused = True
            """LOGGING of inputs"""
            if event.type == KEYDOWN or event.type == KEYUP:
                debug(c.DEBUG,
                      (pygame.event.event_name(event.type), event.dict))

        if pause_selection == 3:
            pygame.mixer.music.stop()
            playing_campaign = False
            return
        """CATCH CIRCLES MATCHING COLORS"""
        # catch matching circles!!
        for circle in circSprites.sprites():
            if circle.catchable:
                # catchable becomes true when the circle comes in contact
                # with the ring.
                debug(c.DEBUG, (circle.color, (r, g, b)))
                circle.add(caughtSprite)
                circle.remove(circSprites)
                circle.catch()
                totalCircTime = datetime.datetime.now() - circMade
        """REPEATED POINTS HOLDING COLORS CAUGHT"""
        # every .1 seconds should add or remove points based on accuracy
        if not (caughtSprite.sprite is None):
            for circle in caughtSprite.sprites():
                if circle.color == (r, g, b) and not (circle.dieing):
                    debug(c.DEBUG,
                          ("CIRCTIME: ", totalCircTime.total_seconds()))
                    #if the circle is more than 1 color, than we give bonus
                    if circle.color[0] + circle.color[1] + circle.color[
                            2] > 255:
                        scoreboard.addScore(40)
                    else:
                        scoreboard.addScore(20)
                    circle.remove(caughtSprite)
                    circle.add(dieingSprites)
                else:
                    circle.remove(caughtSprite)
                    circle.add(dieingSprites)
                    scoreboard.addScore(-10)

        # a circle begins in circSprites, then hits the ring, gets caught, and
        # goes into "caughtSprite" group. From there, it tries to match with
        # the user's input, then dies and goes into the "dieingCircs" group.
        # the purpose of the last group is just to have it animate the fading
        # or "dieing" sequence before disappearing.
        for circle in dieingSprites.sprites():
            circle.death()
        """DELETE FREE STARS SHOOTING"""
        for star in starSprites.sprites():

            if star.travDist >= (264 - star.speed) and not (star.shooting):
                # this tests the stars' distance, once it's close enough. . .
                if not ((ringSprite.sprite.angle) % 360
                        == (star.angleDeg) % 360):
                    debug(c.DEBUG, "Star Died at:")
                    debug(c.DEBUG, ("Ring Angle: ", ringSprite.sprite.angle))
                    debug(c.DEBUG, ("Star Angle: ", star.angleDeg))
                    star.kill()
                    scoreboard.addScore(-30)
                else:
                    debug(c.DEBUG, "Star Made it at:")
                    debug(c.DEBUG, ("Ring Angle: ", ringSprite.sprite.angle))
                    debug(c.DEBUG, ("Star Angle: ", star.angleDeg))
            if star.shooting:
                #                 debug(c.DEBUG, 'I AM SHOOTING1!')
                # if the star has gone off the screen in the x or y direction
                # kill it and add points!!
                if star.pos[0] > c.DISPLAY_W or star.pos[0] < 0:
                    star.kill()
                    #                     debug(c.DEBUG, 'KILLED A STAR')
                    scoreboard.addScore(50)
                elif star.pos[1] > c.DISPLAY_H or star.pos[1] < 0:
                    star.kill()
                    #                     debug(c.DEBUG, 'KILLED A STAR')
                    scoreboard.addScore(50)


#         debug(c.DEBUG, ('Stars #: {0}'.format(len(starSprites.sprites())))
        """DISPLAY SPRITE TOGGLE"""
        allSprites.update()
        if display_sprites == True:
            dieingSprites.draw(c.DISPLAYSURFACE)
            caughtSprite.draw(c.DISPLAYSURFACE)
            circSprites.draw(c.DISPLAYSURFACE)
            starSprites.draw(c.DISPLAYSURFACE)
            ringSprite.draw(c.DISPLAYSURFACE)
            if toggle_color_r:
                c.DISPLAYSURFACE.blit(r_letter, r_letter_rect)
            if toggle_color_g:
                c.DISPLAYSURFACE.blit(g_letter, g_letter_rect)
            if toggle_color_b:
                c.DISPLAYSURFACE.blit(b_letter, b_letter_rect)
            c.DISPLAYSURFACE.blit(box_img, box_rectR)
            c.DISPLAYSURFACE.blit(box_img, box_rectG)
            c.DISPLAYSURFACE.blit(box_img, box_rectB)
            scoreSprite.draw(c.DISPLAYSURFACE)
            c.DISPLAYSURFACE.blit(versionID, (0, 0))
        """DELAY"""
        c.FPSCLOCK.tick_busy_loop(c.FPS)
        """UPDATE"""
        pygame.display.flip()  # update()

        # have to time how long pause takes, for the wait.
        if gamePaused:
            pauseStartTime = datetime.datetime.now()
            pause_selection = pause(c, stock, pygame.display.get_surface())
            pauseEndTime = datetime.datetime.now()
            pauseTotalTime = (pauseEndTime - pauseStartTime)
            starWaitStart += pauseTotalTime
            circleWaitStart += pauseTotalTime
            gamePaused = False

    return
Ejemplo n.º 28
0
import random
import gameFunction as gf
from runner import Runner
from log import Log
from vine import Vine
from coin import Coin
from settings import Settings
from pygame.sprite import Group
from scoreboard import Scoreboard

pygame.init()
ai_settings = Settings()
ai_settings.initDynamicSettings()
pygame.display.set_caption('Side Scroller')
screen = pygame.display.set_mode((ai_settings.W, ai_settings.H))
sb = Scoreboard(ai_settings, screen)

clock = pygame.time.Clock()

runner = Runner(400, 300, 75, 75)
# for increasing speed, setting up obstacles, setting up coins respectively
pygame.time.set_timer(USEREVENT + 1, 500)
pygame.time.set_timer(USEREVENT + 2, random.randrange(3000, 5000))
pygame.time.set_timer(USEREVENT + 3, 3000)
run = True
objects = []
coins = Group()

while run:
    gf.checkEvents(runner, ai_settings)
    if ai_settings.gameActive:
Ejemplo n.º 29
0
from scoreboard import Scoreboard


def quit_game():
    global is_continue
    is_continue = False


screen = Screen()
screen.setup(width=800, height=600)
screen.bgcolor("black")
screen.title("Welcome to the Pong Game!")
screen.listen()
screen.tracer(0)

score = Scoreboard()

paddle_left = Paddle(-350, 0)
paddle_right = Paddle(350, 0)

ball = Ball()
screen.onkey(paddle_right.move_up, "o")
screen.onkey(paddle_right.move_down, "l")
screen.onkey(paddle_left.move_up, "w")
screen.onkey(paddle_left.move_down, "s")
screen.onkey(quit_game, "q")

is_continue = True
while is_continue:
    sleep(ball.move_speed)
    screen.update()
Ejemplo n.º 30
0
from turtle import Turtle
from gameconfig import game_screen, render_game, keyboard_config, start_animation, stop_animation
from snake import Snake
from food import Food
from scoreboard import Scoreboard

width = 900
height = 900
screen_color = 'black'
snake_size = 3

stop_animation()
snake = Snake()
snake.create_snake(shape='square', size=snake_size)
food = Food(width=width, height=height)
scoreboard = Scoreboard(height=height)
game_screen(width=width, height=height, color=screen_color)
keyboard_config(snake.up, 'Up')
keyboard_config(snake.down, 'Down')
keyboard_config(snake.left, 'Left')
keyboard_config(snake.right, 'Right')


def snake_find_food(food):
    return snake.head.distance(food) < 15


def snake_hit_wall():
    return snake.head.xcor() >= width / 2 or snake.head.xcor() <= -(
        width / 2) or snake.head.ycor() >= height / 2 or snake.head.ycor(
        ) <= -(height / 2)