Advertisement
sriyanto

Chapter 1 Complete

Dec 28th, 2023 (edited)
563
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.61 KB | None | 0 0
  1. import tkinter as tk
  2.  
  3.  
  4. class GameObject(object):
  5.     def __init__(self, canvas, item):
  6.         self.canvas = canvas
  7.         self.item = item
  8.  
  9.     def get_position(self):
  10.         return self.canvas.coords(self.item)
  11.  
  12.     def move(self, x, y):
  13.         self.canvas.move(self.item, x, y)
  14.  
  15.     def delete(self):
  16.         self.canvas.delete(self.item)
  17.  
  18.  
  19. class Ball(GameObject):
  20.     def __init__(self, canvas, x, y):
  21.         self.radius = 10
  22.         self.direction = [1, -1]
  23.         self.speed = 10
  24.         item = canvas.create_oval(x-self.radius, y-self.radius,
  25.                                   x+self.radius, y+self.radius,
  26.                                   fill='white')
  27.         super(Ball, self).__init__(canvas, item)
  28.  
  29.     def update(self):
  30.         coords = self.get_position()
  31.         width = self.canvas.winfo_width()
  32.         if coords[0] <= 0 or coords[2] >= width:
  33.             self.direction[0] *= -1
  34.         if coords[1] <= 0:
  35.             self.direction[1] *= -1
  36.         x = self.direction[0] * self.speed
  37.         y = self.direction[1] * self.speed
  38.         self.move(x, y)
  39.  
  40.     def collide(self, game_objects):
  41.         coords = self.get_position()
  42.         x = (coords[0] + coords[2]) * 0.5
  43.         if len(game_objects) > 1:
  44.             self.direction[1] *= -1
  45.         elif len(game_objects) == 1:
  46.             game_object = game_objects[0]
  47.             coords = game_object.get_position()
  48.             if x > coords[2]:
  49.                 self.direction[0] = 1
  50.             elif x < coords[0]:
  51.                 self.direction[0] = -1
  52.             else:
  53.                 self.direction[1] *= -1
  54.  
  55.         for game_object in game_objects:
  56.             if isinstance(game_object, Brick):
  57.                 game_object.hit()
  58.  
  59.  
  60. class Paddle(GameObject):
  61.     def __init__(self, canvas, x, y):
  62.         self.width = 80
  63.         self.height = 10
  64.         self.ball = None
  65.         item = canvas.create_rectangle(x - self.width / 2,
  66.                                        y - self.height / 2,
  67.                                        x + self.width / 2,
  68.                                        y + self.height / 2,
  69.                                        fill='blue')
  70.         super(Paddle, self).__init__(canvas, item)
  71.  
  72.     def set_ball(self, ball):
  73.         self.ball = ball
  74.  
  75.     def move(self, offset):
  76.         coords = self.get_position()
  77.         width = self.canvas.winfo_width()
  78.         if coords[0] + offset >= 0 and coords[2] + offset <= width:
  79.             super(Paddle, self).move(offset, 0)
  80.             if self.ball is not None:
  81.                 self.ball.move(offset, 0)
  82.  
  83.  
  84. class Brick(GameObject):
  85.     COLORS = {1: '#999999', 2: '#555555', 3: '#222222'}
  86.  
  87.     def __init__(self, canvas, x, y, hits):
  88.         self.width = 75
  89.         self.height = 20
  90.         self.hits = hits
  91.         color = Brick.COLORS[hits]
  92.         item = canvas.create_rectangle(x - self.width / 2,
  93.                                        y - self.height / 2,
  94.                                        x + self.width / 2,
  95.                                        y + self.height / 2,
  96.                                        fill=color, tags='brick')
  97.         super(Brick, self).__init__(canvas, item)
  98.  
  99.     def hit(self):
  100.         self.hits -= 1
  101.         if self.hits == 0:
  102.             self.delete()
  103.         else:
  104.             self.canvas.itemconfig(self.item,
  105.                                    fill=Brick.COLORS[self.hits])
  106.  
  107.  
  108. class Game(tk.Frame):
  109.     def __init__(self, master):
  110.         super(Game, self).__init__(master)
  111.         self.lives = 3
  112.         self.width = 610
  113.         self.height = 400
  114.         self.canvas = tk.Canvas(self, bg='#aaaaff',
  115.                                 width=self.width,
  116.                                 height=self.height,)
  117.         self.canvas.pack()
  118.         self.pack()
  119.  
  120.         self.items = {}
  121.         self.ball = None
  122.         self.paddle = Paddle(self.canvas, self.width/2, 326)
  123.         self.items[self.paddle.item] = self.paddle
  124.         for x in range(5, self.width - 5, 75):
  125.             self.add_brick(x + 37.5, 50, 2)
  126.             self.add_brick(x + 37.5, 70, 1)
  127.             self.add_brick(x + 37.5, 90, 1)
  128.  
  129.         self.hud = None
  130.         self.setup_game()
  131.         self.canvas.focus_set()
  132.         self.canvas.bind('<Left>',
  133.                          lambda _: self.paddle.move(-10))
  134.         self.canvas.bind('<Right>',
  135.                          lambda _: self.paddle.move(10))
  136.  
  137.     def setup_game(self):
  138.            self.add_ball()
  139.            self.update_lives_text()
  140.            self.text = self.draw_text(300, 200,
  141.                                       'Press Space to start')
  142.            self.canvas.bind('<space>', lambda _: self.start_game())
  143.  
  144.     def add_ball(self):
  145.         if self.ball is not None:
  146.             self.ball.delete()
  147.         paddle_coords = self.paddle.get_position()
  148.         x = (paddle_coords[0] + paddle_coords[2]) * 0.5
  149.         self.ball = Ball(self.canvas, x, 310)
  150.         self.paddle.set_ball(self.ball)
  151.  
  152.     def add_brick(self, x, y, hits):
  153.         brick = Brick(self.canvas, x, y, hits)
  154.         self.items[brick.item] = brick
  155.  
  156.     def draw_text(self, x, y, text, size='40'):
  157.         font = ('Helvetica', size)
  158.         return self.canvas.create_text(x, y, text=text,
  159.                                        font=font)
  160.  
  161.     def update_lives_text(self):
  162.         text = 'Lives: %s' % self.lives
  163.         if self.hud is None:
  164.             self.hud = self.draw_text(50, 20, text, 15)
  165.         else:
  166.             self.canvas.itemconfig(self.hud, text=text)
  167.  
  168.     def start_game(self):
  169.         self.canvas.unbind('<space>')
  170.         self.canvas.delete(self.text)
  171.         self.paddle.ball = None
  172.         self.game_loop()
  173.  
  174.     def game_loop(self):
  175.         self.check_collisions()
  176.         num_bricks = len(self.canvas.find_withtag('brick'))
  177.         if num_bricks == 0:
  178.             self.ball.speed = None
  179.             self.draw_text(300, 200, 'You win!')
  180.         elif self.ball.get_position()[3] >= self.height:
  181.             self.ball.speed = None
  182.             self.lives -= 1
  183.             if self.lives < 0:
  184.                 self.draw_text(300, 200, 'Game Over')
  185.             else:
  186.                 self.after(1000, self.setup_game)
  187.         else:
  188.             self.ball.update()
  189.             self.after(50, self.game_loop)
  190.  
  191.     def check_collisions(self):
  192.         ball_coords = self.ball.get_position()
  193.         items = self.canvas.find_overlapping(*ball_coords)
  194.         objects = [self.items[x] for x in items if x in self.items]
  195.         self.ball.collide(objects)
  196.  
  197.  
  198.  
  199. if __name__ == '__main__':
  200.     root = tk.Tk()
  201.     root.title('Hello, Pong!')
  202.     game = Game(root)
  203.     game.mainloop()
  204.    
  205.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement