forked from trucmai204/PyPong-Game
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPong.py
More file actions
78 lines (63 loc) · 2.78 KB
/
Pong.py
File metadata and controls
78 lines (63 loc) · 2.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import pygame
from classes.paddle import Paddle
from classes.ball import Ball
from classes.score import Score
class Game:
def __init__(self):
pygame.init()
self.screen_width = 800
self.screen_height = 600
self.screen = pygame.display.set_mode((self.screen_width, self.screen_height))
pygame.display.set_caption("Pong")
self.clock = pygame.time.Clock()
# Tạo paddles, bóng và điểm số
self.paddle_left = Paddle(50, self.screen_height // 2 - 50)
self.paddle_right = Paddle(self.screen_width - 60, self.screen_height // 2 - 50)
self.ball = Ball(self.screen_width, self.screen_height)
self.score = Score(self.screen_width)
def start(self):
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
keys = pygame.key.get_pressed()
if keys[pygame.K_w]:
self.paddle_left.move_up()
if keys[pygame.K_s]:
self.paddle_left.move_down()
if keys[pygame.K_UP]:
self.paddle_right.move_up()
if keys[pygame.K_DOWN]:
self.paddle_right.move_down()
self.paddle_left.keep_within_bounds(self.screen_height)
self.paddle_right.keep_within_bounds(self.screen_height)
self.ball.move()
self.ball.bounce(self.screen_height)
# Kiểm tra va chạm với paddle
if self.ball.x - self.ball.radius < self.paddle_left.x + self.paddle_left.width and \
self.paddle_left.y < self.ball.y < self.paddle_left.y + self.paddle_left.height:
self.ball.dx *= -1
if self.ball.x + self.ball.radius > self.paddle_right.x and \
self.paddle_right.y < self.ball.y < self.paddle_right.y + self.paddle_right.height:
self.ball.dx *= -1
# Kiểm tra nếu bóng vượt qua màn hình
if self.ball.x - self.ball.radius < 0:
self.ball.reset(self.screen_width, self.screen_height)
self.score.right_point()
if self.ball.x + self.ball.radius > self.screen_width:
self.ball.reset(self.screen_width, self.screen_height)
self.score.left_point()
# Cập nhật màn hình
self.screen.fill((255, 192, 203))
self.paddle_left.draw(self.screen)
self.paddle_right.draw(self.screen)
self.ball.draw(self.screen)
self.score.update(self.screen)
pygame.display.flip()
self.clock.tick(60)
pygame.quit()
# Khởi tạo và bắt đầu trò chơi
if __name__ == "__main__":
game = Game()
game.start()