Advertisement
Guest User

simple game

a guest
Mar 23rd, 2018
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 13.33 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on Wed Mar 21 05:42:06 2018
  4.  
  5. @author: Hammer
  6. """
  7.  
  8. TITLE = "Hammer's Game"
  9. WIDTH = 480
  10. HEIGHT = 500
  11. FPS = 60
  12. FONT_NAME = 'arial'
  13. HS_FILE = "highscore.txt"
  14. SPRITESHEET = "spritesheet_jumper.png"
  15.  
  16. # Player properties
  17. PLAYER_ACC = 0.5
  18. PLAYER_FRICTION = -0.12
  19. PLAYER_GRAV = 0.8
  20. PLAYER_JUMP = 20
  21.  
  22. # Game properties
  23. BOOST_POWER = 60
  24. POW_SPAWN_PCT = 7
  25.  
  26. # Starting platforms
  27. PLATFORM_LIST = [(0, HEIGHT - 60),
  28.                  (WIDTH / 2 - 50, HEIGHT * 3 / 4 - 50),
  29.                  (125, HEIGHT - 350),
  30.                  (350, 200),
  31.                  (175, 100)]
  32.  
  33. # define colors
  34. WHITE = (255, 255, 255)
  35. BLACK = (0, 0, 0)
  36. RED = (255, 0, 0)
  37. GREEN = (0, 255, 0)
  38. BLUE = (0, 0, 255)
  39. YELLOW = (255, 255, 0)
  40. LIGHTBLUE = (0, 155, 155)
  41. BGCOLOR = LIGHTBLUE
  42. # Hammer's - Game
  43. import pygame as pg
  44. import random
  45. from os import path
  46.  
  47. class Game:
  48.     def __init__(self):
  49.         # initialize game window, etc
  50.         pg.init()
  51.         pg.mixer.init()
  52.         self.screen = pg.display.set_mode((WIDTH, HEIGHT))
  53.         pg.display.set_caption(TITLE)
  54.         self.clock = pg.time.Clock()
  55.         self.running = True
  56.         self.font_name = pg.font.match_font(FONT_NAME)
  57.         self.load_data()
  58.  
  59.     def load_data(self):
  60.         # load high score
  61.         self.dir = path.dirname(__file__)
  62.         with open(path.join(self.dir, HS_FILE), 'r') as f:
  63.             try:
  64.                 self.highscore = int(f.read())
  65.             except:
  66.                 self.highscore = 0
  67.         # load spritesheet image
  68.         img_dir = path.join(self.dir, 'img')
  69.         self.spritesheet = Spritesheet(path.join(img_dir, SPRITESHEET))
  70.         # load sounds
  71.         self.snd_dir = path.join(self.dir, 'snd')
  72.         self.jump_sound = pg.mixer.Sound(path.join(self.snd_dir, 'Jump33.wav'))
  73.         self.boost_sound = pg.mixer.Sound(path.join(self.snd_dir, 'Boost16.wav'))
  74.  
  75.     def new(self):
  76.         # start a new game
  77.         self.score = 0
  78.         self.all_sprites = pg.sprite.Group()
  79.         self.platforms = pg.sprite.Group()
  80.         self.powerups = pg.sprite.Group()
  81.         self.player = Player(self)
  82.         for plat in PLATFORM_LIST:
  83.             Platform(self, *plat)
  84.         pg.mixer.music.load(path.join(self.snd_dir, 'King-Ham-Lit.ogg'))
  85.         self.run()
  86.  
  87.     def run(self):
  88.         # Game Loop
  89.         pg.mixer.music.play(loops=-1)
  90.         self.playing = True
  91.         while self.playing:
  92.             self.clock.tick(FPS)
  93.             self.events()
  94.             self.update()
  95.             self.draw()
  96.         pg.mixer.music.fadeout(500)
  97.  
  98.     def update(self):
  99.         # Game Loop - Update
  100.         self.all_sprites.update()
  101.         # check if player hits a platform - only if falling
  102.         if self.player.vel.y > 0:
  103.             hits = pg.sprite.spritecollide(self.player, self.platforms, False)
  104.             if hits:
  105.                 lowest = hits[0]
  106.                 for hit in hits:
  107.                     if hit.rect.bottom > lowest.rect.bottom:
  108.                         lowest = hit
  109.                 if self.player.pos.x < lowest.rect.right + 10 and \
  110.                    self.player.pos.x > lowest.rect.left - 10:
  111.                     if self.player.pos.y < lowest.rect.centery:
  112.                         self.player.pos.y = lowest.rect.top
  113.                         self.player.vel.y = 0
  114.                         self.player.jumping = False
  115.  
  116.         # if player reaches top 1/4 of screen
  117.         if self.player.rect.top <= HEIGHT / 4:
  118.             self.player.pos.y += max(abs(self.player.vel.y), 2)
  119.             for plat in self.platforms:
  120.                 plat.rect.y += max(abs(self.player.vel.y), 2)
  121.                 if plat.rect.top >= HEIGHT:
  122.                     plat.kill()
  123.                     self.score += 10
  124.  
  125.         # if player hits powerup
  126.         pow_hits = pg.sprite.spritecollide(self.player, self.powerups, True)
  127.         for pow in pow_hits:
  128.             if pow.type == 'boost':
  129.                 self.boost_sound.play()
  130.                 self.player.vel.y = -BOOST_POWER
  131.                 self.player.jumping = False
  132.  
  133.         # Die!
  134.         if self.player.rect.bottom > HEIGHT:
  135.             for sprite in self.all_sprites:
  136.                 sprite.rect.y -= max(self.player.vel.y, 10)
  137.                 if sprite.rect.bottom < 0:
  138.                     sprite.kill()
  139.         if len(self.platforms) == 0:
  140.             self.playing = False
  141.  
  142.         # spawn new platforms to keep same average number
  143.         while len(self.platforms) < 6:
  144.             width = random.randrange(50, 100)
  145.             Platform(self, random.randrange(0, WIDTH - width),
  146.                      random.randrange(-75, -30))
  147.  
  148.     def events(self):
  149.         # Game Loop - events
  150.         for event in pg.event.get():
  151.             # check for closing window
  152.             if event.type == pg.QUIT:
  153.                 if self.playing:
  154.                     self.playing = False
  155.                 self.running = False
  156.             if event.type == pg.KEYDOWN:
  157.                 if event.key == pg.K_SPACE:
  158.                     self.player.jump()
  159.             if event.type == pg.KEYUP:
  160.                 if event.key == pg.K_SPACE:
  161.                     self.player.jump_cut()
  162.  
  163.     def draw(self):
  164.         # Game Loop - draw
  165.         self.screen.fill(BGCOLOR)
  166.         self.all_sprites.draw(self.screen)
  167.         self.screen.blit(self.player.image, self.player.rect)
  168.         self.draw_text(str(self.score), 22, WHITE, WIDTH / 2, 15)
  169.         # *after* drawing everything, flip the display
  170.         pg.display.flip()
  171.  
  172.     def show_start_screen(self):
  173.         # game splash/start screen
  174.         pg.mixer.music.load(path.join(self.snd_dir, 'Yippee.ogg'))
  175.         pg.mixer.music.play(loops=-1)
  176.         self.screen.fill(BGCOLOR)
  177.         self.draw_text(TITLE, 48, WHITE, WIDTH / 2, HEIGHT / 4)
  178.         self.draw_text("Arrows to move, Space to jump", 22, WHITE, WIDTH / 2, HEIGHT / 2)
  179.         self.draw_text("Press a key to play", 22, WHITE, WIDTH / 2, HEIGHT * 3 / 4)
  180.         self.draw_text("High Score: " + str(self.highscore), 22, WHITE, WIDTH / 2, 15)
  181.         pg.display.flip()
  182.         self.wait_for_key()
  183.         pg.mixer.music.fadeout(500)
  184.  
  185.     def show_go_screen(self):
  186.         # game over/continue
  187.         if not self.running:
  188.             return
  189.         pg.mixer.music.load(path.join(self.snd_dir, 'Yippee.ogg'))
  190.         pg.mixer.music.play(loops=-1)
  191.         self.screen.fill(BGCOLOR)
  192.         self.draw_text("GAME OVER", 48, WHITE, WIDTH / 2, HEIGHT / 4)
  193.         self.draw_text("Score: " + str(self.score), 22, WHITE, WIDTH / 2, HEIGHT / 2)
  194.         self.draw_text("Press a key to play again", 22, WHITE, WIDTH / 2, HEIGHT * 3 / 4)
  195.         if self.score > self.highscore:
  196.             self.highscore = self.score
  197.             self.draw_text("NEW HIGH SCORE!", 22, WHITE, WIDTH / 2, HEIGHT / 2 + 40)
  198.             with open(path.join(self.dir, HS_FILE), 'w') as f:
  199.                 f.write(str(self.score))
  200.         else:
  201.             self.draw_text("High Score: " + str(self.highscore), 22, WHITE, WIDTH / 2, HEIGHT / 2 + 40)
  202.         pg.display.flip()
  203.         self.wait_for_key()
  204.         pg.mixer.music.fadeout(500)
  205.  
  206.     def wait_for_key(self):
  207.         waiting = True
  208.         while waiting:
  209.             self.clock.tick(FPS)
  210.             for event in pg.event.get():
  211.                 if event.type == pg.QUIT:
  212.                     waiting = False
  213.                     self.running = False
  214.                 if event.type == pg.KEYUP:
  215.                     waiting = False
  216.  
  217.     def draw_text(self, text, size, color, x, y):
  218.         font = pg.font.Font(self.font_name, size)
  219.         text_surface = font.render(text, True, color)
  220.         text_rect = text_surface.get_rect()
  221.         text_rect.midtop = (x, y)
  222.         self.screen.blit(text_surface, text_rect)
  223. from random import choice, randrange
  224. vec = pg.math.Vector2
  225.  
  226. class Spritesheet:
  227.     # utility class for loading and parsing spritesheets
  228.     def __init__(self, filename):
  229.         self.spritesheet = pg.image.load(filename).convert()
  230.  
  231.     def get_image(self, x, y, width, height):
  232.         # grab an image out of a larger spritesheet
  233.         image = pg.Surface((width, height))
  234.         image.blit(self.spritesheet, (0, 0), (x, y, width, height))
  235.         image = pg.transform.scale(image, (width // 2, height // 2))
  236.         return image
  237.  
  238. class Player(pg.sprite.Sprite):
  239.     def __init__(self, game):
  240.         self.groups = game.all_sprites
  241.         pg.sprite.Sprite.__init__(self, self.groups)
  242.         self.game = game
  243.         self.walking = False
  244.         self.jumping = False
  245.         self.current_frame = 0
  246.         self.last_update = 0
  247.         self.load_images()
  248.         self.image = self.standing_frames[0]
  249.         self.rect = self.image.get_rect()
  250.         self.rect.center = (40, HEIGHT - 100)
  251.         self.pos = vec(40, HEIGHT - 100)
  252.         self.vel = vec(0, 0)
  253.         self.acc = vec(0, 0)
  254.  
  255.     def load_images(self):
  256.         self.standing_frames = [self.game.spritesheet.get_image(614, 1063, 120, 191),
  257.                                 self.game.spritesheet.get_image(690, 406, 120, 201)]
  258.         for frame in self.standing_frames:
  259.             frame.set_colorkey(BLACK)
  260.         self.walk_frames_r = [self.game.spritesheet.get_image(678, 860, 120, 201),
  261.                               self.game.spritesheet.get_image(692, 1458, 120, 207)]
  262.         self.walk_frames_l = []
  263.         for frame in self.walk_frames_r:
  264.             frame.set_colorkey(BLACK)
  265.             self.walk_frames_l.append(pg.transform.flip(frame, True, False))
  266.         self.jump_frame = self.game.spritesheet.get_image(382, 763, 150, 181)
  267.         self.jump_frame.set_colorkey(BLACK)
  268.  
  269.     def jump_cut(self):
  270.         if self.jumping:
  271.             if self.vel.y < -3:
  272.                 self.vel.y = -3
  273.  
  274.     def jump(self):
  275.         # jump only if standing on a platform
  276.         self.rect.y += 2
  277.         hits = pg.sprite.spritecollide(self, self.game.platforms, False)
  278.         self.rect.y -= 2
  279.         if hits and not self.jumping:
  280.             self.game.jump_sound.play()
  281.             self.jumping = True
  282.             self.vel.y = -PLAYER_JUMP
  283.  
  284.     def update(self):
  285.         self.animate()
  286.         self.acc = vec(0, PLAYER_GRAV)
  287.         keys = pg.key.get_pressed()
  288.         if keys[pg.K_LEFT]:
  289.             self.acc.x = -PLAYER_ACC
  290.         if keys[pg.K_RIGHT]:
  291.             self.acc.x = PLAYER_ACC
  292.  
  293.         # apply friction
  294.         self.acc.x += self.vel.x * PLAYER_FRICTION
  295.         # equations of motion
  296.         self.vel += self.acc
  297.         if abs(self.vel.x) < 0.1:
  298.             self.vel.x = 0
  299.         self.pos += self.vel + 0.5 * self.acc
  300.         # wrap around the sides of the screen
  301.         if self.pos.x > WIDTH + self.rect.width / 2:
  302.             self.pos.x = 0 - self.rect.width / 2
  303.         if self.pos.x < 0 - self.rect.width / 2:
  304.             self.pos.x = WIDTH + self.rect.width / 2
  305.  
  306.         self.rect.midbottom = self.pos
  307.  
  308.     def animate(self):
  309.         now = pg.time.get_ticks()
  310.         if self.vel.x != 0:
  311.             self.walking = True
  312.         else:
  313.             self.walking = False
  314.         # show walk animation
  315.         if self.walking:
  316.             if now - self.last_update > 180:
  317.                 self.last_update = now
  318.                 self.current_frame = (self.current_frame + 1) % len(self.walk_frames_l)
  319.                 bottom = self.rect.bottom
  320.                 if self.vel.x > 0:
  321.                     self.image = self.walk_frames_r[self.current_frame]
  322.                 else:
  323.                     self.image = self.walk_frames_l[self.current_frame]
  324.                 self.rect = self.image.get_rect()
  325.                 self.rect.bottom = bottom
  326.         # show idle animation
  327.         if not self.jumping and not self.walking:
  328.             if now - self.last_update > 350:
  329.                 self.last_update = now
  330.                 self.current_frame = (self.current_frame + 1) % len(self.standing_frames)
  331.                 bottom = self.rect.bottom
  332.                 self.image = self.standing_frames[self.current_frame]
  333.                 self.rect = self.image.get_rect()
  334.                 self.rect.bottom = bottom
  335.  
  336. class Platform(pg.sprite.Sprite):
  337.     def __init__(self, game, x, y):
  338.         self.groups = game.all_sprites, game.platforms
  339.         pg.sprite.Sprite.__init__(self, self.groups)
  340.         self.game = game
  341.         images = [self.game.spritesheet.get_image(0, 288, 380, 94),
  342.                   self.game.spritesheet.get_image(213, 1662, 201, 100)]
  343.         self.image = choice(images)
  344.         self.image.set_colorkey(BLACK)
  345.         self.rect = self.image.get_rect()
  346.         self.rect.x = x
  347.         self.rect.y = y
  348.         if randrange(100) < POW_SPAWN_PCT:
  349.             Pow(self.game, self)
  350.  
  351. class Pow(pg.sprite.Sprite):
  352.     def __init__(self, game, plat):
  353.         self.groups = game.all_sprites, game.powerups
  354.         pg.sprite.Sprite.__init__(self, self.groups)
  355.         self.game = game
  356.         self.plat = plat
  357.         self.type = choice(['boost'])
  358.         self.image = self.game.spritesheet.get_image(820, 1805, 71, 70)
  359.         self.image.set_colorkey(BLACK)
  360.         self.rect = self.image.get_rect()
  361.         self.rect.centerx = self.plat.rect.centerx
  362.         self.rect.bottom = self.plat.rect.top - 5
  363.  
  364.     def update(self):
  365.         self.rect.bottom = self.plat.rect.top - 5
  366.         if not self.game.platforms.has(self.plat):
  367.             self.kill()
  368. g = Game()
  369. g.show_start_screen()
  370. while g.running:
  371.     g.new()
  372.     g.show_go_screen()
  373.  
  374. pg.quit()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement