Ejemplo n.º 1
0
def run_game():
    pygame.init()
    #get start time
    start_time = pygame.time.get_ticks()
    settings = Settings()
    settings.mode = 'human'
    screen = pygame.display.set_mode((settings.screen_width,settings.screen_height))
    pygame.display.set_caption("Fill the bottle")
    conveyor_belt = gf.Conveyor_belt(screen,settings)
    tank = gf.Tank(screen,settings)
    #bottle = gf.Bottle(screen,conveyor_belt,tank,settings.color)
    #print(bottle)
    waterflow = Group()
    bottles = []
    scoreboard = gf.Scoreboard(screen,settings)
    game_state = GameStats(settings)
    timeline = gf.Timeline(screen,settings)
    while True:
        seconds = (pygame.time.get_ticks() - start_time) / 1000
        if seconds >= settings.time_limit:
        #if game_state.action_num >= settings.action_limit:
            print('Final score is %d'%sum(game_state.score_record[:]))
            if sum(game_state.score_record[:]) >= game_state.highest_score:
                game_state.highest_score = sum(game_state.score_record[:])
                print('New highest score reaches %d'%game_state.highest_score)
            #flag done and reward, that can be used in further training
            game_state.done = True
            game_state.reward = sum(game_state.score_record[:])
            #reset the game
            gf.reset(bottles,waterflow,game_state,tank,settings)
            game_state.round += 1
            print('New round!  round %d'%game_state.round)
            start_time = pygame.time.get_ticks()

        #update all components
        bottle = gf.add_bottle(screen,conveyor_belt,tank,settings.water_color,bottles,game_state)
        gf.check_event(bottle,screen,tank,waterflow,conveyor_belt,game_state,settings)
        gf.update_water(waterflow,conveyor_belt)
        timeline.update(game_state)
        #print('reward_fill is %f'%game_state.reward_fill)

        #show all components
        screen.fill(settings.bg_color)
        conveyor_belt.blitme()
        tank.blitme()
        scoreboard.show_score(game_state)
        timeline.draw()
        for bottle in bottles:
            bottle.update(settings.conveyor_speed)
            bottle.draw()
        for drop in waterflow.sprites():
            drop.draw(settings.water_color)


        pygame.display.flip()
Ejemplo n.º 2
0
def run_game():
    pygame.init()
    settings = Settings()
    screen = pygame.display.set_mode(
        (settings.screen_width, settings.screen_height))
    pygame.display.set_caption("Pong")

    # Make paddles
    paddle = Paddle(settings, screen)

    # Create the ball
    ball = Ball(settings, screen)

    # Setup the computer player
    cpu = Computer(settings, screen, ball)

    # Create scoring board
    stats = GameStats(settings)
    scoreboard = Scoreboard(settings, screen, stats)

    while True:
        gf.check_events(settings, screen, ball, paddle, stats)

        if stats.game_active:
            paddle.update()
            ball.update()
            cpu.update(ball, paddle)
            gf.update_screen(settings, screen, ball, paddle, scoreboard, stats)
        else:
            gf.display_start_screen(settings, screen, stats)
Ejemplo n.º 3
0
def run_game():
    pygame.init()
    clock = pygame.time.Clock()
    game_settings = Settings()
    screen = pygame.display.set_mode((game_settings.screen_width, game_settings.screen_height))
    game_menu = Menu(screen, "Game Menu")
    play_button = Button(game_settings, screen, "Play", 500, 250)
    option_button = Button(game_settings, screen, "Options", 500, 350)
    reset_button = Button(game_settings, screen, "Reset game", 500, 450)
    exit_button = Button(game_settings, screen, "Exit", 500, 550)
    pygame.display.set_caption("Alien Invasion")
    stats = GameStats(game_settings)
    score_board = Scoreboard(game_settings, screen, stats)
    player_ship = Ship(screen)
    rockets = Group()
    aliens = Group()

    create_alien_fleet(game_settings, screen, player_ship, aliens)

    # game loop
    while True:
        clock.tick(60)
        check_events(score_board, stats, game_settings, screen, player_ship, aliens, rockets, play_button, reset_button)
        if game_settings.game_active:
            player_ship.update_position()
            update_rockets(game_settings, stats, screen, player_ship, rockets, aliens, score_board)
            update_aliens(game_settings, stats, screen, player_ship, aliens, rockets)
        update_screen(game_settings, screen, player_ship, rockets, aliens, play_button,
                      option_button, exit_button, reset_button, game_menu, score_board)
Ejemplo n.º 4
0
def run_game():
    pygame.init()
    settings = Settings()
    screen = pygame.display.set_mode(
        (settings.screen_width, settings.screen_height))
    pygame.display.set_caption('Space War')
    play_button = Button(settings, screen, 'Play')
    spaceWarrior = SpaceWarrior(screen, settings)
    aliens = pygame.sprite.Group()
    bullets = pygame.sprite.Group()
    gf.create_fleet(settings, screen, aliens, spaceWarrior)
    stats = GameStats(settings)
    sb = Scoreboard(settings, screen, stats)

    # draw cycle
    while True:
        gf.check_events(settings, stats, screen, sb, spaceWarrior, aliens,
                        bullets, play_button)
        if stats.game_active:
            spaceWarrior.update()
            gf.update_aliens(settings, stats, screen, sb, spaceWarrior, aliens,
                             bullets)
            gf.update_bullets(settings, screen, stats, sb, spaceWarrior,
                              aliens, bullets)
        gf.update_screen(settings, stats, sb, screen, spaceWarrior, aliens,
                         bullets, play_button)
Ejemplo n.º 5
0
def start_game():
    pygame.init()
    game_settings = Settings()

    screen = pygame.display.set_mode(
        (game_settings.screen_width, game_settings.screen_height))

    pygame.display.set_caption("Starship Troopers")

    # Create the starship
    starship = Starship(game_settings, screen)

    # Create a group of missiles
    missiles = Group()

    # Create a group of aliens and a fleet
    aliens = Group()
    gf.create_alien_fleet(game_settings, screen, starship, aliens)

    while True:
        gf.check_for_events(game_settings, screen, starship, missiles)
        starship.update_position(game_settings)
        gf.update_missiles_position_and_count(missiles)
        gf.update_aliens(game_settings, aliens)
        gf.update_screen(game_settings, screen, starship, missiles, aliens)
Ejemplo n.º 6
0
def start():
    # initiating pygame
    pygame.init()
    # making instance for game settings
    gs = Settings()
    # passing argument defined as sequence of tuple
    screen = pygame.display.set_mode(gs.size)
    # passing caption for top of GUI
    pygame.display.set_caption(gs.caption)


    # making instance of ship
    ship = Ship(screen,gs)

    # Making instance of bullet
    bullets = Group()

    # Initiating main loop for  continuous update
    while True:
    #     for cehecking key/mouse inputs
    # calling function from game_function module
        gf.chk_events(gs,screen,ship,bullets)
    # updating the bullets
        bullets.update()
    # Updating the screen
        gf.update(gs,screen,ship,bullets)
Ejemplo n.º 7
0
 def __init__(self):
 #   Create Settings object
     self.settings = Settings()
 #   Create Score object
     self.score = Score()
 #   Set Game Number 
     self.game_number = 0
Ejemplo n.º 8
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("正义小飞船与邪恶外星人大战      制作:吴斌")

    # 创建Play按钮
    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()

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

    # 开始游戏的主循环
    while True:
        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)
            gf.update_aliens(ai_settings, stats, sb, screen, ship, aliens,
                             bullets)
        gf.uppdate_screen(ai_settings, screen, stats, sb, ship, aliens,
                          bullets, play_button)
Ejemplo n.º 9
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('Femi\'s Alien Invasion')

    # Make the play Button.
    play_button = Button(ai_settings, screen, "Play Game")

    # Make a ship, bullets, and aliens
    ship = Ship(ai_settings, screen)
    bullets = Group()
    aliens = Group()

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

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

    # Start the main loop for the game.
    while True:

        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)
            gf.update_aliens(ai_settings, screen, stats, sb, ship, aliens, bullets)

        gf.update_screen(ai_settings, screen, stats, sb, ship, aliens, bullets, play_button)
    def __init__(self):
        """Initialize the game, and create game resources."""
        pygame.init()
        self.settings = Settings()

        self.screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
        self.settings.screen_width = self.screen.get_rect().width
        self.settings.screen_height = self.screen.get_rect().height
        pygame.display.set_caption("Target Practice")

        self.ship = Ship(self)
        self.bullets = pygame.sprite.Group()
        self.target = Target(self)
        self.hitcount = 0

        self.play_button = Button(self, "Play")
Ejemplo n.º 11
0
 def __init__(self, host: str, port: int):
     """Initiate the server with host and port and create the clients dict"""
     self.host = host
     self.port = port
     self.clients = dict()
     self.server = self.create_server()
     self.settings = Settings()
     self.active_player = self.settings.active_player
Ejemplo n.º 12
0
def update_rounds(rounds):
    """deletes old rounds and updates position of rounds"""
    ai_settings = Settings()
    # Update pos round
    for bullet in rounds.copy():
        if bullet.rect.left >= ai_settings.win_width:
            rounds.remove(bullet)
        print(len(rounds))
Ejemplo n.º 13
0
    def __init__(self, screen, initial_position):
        super(Bullet, self).__init__()

        self.__screen = screen

        self.top = float(initial_position.top)

        self.rect = pygame.Rect(0, 0, self.__WIDTH, self.__HEIGHT)
        self.rect.centerx = initial_position.centerx
        self.rect.top = self.top
        self.color = Settings().bullet_color
Ejemplo n.º 14
0
    def __init__(self):
        """Initialize game."""
        pygame.mixer.pre_init(44100, -16, 1, 512)
        pygame.init()

        # Ensure correct screen size to be displayed.
        ctypes.windll.user32.SetProcessDPIAware()

        # Make settings object.
        self.settings = Settings()

        # Set screensize and caption.
        self.screen = pygame.display.set_mode(
            (self.settings.screen_width, self.settings.screen_height))
        pygame.display.set_caption(self.settings.caption)

        # Screen flags.
        self.main_menu = True
        self.play_game = False
        # TODO: Implement Main Menu screen.

        # Make a clock object to set fps limit.
        self.clock = pygame.time.Clock()

        # Make player object.
        self.player = Player(self.settings, self.screen)

        # Make Invader Fleet.
        self.invaders = Group()
        func.create_fleet(self.settings, self.screen, self.invaders)

        # Make GameStats object.
        self.game_stats = GameStats(self.settings)

        # Make ScoreBoard object.
        self.scoreboard = ScoreBoard(self.settings, self.screen,
                                     self.game_stats)

        # Make player shot object Group.
        self.player_shots = Group()
        self.invader_shots = Group()

        # Make group for ground and initialise it.
        self.ground_blocks = func.create_ground(self.settings, self.screen)

        # Make list of shield groups.
        self.shields = [
            func.create_shield(self.settings, self.screen, number)
            for number in range(4)
        ]
        # Make group for lives and initialise it.
        #self.remaining_lives = func.create_lives(self.settings, self.screen, self.player)

        self.frame_count = 0
Ejemplo n.º 15
0
 def __init__(self):
     self.name = 'Fill_bottle'
     pygame.init()
     self.start_time = pygame.time.get_ticks()
     self.settings = Settings()
     self.screen = pygame.display.set_mode((self.settings.screen_width, self.settings.screen_height))
     pygame.display.set_caption("Fill the bottle")
     self.conveyor_belt = gf.Conveyor_belt(self.screen,self.settings)
     self.tank = gf.Tank(self.screen,self.settings)
     self.waterflow = Group()
     self.bottles = []
     self.scoreboard = gf.Scoreboard(self.screen, self.settings)
     self.game_state = GameStats(self.settings)
     self.timeline = gf.Timeline(self.screen, self.settings)
     self.speedline = gf.Speedline(self.screen,self.settings)
     self.valveangle = gf.Valveangle(self.screen,self.settings,self.tank)
Ejemplo n.º 16
0
    def __init__(self):
        """Initialize game."""
        pygame.mixer.pre_init(44100, 16, 1, 4096)
        pygame.init()

        # Sound Channels.
        self.music_channel = pygame.mixer.Channel(1)

        self.screen = pygame.display.set_mode((800, 720))
        pygame.display.set_caption('Tetris')

        if platform.system() == 'Windows':
            # Ensure correct screen size to be displayed on Windows.
            ctypes.windll.user32.SetProcessDPIAware()

        # Game objects.
        self.settings = Settings()
        self.utils = Utilities(self.settings)
        self.sounds = Sounds()
        self.game_stats = GameStats(self.sounds)
        self.board = Board(self.screen, self.settings, self.sounds)
        self.scoreboard = Scoreboard(self.screen, self.settings,
                                     self.game_stats)
        self.music_selection = MusicSelection(self.screen, self.settings,
                                              self.sounds, self.music_channel)

        # Tetris shapes.
        self.current_shape = Shape(self.screen, self.settings, self.sounds,
                                   self.utils)
        self.next_shape = Shape(self.screen, self.settings, self.sounds,
                                self.utils, 600, 520)

        # Game flags.
        self.title_screen = True
        self.controls_screen = True
        self.select_music_screen = True
        self.game_over = False
        self.high_score_screen = True
        self.show_fps = False
        self.pause = False
        self.music_pause = False

        # Make a clock object to set fps limit.
        self.clock = pygame.time.Clock()

        # Database connection.
        self.db = DBConnection()
Ejemplo n.º 17
0
    def tic_game(self):
        """Start the game main function"""
        # Send player request for input
        self.broadcast(f'{self.active_player.name} turn')

        # get player input
        move = tf.validate_input(self.active_player.client,
                                 self.settings.board)
        print(f'{self.active_player.nickname} wrote: {move}')
        self.broadcast_move(move, self.active_player)

        # Add symbol to board game
        self.settings.board[move] = self.active_player.symbol
        time.sleep(0.5)

        # Concatenate board game and send to players
        board_state = tf.show_board(self.settings.board)
        self.broadcast_board(board_state)

        # Check for win or draw
        result, self.settings.game_active = tf.check_win(
            self.settings.game_active, self.settings.board)
        if result:
            self.broadcast(f'{self.active_player.name} won\n')
            print(f'{self.active_player.nickname} won')

        message, self.settings.game_active = tf.check_draw(
            self.settings.game_active, self.settings.board)
        if len(message) != 0:
            self.broadcast(message)

        if self.settings.game_active:
            self.active_player = tf.switch_player(self.settings.players.copy(),
                                                  self.active_player)
            return self.tic_game()
        else:
            self.broadcast('Would you like to play again? (y/n)')
            message1 = self.settings.players[0].client.recv(1024).decode(
                'utf-8')
            message2 = self.settings.players[1].client.recv(1024).decode(
                'utf-8')
            if message1.lower() == message2.lower() == 'y':
                self.settings = Settings()
                self.player_assignment()
            else:
                self.broadcast('Thank you for playing')
Ejemplo n.º 18
0
    def __init__(self):
        """Initialize game."""
        pygame.mixer.pre_init(44100, -16, 1, 512)
        pygame.init()

        # Ensure correct screen size to be displayed.
        ctypes.windll.user32.SetProcessDPIAware()
        # Set screensize and caption.
        self.settings = Settings()
        self.screen = pygame.display.set_mode(
            (self.settings.width, self.settings.height))
        pygame.display.set_caption(self.settings.caption)

        self.snake = Snake(self.screen, self.settings)
        self.food = func.create_food(self.screen, self.settings, self.snake)
        self.sounds = Sounds()
        self.keys = {'up': False, 'down': False, 'left': False, 'right': False}

        self.clock = pygame.time.Clock()
Ejemplo n.º 19
0
def run_game():
    #initializing game
    pygame.init()
    #creating an object so as to access variables values in class settings
    sn_settings = Settings()
    #drawing screen
    screen = pygame.display.set_mode(
        (sn_settings.screen_width, sn_settings.screen_height))
    #creating an object snake so as to access variables values in class Snake
    snake = Snake(screen, sn_settings)
    #a list to store values of snake body to track it's movement
    snake_list = []
    ##creating an object food so as to access variables values in class Food
    food = Food(screen, sn_settings)
    #adding screen caption
    pygame.display.set_caption("kings snake game")

    #to keep track of time while playing the game
    clock = pygame.time.Clock()
    # Make the Play button.
    play_button = Button(sn_settings, screen, "Play")
    #game statistics
    game_stats = GameStats(sn_settings)
    #game scores
    sb = Scoreboard(sn_settings, screen, game_stats)

    while True:
        #start main loop for the game
        if game_stats.game_active == True:
            #calling update in Snake class to automate snake movement
            snake.update(sn_settings)
        #watch for keyboard / mouse input
        Gf.check_event(screen, sn_settings, snake, game_stats, snake_list,
                       play_button, sb)
        #displaying screen objects

        Gf.update(screen, sn_settings, snake_list, snake, food, play_button,
                  game_stats, sb)
        #rate at which the screen is update
        clock.tick(sn_settings.snake_speed)
Ejemplo n.º 20
0
    def __init__(self):
        """Load game settings and initialize the game"""
        self.playing_field = []
        self.rounds_played = 0
        self.is_game_over = False

        # Load Settings
        self.settings = Settings()

        # Initialize Deck
        self.deck = Deck(self.settings)
        self.deck.shuffle_deck()

        # Initialize Players
        self.players = [
            Player(name=f"Player {i}")
            for i in range(1, self.settings.number_of_players + 1)
        ]

        # Give player game cards
        n_cards = len(self.deck) // len(self.players)
        for player in self.players:
            player.initialize_hand(self.deck, n_cards)
Ejemplo n.º 21
0
def run_game():
    pygame.init()
    ai_settings = Settings()
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_hight))
    gf.creat_mea(screen, ai_settings, ai_settings.meas)
    gf.creat_kua(screen, ai_settings, ai_settings.kua)
    gf.creat_mushroom(screen, ai_settings, ai_settings.mushrooms)
    clock = pygame.time.Clock()

    while 1:
        gf.check_event(ai_settings)
        gf.running(screen, ai_settings, ai_settings.kua, ai_settings.meas,
                   ai_settings.mushrooms)
        gf.update_kua_meas_mushrooms(ai_settings.meas, ai_settings.mushrooms,
                                     ai_settings.kua, ai_settings)
        gf.update_mea(screen, ai_settings.meas, ai_settings)
        gf.update_kua(ai_settings.kua, ai_settings, screen)
        gf.update_mushroom(screen, ai_settings.mushrooms, ai_settings)
        gf.check_score(ai_settings)
        pygame.display.update()

        clock.tick(ai_settings.fps)
Ejemplo n.º 22
0
def start_game():
    # start the game and make a screen object
    pygame.init()
    ai_settings = Settings()
    win = pygame.display.set_mode(
        (ai_settings.win_width, ai_settings.win_height))
    pygame.display.set_caption("The Gauntlet")

    # draw a plane so the screen
    plane = Plane(ai_settings, win)
    # Creates group to store rounds and enemies
    rounds = Group()
    enemies = Group()
    # create an enemy

    game_f.make_enemies(ai_settings, win, enemies)

    # Main game loop
    while True:
        game_f.ck_evt(ai_settings, win, plane, rounds)
        plane.update()
        rounds.update()
        game_f.update_rounds(rounds)
        game_f.update_win(ai_settings, win, plane, enemies, rounds)
Ejemplo n.º 23
0
def run_game():
    pygame.init()
    game_settings = Settings()
    screen = pygame.display.set_mode((game_settings.screen_width, game_settings.screen_height))
    pygame.display.set_caption("Snake Game")
    # 创建开始按钮
    play_button = Button(game_settings, screen, "Play")
    # 创建贪吃蛇
    snake = Snake(game_settings, screen)
    # 获取Clock对象,来实现固定速度
    clock = pygame.time.Clock()
    # 创建一个food
    foods = Group()
    foods.add(Food(screen, game_settings))
    # 通过时间控制刷新率
    time_passed_seconds = 0
    while True:
        # 计算经过的时间
        time_passed_seconds += clock.tick() / 1000.0
        gf.check_events(game_settings, screen, snake)
        if time_passed_seconds >= 0.5:
            snake.update(time_passed_seconds, game_settings)
            time_passed_seconds = 0
        gf.update_screen(game_settings, screen, snake, foods)
    def __init__(self):
        pg.init()
        pg.font.init()

        # init our settings
        self.settings = Settings(self)

        # FPS Counter
        self.clock = pg.time.Clock()
        self.font = pg.font.SysFont("Arial", 16)

        self.display = pg.display
        # you can also use SCREEN_SIZE
        self.screen = self.display.set_mode(self.settings.size, RESIZABLE)
        self.display.set_caption(self.settings.caption)

        self.running = True

        # image dimesions are 750 x 450
        # Home_ui is the basic surface we're blitting all the components to
        self.home_ui = ui.basic_ui.Home_Window(
            self.settings.screen_width, self.settings.screen_height,
            self.settings.screen_width, self.settings.screen_height
        )  # imgwidth, imgheight, screenwidth, screenheight
Ejemplo n.º 25
0
# 3/17/2018
# 4/20/2018 Refactoring
# help from pythonprogramming.net
# and their YouTube tutorials
#import tkinter as tk
from game_settings import Settings
from game_lineup import Lineup
from game_atbat import Atbat
import game_setup as gs
import json

# Create Objects
settings = Settings()
visitor = Lineup()
home = Lineup()

# Initialize Variables
v_linescore = []
h_linescore = []
LARGE_FONT = ("verdana", 14)
"""
# The controller class
class GameScreen(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        container = tk.Frame(self)
        container.grid(column=0, row=0)
        container.grid_rowconfigure(0,weight=1)
        container.grid_columnconfigure(0,weight=1)
        # creates the Frames (which are the screen/layouts)
        self.frames = {}
class TargetPractice:
    """Overall class to manage game assets and behavior."""
    def __init__(self):
        """Initialize the game, and create game resources."""
        pygame.init()
        self.settings = Settings()

        self.screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
        self.settings.screen_width = self.screen.get_rect().width
        self.settings.screen_height = self.screen.get_rect().height
        pygame.display.set_caption("Target Practice")

        self.ship = Ship(self)
        self.bullets = pygame.sprite.Group()
        self.target = Target(self)
        self.hitcount = 0

        self.play_button = Button(self, "Play")

    def run_game(self):
        """Start the main loop for the game."""
        while True:
            self._check_events()
            if self.settings.game_active:
                self.ship.update()
                self._update_bullets()
                self._update_target()
            self._update_screen()

    def _check_events(self):
        """Respond to keypresses and mouse events."""
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            elif event.type == pygame.MOUSEBUTTONDOWN:
                mouse_pos = pygame.mouse.get_pos()
                self._check_play_button(mouse_pos)
            elif event.type == pygame.KEYDOWN:
                self._check_keydown_events(event)
            elif event.type == pygame.KEYUP:
                self._check_keyup_events(event)

    def _check_keydown_events(self, event):
        """Respond to keypresses."""
        if event.key == pygame.K_UP:
            self.ship.moving_up = True
        elif event.key == pygame.K_DOWN:
            self.ship.moving_down = True
        elif event.key == pygame.K_SPACE and self.settings.game_active:
            self._fire_bullet()
        elif event.key == pygame.K_p and not self.settings.game_active:
            self._start_game()
        elif event.key == pygame.K_q:
            sys.exit()

    def _check_keyup_events(self, event):
        """Respond to to key Releases."""
        if event.key == pygame.K_UP:
            self.ship.moving_up = False
        elif event.key == pygame.K_DOWN:
            self.ship.moving_down = False

    def _check_play_button(self, mouse_pos):
        """Start a new game when the player clicks Play."""
        button_clicked = self.play_button.rect.collidepoint(mouse_pos)
        if button_clicked and not self.settings.game_active:
            self._start_game()

    def _start_game(self):
        # Hide the mouse cursor.
        pygame.mouse.set_visible(False)
        # Reset the game statistics/
        self.settings.game_active = True

        # Get rid of any remaining bullets & reset hitcount.
        self.bullets.empty()
        # Create a new fleet and center the ship.
        self.target.center_target()
        self.ship.center_ship()
        self.settings.initialize_dynamic_settings()

    def _fire_bullet(self):
        new_bullet = Bullet(self)
        self.bullets.add(new_bullet)

    def _update_bullets(self):
        """Position of bullets and get rid of old bullets."""
        # Update bullet positions.
        self.bullets.update()

        # Get rid of bullets that have dissapeared.
        for bullet in self.bullets.copy():
            if bullet.rect.right >= self.screen.get_rect().width:
                self.bullets.remove(bullet)
                self.settings.misses += 1
                if self.settings.misses >= 3:
                    self.settings.game_active = False
                    pygame.mouse.set_visible(True)
                    self.hitcount = 0
                    self.settings.misses = 0
                    break
            bullet.draw_bullet()

        self._check_bullet_target_collisions()

    def _check_bullet_target_collisions(self):
        """Respond to bullet-target collisions."""
        # Check for any bullets that have hit target.
        #    If so, get rid of the bullet keep the target.
        for bullet in self.bullets.copy():
            if bullet.is_collided_with(self.target):
                bullet.kill()
                self.hitcount += 1
                print("Good Hit #" + str(self.hitcount))
                if self.hitcount % 3 == 0:
                    self.settings.increase_speed()

    def _update_target(self):
        """
		Check if the fleet is at an edge,
		 then Update the positions of all aliens in the fleet."""
        self._check_target_edges()
        self.target.update()

    def _check_target_edges(self):
        """Respond if target hits edge"""
        if self.target.check_edges():
            self._change_target_direction()

    def _change_target_direction(self):
        self.settings.target_direction *= -1

    def _update_screen(self):
        """Update images on the screen, and flip to new screen."""
        self.screen.fill(self.settings.bg_color)
        self.ship.blitme()
        for bullet in self.bullets.sprites():
            bullet.draw_bullet()
        self.target.blitme()

        # Draw the play button if the game is inactive.
        if not self.settings.game_active:
            self.play_button.draw_button()

        pygame.display.flip()
Ejemplo n.º 27
0
def main():
    # Create Settings object
    settings = Settings()
    # Create Score object
    score = Score()
    # Determine mode
    console_mode = settings.console_mode

    #CONSOLE MODE
    if console_mode:
        visiting_team_name = input("Enter Visiting Team: ")
        home_team_name = input("Enter Home Team: ")
        print(f'\nThe matchup: {visiting_team_name} at {home_team_name}\n')

        #        v_linescore = []
        #        h_linescore = []

        #        v_lineup_box    = []
        #        v_pitching_box  = []
        v_box = Box(visiting_team_name)
        h_box = Box(home_team_name)

        # roster object
        v_roster = build.build_game_roster(visiting_team_name, 2018)
        h_roster = build.build_game_roster(home_team_name, 2018)

        # starters object
        v_starters = build.pick_starters_dh(v_roster)
        h_starters = build.pick_starters_dh(h_roster)
        # returns: rotation, lineup, bullpen, bench

        # batting order object
        v_battingorder = build.make_battingorder(v_starters["lineup"], True)
        h_battingorder = build.make_battingorder(h_starters["lineup"], True)

        # Print Roster info in verbose_mode
        if settings.verbose_mode:
            print(f'\nVisitors\n====')
            print(f'\n{visiting_team_name}\nLineup')
            for x in v_battingorder:
                print(f' {x["Position"]}: {x["LastName"]}')
            print(f'\nRotation')
            for x in v_starters["rotation"]:
                print(f' {x["LastName"]}')
            print(f'\nBullpen')
            for x in v_starters["bullpen"]:
                print(f' {x["LastName"]}')
            print('\nBench')
            for x in v_starters["bench"]:
                print(f' {x["LastName"]}')

            print(f'\nHome\n====')
            print(f'\n{home_team_name}\nLineup')
            for x in h_battingorder:
                print(f' {x["Position"]}: {x["LastName"]}')
            print(f'\nRotation')
            for x in h_starters["rotation"]:
                print(f' {x["LastName"]}')
            print('\nBullpen')
            for x in h_starters["bullpen"]:
                print(f' {x["LastName"]}')
            print(f'\nBench')
            for x in h_starters["bench"]:
                print(f' {x["LastName"]}')

        visitor = Lineup()
        visitor.pitcher = build.pick_starting_pitcher(v_starters["rotation"])
        visitor.lineup_dictionary = v_battingorder
        visitor.lineup_lastname = visitor.create_lineup_lastname(
            visitor.lineup_dictionary)

        home = Lineup()
        home.pitcher = build.pick_starting_pitcher(h_starters["rotation"])
        home.lineup_dictionary = h_battingorder
        home.lineup_lastname = home.create_lineup_lastname(
            home.lineup_dictionary)

        print(f'Pitching Matchup')
        print(f'{visiting_team_name}         {home_team_name}')
        print(
            f'{visitor.pitcher["FirstName"]} {visitor.pitcher["LastName"]}  {home.pitcher["FirstName"]} {home.pitcher["LastName"]}'
        )
        atbat = Atbat()

        for i in range(9):
            # Top of inning
            inning_top = atbat.inning_top(settings.inning + i,
                                          visitor.lineup_dictionary,
                                          settings.visitor_leads_off_inning,
                                          home.pitcher)
            score.v_score += inning_top["v_score"]
            #            v_linescore.append(inning_top["v_score"])
            v_box.linescore.append(inning_top["v_score"])
            settings.visitor_leads_off_inning = inning_top[
                "visitor_leads_off_inning"]
            settings.half_inning = "Bottom"
            #            v_lineup_box.append(inning_top["lineup_box"])
            #            h_pitching_box.append(inning_top["pitching_box"])
            v_box.lineup.append(inning_top["lineup_box"])
            h_box.pitching.append(inning_top["pitching_box"])
            if PLAY_BY_PLAY:
                print(f'{visiting_team_name}-{score.v_score}')
                print(f'{home_team_name}-{score.h_score}\n')
            # Bottom of inning
            inning_bottom = atbat.inning_bottom(settings.inning + i,
                                                home.lineup_dictionary,
                                                settings.home_leads_off_inning,
                                                visitor.pitcher)
            score.h_score += inning_bottom["h_score"]
            #            h_linescore.append(inning_bottom["h_score"])
            h_box.linescore.append(inning_bottom["h_score"])
            settings.home_leads_off_inning = inning_bottom[
                "home_leads_off_inning"]
            settings.half_inning = "Top"

            h_box.lineup.append(inning_bottom["lineup_box"])
            v_box.pitching.append(inning_bottom["pitching_box"])
            #            v_pitching_box.append(inning_bottom["pitching_box"])

            if PLAY_BY_PLAY:
                print(f'{visiting_team_name}-{score.v_score}')
                print(f'{home_team_name}-{score.h_score}\n')

        print(f'\nGAME OVER')
        print(visiting_team_name, end='   ')
        for r in v_box.linescore:
            print(r, end=' ')
        print(f' -- {score.v_score}')

        print(home_team_name, end='   ')
        for r in h_box.linescore:
            print(r, end=' ')
        print(f' -- {score.h_score}')

        #        print (f"\n\n--------------- v lineup box -----")
        #        gf.print_lineup_box(v_lineup_box)
        v_box_file = gf.save_box_as_json(v_box)
        h_box_file = gf.save_box_as_json(h_box)
        print(v_box.print_box(v_box_file))
        print(h_box.print_box(h_box_file))
Ejemplo n.º 28
0
def main():
    #   Create Settings object
    settings = Settings()
    #   Create Score object
    score = Score()
    #   Determine mode
    console_mode = settings.console_mode

    #  CONSOLE MODE
    if console_mode:
        # INPUT
        visiting_team_name = input("Enter Visiting Team: ")
        home_team_name = input("Enter Home Team: ")
        if PLAY_BY_PLAY:
            print(f'\nThe matchup: {visiting_team_name} at {home_team_name}\n')

        #   Create Box Score Objects
        v_box = Box(visiting_team_name)
        h_box = Box(home_team_name)

        #   Create Roster Objects
        v_roster = build.build_game_roster(visiting_team_name, YEAR)
        h_roster = build.build_game_roster(home_team_name, YEAR)

        #   Create Starters Objects
        #   returns lists: rotation, lineup, bullpen, bench
        v_starters = build.pick_starters_dh(v_roster)
        h_starters = build.pick_starters_dh(h_roster)

        #   Create Batting Order Object
        v_battingorder = build.make_battingorder(v_starters["lineup"], True)
        h_battingorder = build.make_battingorder(h_starters["lineup"], True)

        #   Print Roster Info when using verbose_mode
        if settings.verbose_mode:
            print(f'\nVisitors\n====')
            print(f'\n{visiting_team_name}\nLineup')
            for x in v_battingorder:
                print(f' {x["Position"]}: {x["LastName"]}')
            print(f'\nRotation')
            for x in v_starters["rotation"]:
                print(f' {x["LastName"]}')
            print(f'\nBullpen')
            for x in v_starters["bullpen"]:
                print(f' {x["LastName"]}')
            print('\nBench')
            for x in v_starters["bench"]:
                print(f' {x["LastName"]}')

            print(f'\nHome\n====')
            print(f'\n{home_team_name}\nLineup')
            for x in h_battingorder:
                print(f' {x["Position"]}: {x["LastName"]}')
            print(f'\nRotation')
            for x in h_starters["rotation"]:
                print(f' {x["LastName"]}')
            print('\nBullpen')
            for x in h_starters["bullpen"]:
                print(f' {x["LastName"]}')
            print(f'\nBench')
            for x in h_starters["bench"]:
                print(f' {x["LastName"]}')

        #   Create Lineup Objects
        visitor = Lineup()
        visitor.pitcher = build.pick_starting_pitcher(v_starters["rotation"])
        visitor.lineup_dictionary = v_battingorder
        visitor.lineup_lastname = visitor.create_lineup_lastname(
            visitor.lineup_dictionary)

        home = Lineup()
        home.pitcher = build.pick_starting_pitcher(h_starters["rotation"])
        home.lineup_dictionary = h_battingorder
        home.lineup_lastname = home.create_lineup_lastname(
            home.lineup_dictionary)

        print(f'Pitching Matchup')
        print(visiting_team_name.ljust(18, " ") + home_team_name)
        print(
            f'{ visitor.pitcher["FirstName"] } { visitor.pitcher["LastName"] }'
            .ljust(17, " ") +
            f' { home.pitcher["FirstName"]} {home.pitcher["LastName"]}')

        atbat = Atbat()

        for i in range(9):
            # TOP OF INNING
            inning_top = atbat.inning_top(settings.inning + i,
                                          visitor.lineup_dictionary,
                                          settings.visitor_leads_off_inning,
                                          home.pitcher)
            score.v_score += inning_top["v_score"]
            v_box.linescore.append(inning_top["v_score"])
            settings.visitor_leads_off_inning = inning_top[
                "visitor_leads_off_inning"]
            settings.half_inning = "Bottom"
            v_box.lineup.append(inning_top["lineup_box"])
            h_box.pitching.append(inning_top["pitching_box"])
            if PLAY_BY_PLAY:
                print(f'{visiting_team_name}-{score.v_score}')
                print(f'{home_team_name}-{score.h_score}\n')
            #   BOTTOM OF INNING
            inning_bottom = atbat.inning_bottom(settings.inning + i,
                                                home.lineup_dictionary,
                                                settings.home_leads_off_inning,
                                                visitor.pitcher)
            score.h_score += inning_bottom["h_score"]
            h_box.linescore.append(inning_bottom["h_score"])
            settings.home_leads_off_inning = inning_bottom[
                "home_leads_off_inning"]
            settings.half_inning = "Top"
            h_box.lineup.append(inning_bottom["lineup_box"])
            v_box.pitching.append(inning_bottom["pitching_box"])
            if PLAY_BY_PLAY:
                print(f'{visiting_team_name}-{score.v_score}')
                print(f'{home_team_name}-{score.h_score}\n')

        #   P O S T G A M E
        print(f'\nGAME OVER')
        print(visiting_team_name, end='   ')
        for r in v_box.linescore:
            print(r, end=' ')
        print(f' -- {score.v_score}')

        print(home_team_name, end='   ')
        for r in h_box.linescore:
            print(r, end=' ')
        print(f' -- {score.h_score}')

        v_box_file = v_box.save_box_as_json(v_box)
        h_box_file = h_box.save_box_as_json(h_box)
        print(v_box.print_box(v_box_file))
        print(h_box.print_box(h_box_file))
Ejemplo n.º 29
0
#Imports
import pygame
import game_functions
from pygame.sprite import Group
from game_settings import Settings
from player_ship import Ship

#Variables -EMPTY

#Objects
"""Im assuming pygame object is always around from the looks of this this is 
simply preparing it for changes."""
pygame.init()

current_settings = Settings()

#Screen Size set
screen = pygame.display.set_mode(
    (current_settings.screen_width, current_settings.screen_height))

players_ship = Ship(screen, current_settings)
bullets = Group()

#Functions


def run_game():

    #This sets the screens caption
    pygame.display.set_caption("Zim's Invasion.")
Ejemplo n.º 30
0
def run_game():

    #Create some groups of objects
    game_objects = Group()
    bullets = Group()
    aliens = Group()
    buttons = Group()
    
    #Initialize game settings
    game_settings = Settings()
    
    #Initialize game statistics
    game_stats = Stats()
    
    #Pygame initiation, and establish screen  
    pygame.init()
    screen = pygame.display.set_mode((game_settings.screen_width, 
                        game_settings.screen_height))
    pygame.display.set_caption(game_settings.screen_title)
    
    #Create background object
    background = Background(screen, game_settings)
    game_objects.add(background)
    
    #Create ship object
    ship = Ship(screen, game_settings)
    game_objects.add(ship)
    
    #Create fleet of aliens then add them to game objects and aliens groups
    gf.create_fleet(screen, game_settings, game_objects, aliens)
    
    #Create buttons then ass them to game_objects and buttons groups
    gf.create_start_buttons(screen, game_settings, game_objects, buttons)
    
    #Create clock object
    clock = Clock()
    
    #Some statistics labels
    level = Label(screen, "level: " + str(game_stats.level), 10, 10)
    game_objects.add(level)

    ammo = Label(screen, "ammo: " + str(ship.game_settings.ammo), 200, 10)
    game_objects.add(ammo)

    points = Label(screen, "score: " + str(game_stats.points), 400, 10)
    game_objects.add(points)

    #Update screen           
    gf.update_screen(game_objects)

    while True:
        if len(aliens) == 0:
            game_stats.level += 1
            game_settings.alien_speed_factor += 1
            game_settings.ammo = game_settings.ammo + game_settings.initial_ammo
            #Create fleet of aliens then add them to game objects and aliens groups
            gf.create_fleet(screen, game_settings, game_objects, aliens)
        
        #Check events key down or key up
        gf.check_events(game_stats, game_objects, ship, bullets, buttons)
    
        level.text = "level: " + str(game_stats.level)
        ammo.text = "ammo: " + str(ship.game_settings.ammo)
        points.text = "score: " + str(game_stats.points)
        
        if game_stats.game_started:
            #Check collisions
            gf.check_collisions(screen, game_settings, game_stats, game_objects, ship, aliens, bullets, buttons)
        
            #Update screen           
            gf.update_screen(game_objects)

        #Wait certain time to achieve 40fps 
        clock.tick(40)