Advertisement
Guest User

Untitled

a guest
Nov 16th, 2014
200
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 8.79 KB | None | 0 0
  1. try:
  2.     from   pygame.locals import *
  3.     import pygame
  4.     import sys
  5.     import os
  6.  
  7. except ImportError as e:
  8.     print("[Missing//Error]: {}".format(e))
  9.  
  10. print("The following game is a clone of the original PONG.")
  11. print("I programmed it to learn pygame and i'm not responsible of what you do with it.")
  12. print("This game is provided as it is.")
  13. print("Author: {}".format("MasterLight"))
  14. print("Date: {}".format("10/12/2014"))
  15. print("-" * 50)
  16. print("CONTROLS")
  17. print("-" * 50)
  18. print("Player1 [LEFT] Controls : UP Arrow - Moving up\t// DOWN Arrow - Moving down.")
  19. print("PLAYER2 [RIGHT] Controls : mouse.")
  20.  
  21. class Game(object):
  22.  
  23.     def __init__(self, x, y, text_x = 0, text_y = 0):
  24.         self.x = x
  25.         self.y = y
  26.         self.windows_sz = (self.x, self.y) #tuple with the window size
  27.  
  28.         #Text position
  29.         self.text_x = text_x
  30.         self.text_y = text_y
  31.  
  32.         #Score
  33.         self.score_player1 = 0
  34.         self.score_player2 = 0
  35.  
  36.         #Player1 coords
  37.         self.dx_p1  = 5
  38.         self.dy_p1  = 125
  39.  
  40.         #Player2 coords
  41.         self.dx_p2  = 805
  42.         self.dy_p2  = 125
  43.  
  44.         #Ball const
  45.         self.BALL_x        = 400
  46.         self.BALL_y        = 400
  47.         self.BALL_velocity = 2
  48.         self.directionX    = 1
  49.         self.directionY    = 1
  50.  
  51.         #Color selection
  52.         self.colors = {
  53.             "red" : (255, 0, 0),
  54.             "green" : (0, 255, 0),
  55.             "blue" : (0, 0, 255),
  56.             "darkBlue" : (0, 0, 128),
  57.             "white" : (255, 255, 255),
  58.             "black" : (0, 0, 0),
  59.             "pink" : (255, 200, 200)
  60.         }
  61.  
  62.         #Change the cwd to the script current location
  63.         os.chdir(os.getcwd())
  64.  
  65.         #File I/O
  66.         if not os.path.isfile("highscore.txt"):
  67.             print("\nhighscore.txt file dosen't exists\nCreating...")
  68.             open("highscore.txt","w+")
  69.  
  70.         else:
  71.             print("\nFile exists\nSkipping...")
  72.  
  73.         #MENU
  74.         print("\nEnter y for yes or press enter if you don't want that.")
  75.         self.AI        = bool(input("Do you want AI?[y - yes / enter - no]: "))
  76.         self.highSC    = bool(input("Do you want to record highscore/score from the game? [y - yes / enter - no]:"))
  77.  
  78.  
  79.         #Init the field
  80.         self.window    = pygame.display.set_mode(self.windows_sz)
  81.         self.window_sz = self.window.get_size()
  82.         self.clock     = pygame.time.Clock()
  83.         pygame.display.set_caption("Python - PONG")
  84.  
  85.  
  86.     def PLAYERS(self):
  87.         while True:
  88.  
  89.             #Check for closing
  90.             for event in pygame.event.get():
  91.                 if event.type == pygame.QUIT:
  92.                    
  93.                     if self.highSC:
  94.                         self.highscore()
  95.                     pygame.quit()          #Close the window
  96.                     sys.exit("Exiting...") #Exit the infinite loop
  97.  
  98.             #User input
  99.             key = pygame.key.get_pressed()
  100.             if key[pygame.K_UP]:
  101.                 self.dy_p1 -= 7
  102.             if key[pygame.K_DOWN]:
  103.                 self.dy_p1 += 7
  104.  
  105.             #AI Part
  106.             #This is very rudimentary but it does the job with some problems tho
  107.             #BUG: the player1 rect will exit out of the screen for a portion if the rect is moving up
  108.             if self.AI:
  109.                 self.dy_p1 = self.BALL_y - 90
  110.                 self.dy_p2 = self.BALL_y - 90
  111.  
  112.             #Fill the screen with the specified color as a tuple
  113.             self.window.fill(pygame.Color("black"))
  114.  
  115.             #Draw a line at the middle of the field
  116.             pygame.draw.line(self.window, pygame.Color("white"),
  117.                              (self.window_sz[0] - 400, self.window_sz[-1]),
  118.                              (self.window_sz[0] - 400, self.window_sz[-1] - 700))
  119.  
  120.             #Display the current fps on the screen
  121.             self.window.blit(self.font("FPS: {currentFPS}".format(currentFPS = str(self.clock.get_fps()).split(".")[0]),
  122.                                             "Arial", 16, 1, pygame.Color("white"), pygame.Color("black")),
  123.                              (self.text_x, self.text_y))
  124.  
  125.             #Display the score of the player 1
  126.             self.window.blit(self.font(str(self.score_player1), "Arial", 22, 1, pygame.Color("white"),
  127.                                        pygame.Color("black")),
  128.                                        (self.text_x + 200, self.text_y + 10))
  129.  
  130.             #Display the score of the player 2
  131.             self.window.blit(self.font(str(self.score_player2), "Arial", 22, 1, pygame.Color("white"),
  132.                                        pygame.Color("black")),
  133.                                        (self.text_x + 500, self.text_y + 10))
  134.             #Limit FPS to 60
  135.             self.clock.tick(160)
  136.  
  137.             #Draw a rectangle
  138.             player1 = pygame.draw.rect(self.window, self.colors.get("red", "error"), (self.dx_p1, self.dy_p1, 1, 100), 8)
  139.  
  140.             #Draw the ball
  141.             ball    = pygame.draw.circle(self.window, self.colors.get("red", "error"), (self.BALL_x, self.BALL_y), 10, 10)
  142.  
  143.             #Draw the second player
  144.             player2 = pygame.draw.rect(self.window, pygame.Color("white"), (self.dx_p2, self.dy_p2, 1, 100), 8)
  145.  
  146.             rect_p1   = pygame.Rect(player1)
  147.             rect_p2   = pygame.Rect(player2)
  148.             rect_ball = pygame.Rect(ball)
  149.  
  150.             if rect_ball.colliderect(rect_p2):
  151.                 self.directionY *= -1
  152.                 self.directionX *= -1
  153.  
  154.             if rect_ball.colliderect(rect_p1):
  155.                 self.directionX *= -1
  156.                 self.directionY *= -1
  157.  
  158.             self.BALL_x += self.BALL_velocity * self.directionX
  159.             self.BALL_y += self.BALL_velocity * self.directionY
  160.  
  161.             #Limit the movement to the screen limit
  162.             if self.dy_p1 > (self.window_sz[1] - 100):
  163.                 self.dy_p1 = self.dy_p1 - 7
  164.  
  165.             if self.dy_p1 <= 0:
  166.                 self.dy_p1 = 0
  167.  
  168.             #Ball bound detection
  169.             #Only on the y direction
  170.             if self.BALL_y > 600 or self.BALL_y <= 0:
  171.                 self.directionY *= -1
  172.  
  173.             if self.BALL_x > self.window_sz[0]:
  174.                 self.score_player1 += 1
  175.  
  176.                 #Remove the old one
  177.                 del ball
  178.                 del rect_ball
  179.  
  180.                 #Re-spawn the ball
  181.                 self.BALL_x = 400
  182.                 self.BALL_y = 400
  183.                 self.BALL_x += self.BALL_velocity * self.directionX
  184.                 self.BALL_y += self.BALL_velocity * self.directionY
  185.  
  186.             elif self.BALL_x < 0:
  187.                 self.score_player2 += 1
  188.  
  189.                 #Remove the old one
  190.                 del ball
  191.                 del rect_ball
  192.  
  193.                 #Re-spawn the ball
  194.                 self.BALL_x = 400
  195.                 self.BALL_y = 400
  196.                 self.BALL_x += self.BALL_velocity * self.directionX
  197.                 self.BALL_y += self.BALL_velocity * self.directionY
  198.  
  199.             #Player 2 check for bounding him to the window bounds
  200.             mouse_pos  = pygame.mouse.get_pos()
  201.             self.dy_p2 = mouse_pos[1]
  202.  
  203.             #Player2 - Mouse bound detection
  204.             if  self.dx_p2 + 10 > self.window_sz[0]:
  205.                 self.dx_p2 = self.window_sz[0] - 5
  206.  
  207.             if  self.dy_p2  > self.window_sz[1] - 100:
  208.                 self.dy_p2 = self.window_sz[1] - 100
  209.  
  210.             pygame.display.update()
  211.  
  212.     def font(self, text = "", font_name = "Arial", size = 24, AA = 1, F_color = (), B_color = ()):
  213.         """
  214.        Return a font object witch can be used with blit to output text on the screen
  215.        """
  216.  
  217.         #INIT pygame's font module
  218.         pygame.font.init()
  219.  
  220.         font = pygame.font.SysFont(font_name, size)
  221.         font = font.render(text, AA, F_color, B_color)
  222.         return font
  223.  
  224.     def highscore(self):
  225.         """
  226.        Search for an highscore.txt file to read/write the scores in it
  227.        """
  228.  
  229.         try:
  230.             #Write the highscores to the hightscore.txt file
  231.             with open("highscore.txt", "a") as highFILE:
  232.                 #Get and write the highest score
  233.                 #Also format the things really nicely :)
  234.                 highFILE.write("\n")
  235.                 highFILE.write("\nHighscore: {}\n".format(max(self.score_player1, self.score_player2)))
  236.                 highFILE.write("\n")
  237.                 highFILE.write("-" * 90)
  238.                 highFILE.write("\n")
  239.                 highFILE.write("\nPLAYER1 Score: {}\n".format(self.score_player1))
  240.                 highFILE.write("PLAYER2 Score: {}".format(self.score_player2))
  241.  
  242.         except IOError as e  :   print("Error -> {}".format(e))
  243.         except Exception as e: print("Error -> {}".format(e))
  244.  
  245. if __name__ == "__main__":
  246.     g = Game(800, 600, 10, 5)
  247.     g.PLAYERS()
  248.     g.highscore()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement