Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import pygame
- from pygame.locals import *
- from pygame.color import *
- import pymunk
- import pygame.freetype
- from pygame.sprite import Sprite
- from pygame.rect import Rect
- import math
- """ This file contains the game loop. """
- #----- Initialisation -----#
- #-- Initialise the display
- pygame.init()
- myfont = pygame.font.SysFont('Comic Sans MS', 25)
- myfont2 = pygame.font.SysFont('Comic Sans MS', 20)
- pygame.display.set_mode()
- pygame.mixer.init()
- import welcome_screen
- screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
- game_state = welcome_screen.GameState.TITLE
- #-- Initialise the clock
- clock = pygame.time.Clock()
- #-- Initialise the physics engine
- space = pymunk.Space()
- space.gravity = (0.0, 0.0)
- #-- Import from the ctf framework
- import ai
- import boxmodels
- import images
- import gameobjects
- import maps
- #-- Initialize the title screen ---#
- # create a ui element
- quit_btn = welcome_screen.UIElement(
- center_position=(950, 750),
- font_size=40,
- bg_rgb=welcome_screen.BLUE,
- text_rgb=welcome_screen.WHITE,
- text="Quit", action=welcome_screen.GameState.QUIT)
- singleplayer_btn = welcome_screen.UIElement(
- center_position=(950, 550),
- font_size=40,
- bg_rgb=welcome_screen.BLUE,
- text_rgb=welcome_screen.WHITE,
- text="SINGLEPLAYER", action=welcome_screen.GameState.SINGLEPLAYER)
- multiplayer_btn = welcome_screen.UIElement(
- center_position=(950, 650),
- font_size=40,
- bg_rgb=welcome_screen.BLUE,
- text_rgb=welcome_screen.WHITE,
- text="MULTIPLAYER", action=welcome_screen.GameState.MULTIPLAYER)
- running_startup = True
- pygame.mixer.music.load('music.mp3')
- pygame.mixer.music.play()
- while running_startup:
- mouse_up = False
- for event in pygame.event.get():
- if event.type == pygame.MOUSEBUTTONUP and event.button == 1:
- mouse_up = True
- screen.blit(images.title,(0,0))
- ui_quit = quit_btn.update(pygame.mouse.get_pos(), mouse_up)
- ui_singleplayer = singleplayer_btn.update(pygame.mouse.get_pos(), mouse_up)
- ui_multiplayer = multiplayer_btn.update(pygame.mouse.get_pos(), mouse_up)
- if ui_quit is not None:
- pygame.quit()
- if ui_singleplayer is not None:
- number_of_players = 1
- running_mapselection = True
- running_startup = False
- if ui_multiplayer is not None:
- number_of_players = 2
- running_mapselection = True
- running_startup = False
- quit_btn.draw(screen)
- singleplayer_btn.draw(screen)
- multiplayer_btn.draw(screen)
- pygame.display.flip()
- map0_btn = welcome_screen.UIElement(
- center_position=(950, 550),
- font_size=40,
- bg_rgb=welcome_screen.BLUE,
- text_rgb=welcome_screen.WHITE,
- text="LEVEL 1", action=welcome_screen.GameState.LEVEL1)
- map1_btn = welcome_screen.UIElement(
- center_position=(950, 650),
- font_size=40,
- bg_rgb=welcome_screen.BLUE,
- text_rgb=welcome_screen.WHITE,
- text="LEVEL 2", action=welcome_screen.GameState.LEVEL2)
- while running_mapselection:
- mouse_up = False
- for event in pygame.event.get():
- if event.type == pygame.MOUSEBUTTONUP and event.button == 1:
- mouse_up = True
- screen.blit(images.title,(0,0))
- ui_level1 = map0_btn.update(pygame.mouse.get_pos(), mouse_up)
- ui_level2 = map1_btn.update(pygame.mouse.get_pos(), mouse_up)
- screen.blit(images.title,(0,0))
- if ui_level1 is not None:
- current_map = maps.map0
- running_mapselection = False
- if ui_level2 is not None:
- current_map = maps.map1
- running_mapselection = False
- map0_btn.draw(screen)
- map1_btn.draw(screen)
- pygame.display.flip()
- if running_mapselection == False:
- pygame.mixer.music.stop()
- pygame.mixer.music.load('vibtory.mp3')
- pygame.mixer.music.play()
- #-- Constants
- FRAMERATE = 200
- #-- Variables
- collision_type = {"bullet" : 1, "tank" : 2, "woodbox": 3, "rockbox": 4, "border_lines": 5}
- # Define the current level
- # List of all game objects
- game_objects_list = []
- tanks_list = []
- ai_list = []
- #-- Resize the screen to the size of the current level
- screen = pygame.display.set_mode(current_map.rect().size)
- #<INSERT GENERATE BACKGROUND>
- background = pygame.Surface(screen.get_size())
- for x in range(0, screen.get_size()[0], images.TILE_SIZE):
- for y in range(0, screen.get_size()[1], images.TILE_SIZE):
- background.blit(images.grass, (x, y))
- screen.blit(background,(0,0))
- #Create borders
- static_body = space.static_body
- border_lines = [pymunk.Segment(static_body, (0.0, 0.0), (current_map.width, 0.0), 0.0),
- pymunk.Segment(static_body, (current_map.width, 0.0), (current_map.width, current_map.height), 0.0),
- pymunk.Segment(static_body, (current_map. width, current_map.height), (0, current_map.height), 0.0),
- pymunk.Segment(static_body, (0, current_map.height), (0.0, 0.0), 0.0)]
- for line in border_lines:
- line.elasticity = 0.95
- line.friction = 0.9
- space.collision_type = 5
- space.add(border_lines)
- #<INSERT CREATE BOXES>
- #-- Create the boxes
- for x in range(0, current_map.width):
- for y in range(0, current_map.height):
- # Get the type of boxes
- box_type = current_map.boxAt(x, y)
- box_model = boxmodels.get_model(box_type)
- # If the box model is non null, create a box
- if(box_model != None):
- # Create a "Box" using the model "box_model" at the
- # coordinate (x,y) (an offset of 0.5 is added since
- # the constructor of the Box object expects to know
- # the centre of the box, have a look at the coordinate
- # systems section for more explanations).
- box = gameobjects.Box(x + 0.5, y + 0.5, box_model, space)
- game_objects_list.append(box)
- #<INSERT CREATE TANKS>
- #-- Create the tanks
- # Loop over the starting poistion
- for i in range(0, len(current_map.start_positions)):
- # Get the starting position of the tank "i"
- pos = current_map.start_positions[i]
- # Create the tank, images.tanks contains the image representing the tank
- #pos[2] ist för 0 nedanför
- tank = gameobjects.Tank(pos[0], pos[1], 0, images.tanks[i], space) # Creates a base
- base = gameobjects.GameVisibleObject(pos[0], pos[1], images.bases[i])
- # Add the tank to the list of objects to display
- game_objects_list.append(tank)
- # Add the tank to the list of tanks
- tanks_list.append(tank)
- tank.starting_position = (pos[0], pos[1])
- # Add the base to the list of objects to display
- game_objects_list.append(base)
- if i > number_of_players - 1:
- ais = ai.Ai(tank, game_objects_list, tanks_list, space, current_map)
- ai_list.append(ais)
- tank1 = tanks_list[0]
- tank2 = tanks_list[1]
- #<INSERT CREATE FLAG>
- #-- Create the flag
- flag = gameobjects.Flag(current_map.flag_position[0], current_map.flag_position[1])
- game_objects_list.append(flag)
- def collision_bullet_woodbox(arb, space, data):
- game_objects_list.remove(arb.shapes[0].parent)
- game_objects_list.remove(arb.shapes[1].parent)
- space.remove(arb.shapes[0], arb.shapes[0].body)
- space.remove(arb.shapes[1], arb.shapes[1].body)
- #soundeffect('woodbox.wav')
- return False
- handler2 = space.add_collision_handler(collision_type["bullet"],
- collision_type["woodbox"])
- handler2.begin = collision_bullet_woodbox
- def soundeffect(file_name):
- pygame.mixer.Sound(file_name)
- pygame.mixer.Sound(file_name).play().set_volume(0.8)
- def collision_bullet_tank(arb, space, data):
- soundeffect('explosion.wav')
- arb.shapes[1].parent.flag = None
- arb.shapes[1].parent.body.position = arb.shapes[1].parent.start_position
- game_objects_list.remove(arb.shapes[0].parent)
- space.remove(arb.shapes[0],arb.shapes[0].body)
- print("bullet tank")
- return False
- handler1 = space.add_collision_handler(collision_type["bullet"],
- collision_type["tank"])
- handler1.begin = collision_bullet_tank
- def collision_bullet_rockbox(arb, space, data):
- game_objects_list.remove(arb.shapes[0].parent)
- space.remove(arb.shapes[0], arb.shapes[0].body)
- return False
- handler3 = space.add_collision_handler(collision_type["bullet"],
- collision_type["rockbox"])
- handler3.begin = collision_bullet_rockbox
- def collision_bullet_borderlines(arb, spaces, data):
- game_objects_list.remove(arb.shapes[0].parent)
- space.remove(arb.shapes[0], arb.shapes[0].body)
- return False
- handler4 = space.add_collision_handler(collision_type["bullet"],
- collision_type["border_lines"])
- handler4.begin = collision_bullet_borderlines
- #----- Main Loop -----#
- ##
- #-- Control whether the game run
- skip_update = 0
- own_tank = tanks_list[3]
- screen_width=700
- if ui_level1 is not None or ui_level2 is not None:
- running = True
- while running:
- #-- Handle the events
- for event in pygame.event.get():
- # Check if we receive a QUIT event (for instance, if the user press the
- # close button of the wiendow) or if the user press the escape key.
- time = pygame.time.get_ticks()
- #Moves tank1
- if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
- running = False
- if event.type == KEYDOWN and event.key == K_UP:
- tank1.accelerate()
- if event.type == KEYUP and event.key == K_UP:
- tank1.stop_moving()
- if event.type == KEYDOWN and event.key == K_DOWN:
- tank1.decelerate()
- if event.type == KEYUP and event.key == K_DOWN:
- tank1.stop_moving()
- if event.type == KEYDOWN and event.key == K_LEFT:
- tank1.turn_left()
- if event.type == KEYUP and event.key == K_LEFT:
- tank1.stop_turning()
- if event.type == KEYDOWN and event.key == K_RIGHT:
- tank1.turn_right()
- if event.type == KEYUP and event.key == K_RIGHT:
- tank1.stop_turning()
- if event.type == KEYDOWN and event.key == K_RETURN:
- bullet = tank1.shoot(space)
- if bullet != None:
- game_objects_list.append(bullet)
- soundeffect('blast.wav')
- #Moves tank2
- if number_of_players == 2:
- if event.type == KEYDOWN and event.key == K_w:
- tank2.accelerate()
- if event.type == KEYUP and event.key == K_w:
- tank2.stop_moving()
- if event.type == KEYDOWN and event.key == K_s:
- tank2.decelerate()
- if event.type == KEYUP and event.key == K_s:
- tank2.stop_moving()
- if event.type == KEYDOWN and event.key == K_a:
- tank2.turn_left()
- if event.type == KEYUP and event.key == K_a:
- tank2.stop_turning()
- if event.type == KEYDOWN and event.key == K_d:
- tank2.turn_right()
- if event.type == KEYUP and event.key == K_d:
- tank2.stop_turning()
- if event.type == KEYDOWN and event.key == K_SPACE:
- if time - tank2.last_bullet > 1000:
- game_objects_list.append(tank2.shoot(space, time))
- soundeffect('blast.wav')
- #-- Update physics
- if skip_update == 0:
- # Loop over all the game objects and update their speed in function of their
- # acceleration.
- for obj in game_objects_list:
- obj.update()
- for ai in ai_list:
- ai.decide()
- ai.move_cycle_gen()
- ai.find_shortest_path()
- ai.tank.try_grab_flag(flag)
- #test2 = tank1.body.position
- #print(test2)
- skip_update = 2
- else:
- skip_update -= 1
- # Check collisions and update the objects position
- space.step(1 / FRAMERATE)
- # Check if flag is near tank. Grab the flag if it is
- for tank in tanks_list:
- tank.try_grab_flag(flag)
- def respawn_tanks():
- for i in range(len(tanks_list)):
- pos = current_map.start_positions[i]
- tanks_list[i].body.position = pos[0], pos[1]
- tanks_list[i].body.angle = pos[2]
- def print_playerscores():
- print("Scoreboard: ")
- for tank in tanks_list:
- print("Player " + str(tank.playernbr) + ": " + str(tank.score) + " points")
- def show_scorescreen(tankslist):
- x_middle = int(screen.get_size()[0]/2)
- y_middle = int(screen.get_size()[1]/2)
- pygame.draw.circle(screen, (255, 0, 0), (x_middle, y_middle), 200)
- for i in range(len(tankslist)):
- textsurface = myfont.render("P" + str(i+1) + ": " +
- str(tankslist[i].score), False, (0,0,0))
- screen.blit(textsurface, (150, 80+30*i))
- textsurface = myfont2.render("PRESS ENTER TO CONTINUE", False, (0, 0, 0))
- screen.blit(textsurface, (30, 110+30*len(tankslist)))
- pygame.display.flip()
- pygame.event.clear()
- #event = pygame.event.wait()
- pausing = True
- while pausing:
- for event in pygame.event.get():
- if event.type == KEYDOWN and event.key == K_RETURN:
- pausing = False
- for tank in tanks_list:
- # Check if tank has has_won
- if tank.has_won():
- tank.flag = None
- flag.x = current_map.flag_position[0]
- flag.y = current_map.flag_position[1]
- flag.orientation = 0
- tank.score += 1
- print("Player " + str(tank.playernbr) + " scored a point!")
- respawn_tanks()
- print_playerscores()
- show_scorescreen(tanks_list)
- # Update object that depends on an other object position (for instance a flag)
- for obj in game_objects_list:
- obj.post_update()
- #-- Update Display
- screen.blit(background,(0,0))
- #<INSERT DISPLAY BACKGROUND>
- #<INSERT DISPLAY OBJECTS>
- # Create bases
- # Update the display of the game objects on the screen
- for obj in game_objects_list:
- obj.update_screen(screen)
- # Redisplay the entire screen (see double buffer technique)
- pygame.display.flip()
- # Control the game framerate
- clock.tick(FRAMERATE)
- pygame.quit()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement