Advertisement
Guest User

ctf

a guest
Dec 10th, 2019
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 14.40 KB | None | 0 0
  1. import pygame
  2. from pygame.locals import *
  3. from pygame.color import *
  4. import pymunk
  5. import pygame.freetype
  6. from pygame.sprite import Sprite
  7. from pygame.rect import Rect
  8. import math
  9. """ This file contains the game loop. """
  10. #----- Initialisation -----#
  11.  
  12. #-- Initialise the display
  13. pygame.init()
  14. myfont = pygame.font.SysFont('Comic Sans MS', 25)
  15. myfont2 = pygame.font.SysFont('Comic Sans MS', 20)
  16. pygame.display.set_mode()
  17. pygame.mixer.init()
  18. import welcome_screen
  19.  
  20. screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
  21. game_state = welcome_screen.GameState.TITLE
  22.  
  23.  
  24.  
  25. #-- Initialise the clock
  26. clock = pygame.time.Clock()
  27.  
  28. #-- Initialise the physics engine
  29. space = pymunk.Space()
  30. space.gravity = (0.0,  0.0)
  31.  
  32. #-- Import from the ctf framework
  33. import ai
  34. import boxmodels
  35. import images
  36. import gameobjects
  37. import maps
  38.  
  39. #-- Initialize the title screen ---#
  40.  
  41.  
  42. # create a ui element
  43. quit_btn = welcome_screen.UIElement(
  44.     center_position=(950, 750),
  45.     font_size=40,
  46.     bg_rgb=welcome_screen.BLUE,
  47.     text_rgb=welcome_screen.WHITE,
  48.     text="Quit", action=welcome_screen.GameState.QUIT)
  49.  
  50. singleplayer_btn = welcome_screen.UIElement(
  51.     center_position=(950, 550),
  52.     font_size=40,
  53.     bg_rgb=welcome_screen.BLUE,
  54.     text_rgb=welcome_screen.WHITE,
  55.     text="SINGLEPLAYER", action=welcome_screen.GameState.SINGLEPLAYER)
  56.  
  57. multiplayer_btn = welcome_screen.UIElement(
  58.     center_position=(950, 650),
  59.     font_size=40,
  60.     bg_rgb=welcome_screen.BLUE,
  61.     text_rgb=welcome_screen.WHITE,
  62.     text="MULTIPLAYER", action=welcome_screen.GameState.MULTIPLAYER)
  63.  
  64. running_startup = True
  65.  
  66.  
  67. pygame.mixer.music.load('music.mp3')
  68. pygame.mixer.music.play()
  69.  
  70. while running_startup:
  71.     mouse_up = False
  72.     for event in pygame.event.get():
  73.         if event.type == pygame.MOUSEBUTTONUP and event.button == 1:
  74.             mouse_up = True
  75.     screen.blit(images.title,(0,0))
  76.     ui_quit = quit_btn.update(pygame.mouse.get_pos(), mouse_up)
  77.     ui_singleplayer = singleplayer_btn.update(pygame.mouse.get_pos(), mouse_up)
  78.     ui_multiplayer = multiplayer_btn.update(pygame.mouse.get_pos(), mouse_up)
  79.     if ui_quit is not None:
  80.         pygame.quit()
  81.     if ui_singleplayer is not None:
  82.         number_of_players = 1
  83.         running_mapselection = True
  84.         running_startup = False
  85.     if ui_multiplayer is not None:
  86.         number_of_players = 2
  87.         running_mapselection = True
  88.         running_startup = False
  89.     quit_btn.draw(screen)
  90.     singleplayer_btn.draw(screen)
  91.     multiplayer_btn.draw(screen)
  92.     pygame.display.flip()
  93.  
  94.  
  95. map0_btn = welcome_screen.UIElement(
  96.     center_position=(950, 550),
  97.     font_size=40,
  98.     bg_rgb=welcome_screen.BLUE,
  99.     text_rgb=welcome_screen.WHITE,
  100.     text="LEVEL 1", action=welcome_screen.GameState.LEVEL1)
  101.  
  102. map1_btn = welcome_screen.UIElement(
  103.     center_position=(950, 650),
  104.     font_size=40,
  105.     bg_rgb=welcome_screen.BLUE,
  106.     text_rgb=welcome_screen.WHITE,
  107.     text="LEVEL 2", action=welcome_screen.GameState.LEVEL2)
  108.  
  109. while running_mapselection:
  110.     mouse_up = False
  111.     for event in pygame.event.get():
  112.         if event.type == pygame.MOUSEBUTTONUP and event.button == 1:
  113.             mouse_up = True
  114.     screen.blit(images.title,(0,0))
  115.     ui_level1 = map0_btn.update(pygame.mouse.get_pos(), mouse_up)
  116.     ui_level2 = map1_btn.update(pygame.mouse.get_pos(), mouse_up)
  117.     screen.blit(images.title,(0,0))
  118.     if ui_level1 is not None:
  119.         current_map = maps.map0
  120.         running_mapselection = False
  121.     if ui_level2 is not None:
  122.         current_map = maps.map1
  123.         running_mapselection = False
  124.     map0_btn.draw(screen)
  125.     map1_btn.draw(screen)
  126.     pygame.display.flip()
  127.  
  128. if running_mapselection == False:
  129.     pygame.mixer.music.stop()
  130.     pygame.mixer.music.load('vibtory.mp3')
  131.     pygame.mixer.music.play()
  132.  
  133. #-- Constants
  134. FRAMERATE = 200
  135.  
  136.  
  137. #-- Variables
  138. collision_type = {"bullet" : 1, "tank" : 2, "woodbox": 3, "rockbox": 4, "border_lines": 5}
  139. #   Define the current level
  140.  
  141. #   List of all game objects
  142. game_objects_list   = []
  143. tanks_list          = []
  144. ai_list             = []
  145.  
  146. #-- Resize the screen to the size of the current level
  147. screen = pygame.display.set_mode(current_map.rect().size)
  148.  
  149.  
  150. #<INSERT GENERATE BACKGROUND>
  151. background = pygame.Surface(screen.get_size())
  152.  
  153. for x in range(0, screen.get_size()[0], images.TILE_SIZE):
  154.     for y in range(0, screen.get_size()[1], images.TILE_SIZE):
  155.         background.blit(images.grass, (x, y))
  156.  
  157. screen.blit(background,(0,0))
  158. #Create borders
  159. static_body = space.static_body
  160. border_lines = [pymunk.Segment(static_body, (0.0, 0.0), (current_map.width, 0.0), 0.0),
  161.                 pymunk.Segment(static_body, (current_map.width, 0.0), (current_map.width, current_map.height), 0.0),
  162.                 pymunk.Segment(static_body, (current_map. width, current_map.height), (0, current_map.height), 0.0),
  163.                 pymunk.Segment(static_body, (0, current_map.height), (0.0, 0.0), 0.0)]
  164. for line in border_lines:
  165.     line.elasticity = 0.95
  166.     line.friction = 0.9
  167.     space.collision_type = 5
  168.  
  169. space.add(border_lines)
  170.  
  171.  
  172.  
  173. #<INSERT CREATE BOXES>
  174.  
  175. #-- Create the boxes
  176. for x in range(0, current_map.width):
  177.     for y in range(0,  current_map.height):
  178.         # Get the type of boxes
  179.         box_type  = current_map.boxAt(x, y)
  180.         box_model = boxmodels.get_model(box_type)
  181.         # If the box model is non null, create a box
  182.         if(box_model != None):
  183.             # Create a "Box" using the model "box_model" at the
  184.             # coordinate (x,y) (an offset of 0.5 is added since
  185.             # the constructor of the Box object expects to know
  186.             # the centre of the box, have a look at the coordinate
  187.             # systems section for more explanations).
  188.             box = gameobjects.Box(x + 0.5, y + 0.5, box_model, space)
  189.             game_objects_list.append(box)
  190.  
  191.  
  192. #<INSERT CREATE TANKS>
  193. #-- Create the tanks
  194. # Loop over the starting poistion
  195. for i in range(0, len(current_map.start_positions)):
  196.  
  197.     # Get the starting position of the tank "i"
  198.     pos = current_map.start_positions[i]
  199.     # Create the tank, images.tanks contains the image representing the tank
  200.     #pos[2] ist för 0 nedanför
  201.     tank = gameobjects.Tank(pos[0], pos[1], 0, images.tanks[i], space)    # Creates a base
  202.     base = gameobjects.GameVisibleObject(pos[0], pos[1], images.bases[i])
  203.  
  204.     # Add the tank to the list of objects to display
  205.     game_objects_list.append(tank)
  206.     # Add the tank to the list of tanks
  207.     tanks_list.append(tank)
  208.     tank.starting_position = (pos[0], pos[1])
  209.     # Add the base to the list of objects to display
  210.     game_objects_list.append(base)
  211.     if i > number_of_players - 1:
  212.         ais = ai.Ai(tank, game_objects_list, tanks_list, space, current_map)
  213.         ai_list.append(ais)
  214.  
  215. tank1 = tanks_list[0]
  216. tank2 = tanks_list[1]
  217.  
  218.  
  219.  
  220.  
  221. #<INSERT CREATE FLAG>
  222. #-- Create the flag
  223. flag = gameobjects.Flag(current_map.flag_position[0], current_map.flag_position[1])
  224. game_objects_list.append(flag)
  225.  
  226.  
  227.  
  228. def collision_bullet_woodbox(arb, space, data):
  229.     game_objects_list.remove(arb.shapes[0].parent)
  230.     game_objects_list.remove(arb.shapes[1].parent)
  231.     space.remove(arb.shapes[0], arb.shapes[0].body)
  232.     space.remove(arb.shapes[1], arb.shapes[1].body)
  233.     #soundeffect('woodbox.wav')
  234.     return False
  235.  
  236. handler2 = space.add_collision_handler(collision_type["bullet"],
  237.                                       collision_type["woodbox"])
  238. handler2.begin = collision_bullet_woodbox
  239.  
  240. def soundeffect(file_name):
  241.     pygame.mixer.Sound(file_name)
  242.     pygame.mixer.Sound(file_name).play().set_volume(0.8)
  243.  
  244.  
  245. def collision_bullet_tank(arb, space, data):
  246.     soundeffect('explosion.wav')
  247.     arb.shapes[1].parent.flag = None
  248.     arb.shapes[1].parent.body.position = arb.shapes[1].parent.start_position
  249.     game_objects_list.remove(arb.shapes[0].parent)
  250.     space.remove(arb.shapes[0],arb.shapes[0].body)
  251.     print("bullet tank")
  252.     return False
  253.  
  254. handler1 = space.add_collision_handler(collision_type["bullet"],
  255.                                       collision_type["tank"])
  256. handler1.begin = collision_bullet_tank
  257.  
  258. def collision_bullet_rockbox(arb, space, data):
  259.     game_objects_list.remove(arb.shapes[0].parent)
  260.     space.remove(arb.shapes[0], arb.shapes[0].body)
  261.     return False
  262.  
  263. handler3 = space.add_collision_handler(collision_type["bullet"],
  264.                                       collision_type["rockbox"])
  265. handler3.begin = collision_bullet_rockbox
  266.  
  267. def collision_bullet_borderlines(arb, spaces, data):
  268.     game_objects_list.remove(arb.shapes[0].parent)
  269.     space.remove(arb.shapes[0], arb.shapes[0].body)
  270.     return False
  271.  
  272. handler4 = space.add_collision_handler(collision_type["bullet"],
  273.                                        collision_type["border_lines"])
  274. handler4.begin = collision_bullet_borderlines
  275.  
  276. #----- Main Loop -----#
  277. ##
  278. #-- Control whether the game run
  279.  
  280. skip_update = 0
  281.  
  282. own_tank = tanks_list[3]
  283. screen_width=700
  284.  
  285. if ui_level1 is not None or ui_level2 is not None:
  286.     running = True
  287.  
  288.  
  289.  
  290.  
  291.  
  292. while running:
  293.     #-- Handle the events
  294.  
  295.     for event in pygame.event.get():
  296.         # Check if we receive a QUIT event (for instance, if the user press the
  297.         # close button of the wiendow) or if the user press the escape key.
  298.  
  299.         time = pygame.time.get_ticks()
  300.  
  301.         #Moves tank1
  302.         if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
  303.             running = False
  304.         if event.type == KEYDOWN and event.key == K_UP:
  305.             tank1.accelerate()
  306.         if event.type == KEYUP and event.key == K_UP:
  307.             tank1.stop_moving()
  308.         if event.type == KEYDOWN and event.key == K_DOWN:
  309.             tank1.decelerate()
  310.         if event.type == KEYUP and event.key == K_DOWN:
  311.             tank1.stop_moving()
  312.         if event.type == KEYDOWN and event.key == K_LEFT:
  313.             tank1.turn_left()
  314.         if event.type == KEYUP and event.key == K_LEFT:
  315.             tank1.stop_turning()
  316.         if event.type == KEYDOWN and event.key == K_RIGHT:
  317.             tank1.turn_right()
  318.         if event.type == KEYUP and event.key == K_RIGHT:
  319.             tank1.stop_turning()
  320.         if event.type == KEYDOWN and event.key == K_RETURN:
  321.             bullet = tank1.shoot(space)
  322.             if bullet != None:
  323.                 game_objects_list.append(bullet)
  324.                 soundeffect('blast.wav')
  325.  
  326.         #Moves tank2
  327.         if number_of_players == 2:
  328.             if event.type == KEYDOWN and event.key == K_w:
  329.                 tank2.accelerate()
  330.             if event.type == KEYUP and event.key == K_w:
  331.                 tank2.stop_moving()
  332.             if event.type == KEYDOWN and event.key == K_s:
  333.                 tank2.decelerate()
  334.             if event.type == KEYUP and event.key == K_s:
  335.                 tank2.stop_moving()
  336.             if event.type == KEYDOWN and event.key == K_a:
  337.                 tank2.turn_left()
  338.             if event.type == KEYUP and event.key == K_a:
  339.                 tank2.stop_turning()
  340.             if event.type == KEYDOWN and event.key == K_d:
  341.                 tank2.turn_right()
  342.             if event.type == KEYUP and event.key == K_d:
  343.                 tank2.stop_turning()
  344.             if event.type == KEYDOWN and event.key == K_SPACE:
  345.                 if time - tank2.last_bullet > 1000:
  346.                     game_objects_list.append(tank2.shoot(space, time))
  347.                     soundeffect('blast.wav')
  348.  
  349.     #-- Update physics
  350.     if skip_update == 0:
  351.         # Loop over all the game objects and update their speed in function of their
  352.         # acceleration.
  353.         for obj in game_objects_list:
  354.             obj.update()
  355.         for ai in ai_list:
  356.             ai.decide()
  357.             ai.move_cycle_gen()
  358.             ai.find_shortest_path()
  359.             ai.tank.try_grab_flag(flag)
  360.             #test2 = tank1.body.position
  361.             #print(test2)
  362.         skip_update = 2
  363.     else:
  364.         skip_update -= 1
  365.  
  366.     #   Check collisions and update the objects position
  367.     space.step(1 / FRAMERATE)
  368.  
  369.     #   Check if flag is near tank. Grab the flag if it is
  370.     for tank in tanks_list:
  371.         tank.try_grab_flag(flag)
  372.  
  373.     def respawn_tanks():
  374.         for i in range(len(tanks_list)):
  375.             pos = current_map.start_positions[i]
  376.             tanks_list[i].body.position = pos[0], pos[1]
  377.             tanks_list[i].body.angle = pos[2]
  378.  
  379.     def print_playerscores():
  380.         print("Scoreboard: ")
  381.         for tank in tanks_list:
  382.             print("Player " + str(tank.playernbr) + ": " + str(tank.score) + " points")
  383.  
  384.     def show_scorescreen(tankslist):
  385.         x_middle = int(screen.get_size()[0]/2)
  386.         y_middle = int(screen.get_size()[1]/2)
  387.         pygame.draw.circle(screen, (255, 0, 0), (x_middle, y_middle), 200)
  388.         for i in range(len(tankslist)):
  389.             textsurface = myfont.render("P" + str(i+1) + ": " +
  390.                           str(tankslist[i].score), False, (0,0,0))
  391.             screen.blit(textsurface, (150, 80+30*i))
  392.         textsurface = myfont2.render("PRESS ENTER TO CONTINUE", False, (0, 0, 0))
  393.         screen.blit(textsurface, (30, 110+30*len(tankslist)))
  394.  
  395.         pygame.display.flip()
  396.         pygame.event.clear()
  397.         #event = pygame.event.wait()
  398.         pausing = True
  399.  
  400.         while pausing:
  401.             for event in pygame.event.get():
  402.                 if event.type == KEYDOWN and event.key == K_RETURN:
  403.                     pausing = False
  404.  
  405.  
  406.  
  407.     for tank in tanks_list:
  408.     # Check if tank has has_won
  409.         if tank.has_won():
  410.             tank.flag = None
  411.             flag.x = current_map.flag_position[0]
  412.             flag.y = current_map.flag_position[1]
  413.             flag.orientation = 0
  414.             tank.score += 1
  415.             print("Player " + str(tank.playernbr) + " scored a point!")
  416.             respawn_tanks()
  417.             print_playerscores()
  418.             show_scorescreen(tanks_list)
  419.  
  420.  
  421.     #   Update object that depends on an other object position (for instance a flag)
  422.     for obj in game_objects_list:
  423.         obj.post_update()
  424.  
  425.     #-- Update Display
  426.     screen.blit(background,(0,0))
  427.  
  428.  
  429.     #<INSERT DISPLAY BACKGROUND>
  430.  
  431.  
  432.     #<INSERT DISPLAY OBJECTS>
  433.  
  434.     # Create bases
  435.  
  436.  
  437.     # Update the display of the game objects on the screen
  438.     for obj in game_objects_list:
  439.         obj.update_screen(screen)
  440.  
  441.  
  442.     #   Redisplay the entire screen (see double buffer technique)
  443.     pygame.display.flip()
  444.  
  445.     #   Control the game framerate
  446.     clock.tick(FRAMERATE)
  447.  
  448. pygame.quit()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement