Advertisement
Guest User

Pong in the SGE

a guest
Feb 9th, 2014
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 9.38 KB | None | 0 0
  1. #!/usr/bin/env python2
  2.  
  3. # Pong Example
  4. # Written in 2013, 2014 by Julian Marchant <onpon4@riseup.net>
  5. #
  6. # To the extent possible under law, the author(s) have dedicated all
  7. # copyright and related and neighboring rights to this software to the
  8. # public domain worldwide. This software is distributed without any
  9. # warranty.
  10. #
  11. # You should have received a copy of the CC0 Public Domain Dedication
  12. # along with this software. If not, see
  13. # <http://creativecommons.org/publicdomain/zero/1.0/>.
  14.  
  15. """Pong
  16.  
  17. A simple two-player Pong game.
  18.  
  19. """
  20.  
  21. from __future__ import division
  22. from __future__ import absolute_import
  23. from __future__ import print_function
  24. from __future__ import unicode_literals
  25.  
  26. import sge
  27.  
  28. PADDLE_SPEED = 4
  29. PADDLE_VERTICAL_FORCE = 1 / 12
  30. BALL_START_SPEED = 2
  31. BALL_ACCELERATION = 0.2
  32. BALL_MAX_SPEED = 15
  33. POINTS_TO_WIN = 10
  34. TEXT_OFFSET = 16
  35.  
  36.  
  37. class glob(object):
  38.  
  39.     # This class is for global variables.  While not necessary, using a
  40.     # container class like this is less potentially confusing than using
  41.     # actual global variables.
  42.  
  43.     player1 = None
  44.     player2 = None
  45.     ball = None
  46.     hud_sprite = None
  47.     bounce_sound = None
  48.     bounce_wall_sound = None
  49.     score_sound = None
  50.     game_in_progress = True
  51.  
  52.  
  53. class Game(sge.Game):
  54.  
  55.     def event_game_start(self):
  56.         self.mouse.visible = False
  57.  
  58.     def event_key_press(self, key, char):
  59.         if key == 'f8':
  60.             sge.Sprite.from_screenshot().save('screenshot.jpg')
  61.         elif key == 'f11':
  62.             self.fullscreen = not self.fullscreen
  63.         elif key == 'escape':
  64.             self.event_close()
  65.         elif key in ('p', 'enter'):
  66.             if glob.game_in_progress:
  67.                 self.pause()
  68.             else:
  69.                 glob.game_in_progress = True
  70.                 self.current_room.start()
  71.  
  72.     def event_close(self):
  73.         m = "Are you sure you want to quit?"
  74.         if sge.show_message(m, ("No", "Yes")):
  75.             self.end()
  76.  
  77.     def event_paused_key_press(self, key, char):
  78.         if key == 'escape':
  79.             # This allows the player to still exit while the game is
  80.             # paused, rather than having to unpause first.
  81.             self.event_close()
  82.         else:
  83.             self.unpause()
  84.  
  85.     def event_paused_close(self):
  86.         # This allows the player to still exit while the game is paused,
  87.         # rather than having to unpause first.
  88.         self.event_close()
  89.  
  90.  
  91. class Player(sge.StellarClass):
  92.  
  93.     @property
  94.     def score(self):
  95.         return self.v_score
  96.  
  97.     @score.setter
  98.     def score(self, value):
  99.         if value != self.v_score:
  100.             self.v_score = value
  101.             refresh_hud()
  102.  
  103.     def __init__(self, player=1):
  104.         if player == 1:
  105.             self.joystick = 0
  106.             self.up_key = "w"
  107.             self.down_key = "s"
  108.             x = 32
  109.             glob.player1 = self
  110.             self.hit_direction = 1
  111.         else:
  112.             self.joystick = 1
  113.             self.up_key = "up"
  114.             self.down_key = "down"
  115.             x = sge.game.width - 32
  116.             glob.player2 = self
  117.             self.hit_direction = -1
  118.  
  119.         y = sge.game.height / 2
  120.         super(Player, self).__init__(x, y, 0, sprite="paddle")
  121.  
  122.     def event_create(self):
  123.         self.v_score = 0
  124.         self.trackball_motion = 0
  125.  
  126.     def event_step(self, time_passed):
  127.         # Movement
  128.         key_motion = (sge.get_key_pressed(self.down_key) -
  129.                       sge.get_key_pressed(self.up_key))
  130.         axis_motion = sge.get_joystick_axis(self.joystick, 1)
  131.  
  132.         if (abs(axis_motion) > abs(key_motion) and
  133.                 abs(axis_motion) > abs(self.trackball_motion)):
  134.             self.yvelocity = axis_motion * PADDLE_SPEED
  135.         elif (abs(self.trackball_motion) > abs(key_motion) and
  136.               abs(self.trackball_motion) > abs(axis_motion)):
  137.             self.yvelocity = self.trackball_motion * PADDLE_SPEED
  138.         else:
  139.             self.yvelocity = key_motion * PADDLE_SPEED
  140.  
  141.         self.trackball_motion = 0
  142.  
  143.         # Keep the paddle inside the window
  144.         if self.bbox_top < 0:
  145.             self.bbox_top = 0
  146.         elif self.bbox_bottom > sge.game.height:
  147.             self.bbox_bottom = sge.game.height
  148.  
  149.     def event_joystick_trackball_move(self, joystick, ball, x, y):
  150.         if joystick == self.joystick:
  151.             if abs(y) > abs(self.trackball_motion):
  152.                 self.trackball_motion = y
  153.  
  154.  
  155. class Ball(sge.StellarClass):
  156.  
  157.     def __init__(self):
  158.         x = sge.game.width / 2
  159.         y = sge.game.height / 2
  160.         super(Ball, self).__init__(x, y, 1, sprite="ball")
  161.  
  162.     def event_create(self):
  163.         refresh_hud()
  164.         self.serve()
  165.  
  166.     def event_step(self, time_passed):
  167.         # Scoring
  168.         if self.bbox_right < 0:
  169.             glob.player2.score += 1
  170.             glob.score_sound.play()
  171.             self.serve(-1)
  172.         elif self.bbox_left > sge.game.width:
  173.             glob.player1.score += 1
  174.             glob.score_sound.play()
  175.             self.serve(1)
  176.  
  177.         # Bouncing off of the edges
  178.         if self.bbox_bottom > sge.game.height:
  179.             self.bbox_bottom = sge.game.height
  180.             self.yvelocity = -abs(self.yvelocity)
  181.             glob.bounce_wall_sound.play()
  182.         elif self.bbox_top < 0:
  183.             self.bbox_top = 0
  184.             self.yvelocity = abs(self.yvelocity)
  185.             glob.bounce_wall_sound.play()
  186.  
  187.     def event_collision(self, other):
  188.         if isinstance(other, Player):
  189.             if other.hit_direction == 1:
  190.                 self.bbox_left = other.bbox_right + 1
  191.                 self.xvelocity = min(abs(self.xvelocity) + BALL_ACCELERATION,
  192.                                      BALL_MAX_SPEED)
  193.             else:
  194.                 self.bbox_right = other.bbox_left - 1
  195.                 self.xvelocity = max(-abs(self.xvelocity) - BALL_ACCELERATION,
  196.                                      -BALL_MAX_SPEED)
  197.  
  198.             self.yvelocity += (self.y - other.y) * PADDLE_VERTICAL_FORCE
  199.             glob.bounce_sound.play()
  200.  
  201.     def serve(self, direction=1):
  202.         self.x = self.xstart
  203.         self.y = self.ystart
  204.  
  205.         if (glob.player1.score < POINTS_TO_WIN and
  206.                 glob.player2.score < POINTS_TO_WIN):
  207.             # Next round
  208.             self.xvelocity = BALL_START_SPEED * direction
  209.             self.yvelocity = 0
  210.         else:
  211.             # Game Over!
  212.             self.xvelocity = 0
  213.             self.yvelocity = 0
  214.             glob.hud_sprite.draw_clear()
  215.             x = glob.hud_sprite.width / 2
  216.             p1score = glob.player1.score
  217.             p2score = glob.player2.score
  218.             p1text = "WIN" if p1score > p2score else "LOSE"
  219.             p2text = "WIN" if p2score > p1score else "LOSE"
  220.             glob.hud_sprite.draw_text("hud", p1text, x - TEXT_OFFSET,
  221.                                       TEXT_OFFSET, color="white",
  222.                                       halign=sge.ALIGN_RIGHT,
  223.                                       valign=sge.ALIGN_TOP)
  224.             glob.hud_sprite.draw_text("hud", p2text, x + TEXT_OFFSET,
  225.                                       TEXT_OFFSET, color="white",
  226.                                       halign=sge.ALIGN_LEFT,
  227.                                       valign=sge.ALIGN_TOP)
  228.             glob.game_in_progress = False
  229.  
  230.  
  231. def refresh_hud():
  232.     # This fixes the HUD sprite so that it displays the correct score.
  233.     glob.hud_sprite.draw_clear()
  234.     x = glob.hud_sprite.width / 2
  235.     glob.hud_sprite.draw_text("hud", str(glob.player1.score), x - TEXT_OFFSET,
  236.                               TEXT_OFFSET, color="white",
  237.                               halign=sge.ALIGN_RIGHT, valign=sge.ALIGN_TOP)
  238.     glob.hud_sprite.draw_text("hud", str(glob.player2.score), x + TEXT_OFFSET,
  239.                               TEXT_OFFSET, color="white",
  240.                               halign=sge.ALIGN_LEFT, valign=sge.ALIGN_TOP)
  241.  
  242.  
  243. def main():
  244.     # Create Game object
  245.     Game(640, 480, fps=120)
  246.  
  247.     # Load sprites
  248.     paddle_sprite = sge.Sprite(ID="paddle", width=8, height=48, origin_x=4,
  249.                                origin_y=24)
  250.     paddle_sprite.draw_rectangle(0, 0, paddle_sprite.width,
  251.                                  paddle_sprite.height, fill="white")
  252.     ball_sprite = sge.Sprite(ID="ball", width=8, height=8, origin_x=4,
  253.                              origin_y=4)
  254.     ball_sprite.draw_rectangle(0, 0, ball_sprite.width, ball_sprite.height,
  255.                                fill="white")
  256.     glob.hud_sprite = sge.Sprite(width=320, height=160, origin_x=160,
  257.                                  origin_y=0)
  258.  
  259.     # Load backgrounds
  260.     layers = (sge.BackgroundLayer("ball", sge.game.width / 2, 0, -10000,
  261.                                   xrepeat=False),)
  262.     background = sge.Background (layers, "black")
  263.  
  264.     # Load fonts
  265.     sge.Font('Liberation Mono', ID="hud", size=48)
  266.  
  267.     # Load sounds
  268.     glob.bounce_sound = sge.Sound('bounce.wav')
  269.     glob.bounce_wall_sound = sge.Sound('bounce_wall.wav')
  270.     glob.score_sound = sge.Sound('score.wav')
  271.  
  272.     # Create objects
  273.     Player(1)
  274.     Player(2)
  275.     glob.ball = Ball()
  276.     hud = sge.StellarClass(sge.game.width / 2, 0, -10, sprite=glob.hud_sprite,
  277.                            detects_collisions=False)
  278.     objects = (glob.player1, glob.player2, glob.ball, hud)
  279.  
  280.     # Create rooms
  281.     room1 = sge.Room(objects, background=background)
  282.  
  283.     sge.game.start()
  284.  
  285.  
  286. if __name__ == '__main__':
  287.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement