11.3. 乒乓球



完整代码
 1# Pong game for mPython
 2# MIT license,Copyright (c) 2019 labplus@Tangliufeng
 3
 4from mpython import *
 5import music
 6
 7
 8class Pong():
 9    def __init__(self):
10
11        self.running = True
12        self.start = False
13        self.ball_rad = 5
14        self.bats_position = 0
15        self.bats_width = 15
16        self.bats_height = 4
17
18        self.ball_x = self.bats_width // 2
19        self.ball_y = 64 - (self.ball_rad + self.bats_height + 1)
20        self.inc_x, self.inc_y = 1, 1
21        self.score = 0
22
23    def collision(self):
24
25        if self.ball_x >= 128 - self.ball_rad or self.ball_x < self.ball_rad:
26            self.inc_x = -self.inc_x
27        if self.ball_y >= 64 - (self.ball_rad + self.bats_height) or self.ball_y <= self.ball_rad:
28            self.inc_y = -self.inc_y
29
30    def update(self):
31        self.ball_x = self.ball_x + self.inc_x
32        self.ball_y = self.ball_y + self.inc_y
33        self.bats_position = min(max(self.bats_position, 0), 128 - self.bats_width)
34
35    def is_hit(self):
36        # print('ball:', self.ball_x, self.ball_y, 'bats:', self.bats_position)
37        if self.ball_y >= 64 - (self.ball_rad + self.bats_height):
38            if self.ball_x >= self.bats_position + self.bats_width + self.ball_rad or self.ball_x <= self.bats_position - self.ball_rad:
39
40                return False
41            self.score += 1
42            return True
43
44    def run(self):
45
46        while self.running:
47            if button_a.value() == 0 and button_b.value() == 1:
48                self.bats_position -= 2
49                self.start = True
50            if button_a.value() == 1 and button_b.value() == 0:
51                self.bats_position += 2
52                self.start = True
53
54            if self.start:
55                self.update()
56                self.collision()
57
58                if self.is_hit() == False:
59                    self.running = False
60                    continue
61
62            oled.fill(0)
63            oled.fill_circle(self.ball_x, self.ball_y, self.ball_rad, 1)
64            oled.fill_rect(self.bats_position, 64 - self.bats_height, self.bats_width, self.bats_height, 1)
65            oled.show()
66
67        oled.text('Game over!', 20, 20)
68        oled.text('Score %d' % self.score, 20, 32)
69        oled.show()
70
71
72if __name__ == '__main__':
73    pong = Pong()
74    pong.run()