コード例 #1
0
def main():

    w = GWindow()

    # r1 = Robot(183, 70, color='magenta')
    # ball1 = r1.give_me_a_ball(100)
    # w.add(ball1, 200, 100)
    # r1.self_intro()
    # r1.bmi()
    # r1.say_hi()
    #
    # r2 = Robot(160, 45, color='navy')
    # r2.self_intro()
    # r2.bmi()
    # r2.say_hi()
    #
    # Robot.say_hi()

    robot2_1 = Robot2(183, 70, color2='megenta', count2=10)
    robot2_1.start_count()
    robot2_1.say_hi()
    robot2_1.bmi()

    robot3 = Robot3(170, 65, 'tomato', color3='red', count3=100)
    robot3.self_intro()
    robot3.bmi()
    ball3 = robot3.give_me_a_ball(100)
    rect3 = robot3.give_me_a_rect(100)
    w.add(rect3)
    w.add(ball3, 150, 200)
コード例 #2
0
def main():
    window = GWindow(500, 500)
    r1 = Robot(188, 80, color='black')
    r1.give_me_a_ball(SIZE)
    print(__name__)
    # r1.speak()
    # r1.self_intro()
    # print(r1.bmi())
    # window.add(r1.ball, window.width/2 - SIZE/2, window.height/2 - SIZE/2)
    # print(r1.ball.width)
    # r1.say_hi1()
    # Robot.say_hi2()
    #
    #
    # right_r1_arm = r1.RobotArm("right", 100)
    # print(right_r1_arm.property, "arm length = ", right_r1_arm.length)

    r2 = Robot2(200, 300, color2="brown", count2=5)
    r2.start_count()
    r2.say_hi1()
    r2.say_hi2()
    r2.self_intro()

    r3 = Robot3(300, 400, "pink", color3="black", count3=100)
    r3.bmi()
    rect = r3.give_me_a_rect(20)
    r3.give_me_a_ball(SIZE)
    window.add(r1.ball, window.width / 2 - SIZE / 2,
               window.height / 2 - SIZE / 2)
    window.add(rect, window.width / 2 - SIZE / 2, window.height / 2 - SIZE / 2)
コード例 #3
0
def main():
    # window = GWindow(width = 1000, height = 800, title = 'MyFacew')
    # face = GOval(250, 350, x = 350 , y = 200)
    # face.filled = True
    # face.fill_color = 'lightpink'
    # window.add(face)
    # l_eye = GOval(50, 50, x = 400, y = 250)
    # l_eye.filled = True
    # l_eye.fill_color = 'black'
    # window.add(l_eye)
    # r_eye = GOval(50, 50, x = 500, y = 250)
    # r_eye.filled = True
    # r_eye.fill_color = 'black'
    # window.add(r_eye)
    # mouth = GRect(150, 50, x = 400, y = 400)
    # mouth.filled = True
    # mouth.fill_color = 'red'
    # window.add(mouth)
    # window.draw_oval(50, 50, 500, 200)
    #
    # label = GLabel('Hello World!', 100, 200)
    # label.color = 'magenta'
    # window.add(label, 100, 200)
    window = GWindow()
    # triangle = GPolygon()
    # triangle.add_vertex((100, 200))
    # triangle.add_vertex((200, 200))
    # triangle.add_vertex((150, 100))
    # triangle.filled = True
    # triangle.fill_color = 'blue'
    # window.add(triangle)
    arc = GArc(200, 80, 0, 180, window.width / 2, window.height / 2)
    arc.filled = True
    arc.fill_color = 'red'
    window.add(arc)
コード例 #4
0
def main():
    """
    This program makes a simple sunset animation.
    """
    window = GWindow(width=WIDTH, height=HEIGHT, title='Sunset')
    sun = make_sun(window)
    horizon = make_horizon(window)
    window.add(sun)
    window.add(horizon)
    move_sun(window, sun)
コード例 #5
0
class NoGraphics:
    def __init__(self,
                 window_width=WINDOW_WIDTH,
                 window_height=WINDOW_HEIGHT,
                 boundary_x=BOUNDARY_X,
                 boundary_y=BOUNDARY_Y):
        # 介面碼定義
        self.__menu_code = 0  # 介面碼 0:wait 1:main 2:game 9:none
        # 狀態碼定義
        self.__status_code = 0  # 狀態碼 0:wait 1:start 9:reade

        # 邊界定義
        self.__boundary_x = boundary_x
        self.__boundary_y = boundary_y

        # 建視窗
        self.window = GWindow(width=window_width,
                              height=window_height,
                              title='NONO',
                              color="green")

        self.__obj = None

    def grid_line(self, size=50, dx=0, dy=0):
        """
        功能:輔助功能,方格線
        size = 單位方格大小
        dx = x軸位移量
        dy = y軸位移量
        """
        line_color = 'lightgray'

        # 水平輔助線
        for r in range(self.window.width // size + 1):
            p1_x = r * size + dx
            p1_y = 0
            p2_x = r * size + dx
            p2_y = self.window.height

            line_row = GLine(p1_x, p1_y, p2_x, p2_y)
            line_row.color = line_color

            self.window.add(line_row)

        # 垂直輔助線
        for c in range(self.window.height // size + 1):
            p1_x = 0
            p1_y = c * size + dy
            p2_x = self.window.width
            p2_y = c * size + dy

            line_column = GLine(p1_x, p1_y, p2_x, p2_y)
            line_column.color = line_color

            self.window.add(line_column)
コード例 #6
0
def main():
    print(f'__name__== {__name__}')
    window = GWindow(600, 400)

    r1 = SuperRobot(200, 100, super_c='salmon', counter=5)
    r1_ball = r1.give_me_a_ball(100)
    window.add(r1_ball, 200, 200)
    r1.self_intro()
    r1.bmi()
    SuperRobot.say_tater()
    r1.self_count()
コード例 #7
0
def main():
    """
    Center a magenta rect on the canvas
    where the width and height are SIZE
    """
    rect = GRect(SIZE, SIZE)
    rect.filled = True
    rect.color = 'magenta'
    rect.fill_color = 'magenta'
    window = GWindow()
    rect_x = (window.width - rect.width) / 2
    rect_y = (window.height - rect.height) / 2
    window.add(rect, rect_x, rect_y)
コード例 #8
0
class ZoneGraphics:
    def __init__(self,
                 window_width=WINDOW_WIDTH,
                 window_height=WINDOW_HEIGHT,
                 zone_width=ZONE_WIDTH,
                 zone_height=ZONE_HEIGHT,
                 ball_radius=BALL_RADIUS):
        # Create window
        self.window = GWindow(WINDOW_WIDTH, WINDOW_HEIGHT, title='ZONE_GAME')
        # Create zone
        self.zone = GRect(zone_width,
                          zone_height,
                          x=(self.window.width - zone_width) / 2,
                          y=(self.window.height - zone_height) / 2)
        self.zone.color = 'blue'
        self.zone.filled = True
        self.zone.fill_color = "blue"
        self.window.add(self.zone)
        # Create ball and initialize velocity/position
        self.ball = GOval(BALL_RADIUS * 2, BALL_RADIUS * 2)
        self.ball.filled = True
        self.set_ball_position()
        self.ball.fill_color = 'black'
        self.window.add(self.ball)
        #speed
        self.dx_right = True
        self.dy_down = True
        #bounce

        # Initialize mouse listeners

    def set_ball_position(self):
        while True:
            rand_x = random.randint(0, self.window.width - self.ball.width)
            rand_y = random.randint(0, self.window.height - self.ball.height)
            if not (self.zone.x < rand_x < self.zone.x + ZONE_WIDTH
                    and self.zone.y < rand_y < self.zone.y + ZONE_HEIGHT):
                break
        self.ball.x = rand_x
        self.ball.y = rand_y

    def set_ball_velocity(self):
        self.dx = random.randint(MIN_SPEED, MAX_SPEED)
        if random.random() > 0.5:
            self.dx *= -1
        self.dy = random.randint(MIN_SPEED, MAX_SPEED)
        if random.random() > 0.5:
            self.dy *= -1
コード例 #9
0
def main():

    window = GWindow()
    rect = GRect(SIZE,
                 SIZE,
                 x=(window.width - SIZE) / 2,
                 y=(window.height - SIZE) / 2)
    rect.filled = True
    rect.fill_color = 'hotpink'
    window.add(rect)
    vx = 5
    while True:
        rect.move(vx, 0)
        if rect.x <= 0 or (rect.x + SIZE) >= window.width:
            vx = -vx
        pause(DELAY)
コード例 #10
0
class Log_in_page:
    def __init__(self, bar_width=BAR_WIDTH, bar_height=BAR_HEIGHT, win_width=WIN_WIDTH, win_height=WIN_HEIGHT,
                 play_button_width=PLAY_BUTTON_WIDTH, play_button_height=PLAY_BUTTON_HEIGHT,
                 fb_button_width=WIN_WIDTH * 0.6,
                 fb_button_height=FB_BUTTON_HEIGHT):

        self.window = GWindow(win_width, win_height, title='Welcome')
        self.load_bar = GRect(bar_width, bar_height)
        self.load_label = GLabel('0%')
        self.solid_bar = GRect(0, bar_height)
        self.play_button = GRect(play_button_width, play_button_height)
        self.play_label = GLabel('Start New Game')
        self.fb_button = GRect(fb_button_width, fb_button_height)
        self.fb_label = GLabel('continue with facebook')

    def loading(self):

        self.download_label = GLabel('downloading')
        self.solid_bar.color = 'black'
        self.solid_bar.filled = True
        self.solid_bar.fill_color = 'black'

        self.window.add(self.load_bar, (self.window.width - self.load_bar.width) / 2,
                        self.window.height * 0.7)

        while self.solid_bar.width < self.load_bar.width:
            self.window.remove(self.solid_bar)
            self.window.remove(self.load_label)
            self.solid_bar.width = self.solid_bar.width + 10
            if (bar_ratio := (self.solid_bar.width / self.load_bar.width) * 100) < 100:
                self.load_label.text = f'{int(bar_ratio)} %'
            else:
                self.load_label.text = f'100%'

            self.window.add(self.solid_bar, self.load_bar.x, self.load_bar.y)
            self.window.add(self.load_label, self.load_bar.x + self.load_bar.width - self.load_label.width,
                            self.load_bar.y + self.load_bar.height + self.load_label.height + 5)

            if self.solid_bar.width < self.load_bar.width * 0.33:
                self.download_label.text = 'downloading....'
            elif self.load_bar.width * 0.25 <= self.solid_bar.width < self.load_bar.width * 0.66:
                self.download_label.text = 'downloading........'
            elif self.load_bar.width * 0.5 <= self.solid_bar.width < self.load_bar.width * 0.99:
                self.download_label.text = 'downloading............'

            self.window.add(self.download_label, self.load_bar.x,
                            self.load_bar.y + self.load_bar.height + self.load_label.height + 5)

            pause(100)
            self.window.remove(self.download_label)

        self.download_label.text = 'completed!'
        self.window.add(self.download_label, self.load_bar.x,
                        self.load_bar.y + self.load_bar.height + self.load_label.height + 5)
コード例 #11
0
def main():
    window = GWindow()
    rect = set_up_r()
    window.add(rect, (window.width - rect.width) // 2,
               (window.height - rect.height) // 2)
    vx = 5
    while True:
        rect.move(vx, 0)
        if rect.x <= 0 or rect.x + rect.width >= window.width:
            vx = -vx
            if vx > 0:
                rect.color = 'purple'
                rect.filled = True
                rect.fill_color = rect.color
            else:
                rect.color = 'green'
                rect.filled = True
                rect.fill_color = rect.color
        pause(DELAY)
コード例 #12
0
def main():
    window = GWindow(width=600, height=600, title='MyDrawing')

    dish = GOval(300, 300, x=150, y=100)
    window.add(dish)

    arc = myGArc(100, 100, 0, 90, x=100, y=100)
    window.add(arc)
    # print(arc.start_point)
    # print(arc.end_point)

    #arc.rotate()
    # arc2 = GArc(50, 50, 0, 180, x=0 ,y=0)
    # window.add(arc2)
    # print(arc2.start_point)
    # print(arc2.end_point)
    #
    # arc3 = GArc(50, 50, 0, 270, x=0, y=0)
    # window.add(arc3)
    # print(arc3.start_point)
    # print(arc3.end_point)
    #
    # arc4 = GArc(50, 100, 90, 180, x=50, y=50)
    # window.add(arc4)
    # print(arc4.start_point)
    # print(arc4.end_point)
    #
    # dish2 = GRect(width=100, height=100, x=50, y=50)
    # # dish2._transformed = True
    # # gobject_rotate(dish2, 30)
    # # dish2.transformed = True
    # dish2.rotate(90)
    # window.add(dish2)

    word = GLabel('Hello Word!', 50, 100)
    window.add(word)
コード例 #13
0
ファイル: illusion.py プロジェクト: TristenSeth/campy
# Radius of each constructed arc. For the illusion to look interesting, this
# should be no more than half the minimum of the rectangle's height and width.
ARC_RADIUS = 50

if __name__ == '__main__':
    window = GWindow(title='Illusion')
    center = GPoint(window.width / 2, window.height / 2)
    corners = (
        GPoint(center.x - RECTANGLE_WIDTH / 2,
               center.y - RECTANGLE_HEIGHT / 2),  # Upper-left
        GPoint(center.x - RECTANGLE_WIDTH / 2,
               center.y + RECTANGLE_HEIGHT / 2),  # Lower-left
        GPoint(center.x + RECTANGLE_WIDTH / 2,
               center.y + RECTANGLE_HEIGHT / 2),  # Lower-right
        GPoint(center.x + RECTANGLE_WIDTH / 2,
               center.y - RECTANGLE_HEIGHT / 2),  # Upper-right
    )

    for corner, start in zip(corners, range(0, 360, 90)):
        arc = GArc(ARC_RADIUS * 2,
                   ARC_RADIUS * 2,
                   start=start,
                   sweep=270,
                   x=corner.x - ARC_RADIUS,
                   y=corner.y - ARC_RADIUS)
        arc.filled = True
        window.add(arc)
        # Alternatively, don't set the arc's location at initialization and instead set it here.
        # window.add(arc, corner.x - ARC_RADIUS, corner.y - ARC_RADIUS)
コード例 #14
0
class BreakoutGraphics:
    def __init__(self,
                 ball_radius=BALL_RADIUS,
                 paddle_width=PADDLE_WIDTH,
                 paddle_height=PADDLE_HEIGHT,
                 paddle_offset=PADDLE_OFFSET,
                 brick_rows=BRICK_ROWS,
                 brick_cols=BRICK_COLS,
                 brick_width=BRICK_WIDTH,
                 brick_height=BRICK_HEIGHT,
                 brick_offset=BRICK_OFFSET,
                 brick_spacing=BRICK_SPACING,
                 title='Breakout'):

        self.pw = paddle_width  # Class variable to store paddle width.
        self.ph = paddle_height  # Class variable to store paddle height.
        self.pos = paddle_offset  # Class variable to store paddle offset.
        self.br = ball_radius  # Class variable to store ball radius.
        self.brk_row = brick_rows  # Class variable to store the number of brick rows.
        self.brk_col = brick_cols  # Class variable to store the number of brick columns.
        self.click = 1  # Class variable as a switch to control game status, where 1 equals to game termination.
        self.brick_count = 0  # Class variable to store the number of bricks being eliminated.
        self.score = 0  # Class variable to store the score of the game.

        # Create a graphical window, with some extra space.
        window_width = brick_cols * (brick_width +
                                     brick_spacing) - brick_spacing
        window_height = brick_offset + 3 * (brick_rows *
                                            (brick_height + brick_spacing) -
                                            brick_spacing)
        self.window = GWindow(width=window_width,
                              height=window_height,
                              title=title)

        self.wh = window_height  # Class variable to store window height.
        self.ww = window_width  # Class variable to store window width.

        # Create a label to show the score.
        self.label_s = GLabel('Scores: ' + str(self.score),
                              x=2,
                              y=window_height - 2)
        self.label_s.font = '-10'
        self.window.add(self.label_s)

        # Create a paddle.
        self.paddle = GRect(width=paddle_width,
                            height=paddle_height,
                            x=(window_width - paddle_width) / 2,
                            y=window_height - paddle_offset - paddle_height)
        self.paddle.filled = True
        self.paddle.fill_color = 'black'
        self.paddle.color = 'black'
        self.window.add(self.paddle)

        # Center a filled ball in the graphical window.
        self.ball = GOval(ball_radius * 2, ball_radius * 2)
        self.ball.filled = True
        self.ball.fill_color = 'black'
        self.ball.color = 'black'
        self.set_ball(
        )  # Method to set ball place at initial, details shown as below.
        self.window.add(self.ball)

        # Method to set initial velocity of the ball, details shown as below.
        self.set_ball_velocity()

        # Initialize mouse listeners.
        onmousemoved(self.paddle_location
                     )  # Method to move paddle while moving the mouse.
        onmouseclicked(
            self.game_start
        )  # Method to control game status while clicking the mouse.

        # Draw bricks with different colors, which is determined ny the number of rows.
        for i in range(brick_cols):
            for j in range(brick_rows):
                self.brick = GRect(brick_width,
                                   brick_height,
                                   x=i * (brick_width + brick_spacing),
                                   y=j * (brick_height + brick_spacing) +
                                   BRICK_OFFSET)
                self.brick.filled = True
                if j % 10 == 0 or j % 10 == 1:
                    self.brick.fill_color = 'Red'
                    self.brick.color = 'Red'
                elif j % 10 == 2 or j % 10 == 3:
                    self.brick.fill_color = 'Orange'
                    self.brick.color = 'Orange'
                elif j % 10 == 4 or j % 10 == 5:
                    self.brick.fill_color = 'Yellow'
                    self.brick.color = 'Yellow'
                elif j % 10 == 6 or j % 10 == 7:
                    self.brick.fill_color = 'Green'
                    self.brick.color = 'Green'
                else:
                    self.brick.fill_color = 'Blue'
                    self.brick.color = 'Blue'
                self.window.add(self.brick)

    def set_ball(self):
        """
        A method to set ball at initial place.
        """
        self.ball.x = (self.ww - self.br) / 2
        self.ball.y = (self.wh - self.br) / 2

    def set_ball_velocity(self):
        """
        A method to set the initial velocity of the ball speed.
        """
        self.__dx = random.randint(1, MAX_X_SPEED)
        self.__dy = INITIAL_Y_SPEED
        if random.random() > 0.5:
            self.__dx = -self.__dx

    def game_start(self, event):
        """
        :param event: Detect when the user presses the button on their mouse and then minus variable click by 1.
        :return: Continuing the game when the number of click is less than 1.
        """
        self.click -= 1

    def paddle_location(self, event):
        """
        :param event: Detect when the user moves the mouse.
        :return:Move paddle when the mouse is moved and make sure that the paddle completely stays in the window.
        """
        if event.x - (self.pw / 2) < 0:
            self.paddle.x = 0
        elif event.x + (self.pw / 2) >= self.ww:
            self.paddle.x = self.ww - self.pw
        else:
            self.paddle.x = event.x - self.pw / 2
        self.paddle.y = self.wh - self.pos

    def check_for_wall(self):
        """
        A method that changes the direction of the ball when it hits the wall.
        """
        if self.ball.x <= 0 or self.ball.x + self.ball.width >= self.window.width:
            self.__dx = -self.__dx
        if self.ball.y <= 0:
            self.__dy = -self.__dy

    def check_for_collision(self):
        """
        A method that changes the direction of the ball when it hits the paddle.
        """
        ul_obj = self.window.get_object_at(self.ball.x, self.ball.y)
        ur_obj = self.window.get_object_at(self.ball.x + self.ball.width,
                                           self.ball.y)
        ll_obj = self.window.get_object_at(self.ball.x,
                                           self.ball.y + self.ball.width)
        lr_obj = self.window.get_object_at(self.ball.x + self.ball.width,
                                           self.ball.y + self.ball.width)
        if ul_obj is not None and ul_obj is not self.paddle and ul_obj is not self.label_s:
            self.window.remove(ul_obj)
            self.brick_count += 1
            self.score += 1
            self.label_s.text = 'Scores: ' + str(self.score)
            self.__dy *= -1.1
        elif ur_obj is not None and ur_obj is not self.paddle and ul_obj is not self.label_s:
            self.window.remove(ur_obj)
            self.brick_count += 1
            self.score += 1
            self.label_s.text = 'Scores: ' + str(self.score)
            self.__dy *= -1.1
        elif ll_obj is self.paddle:
            self.__dy *= -1
        elif lr_obj is self.paddle:
            self.__dy *= -1

    def get_dx(self):
        """
        Getter function for x velocity.
        """
        return self.__dx

    def get_dy(self):
        """
        Getter function for y velocity.
        """
        return self.__dy
コード例 #15
0
ファイル: my_drawing.py プロジェクト: elsa7718/sc101-2020-Nov
def main():
    """
    TODO:
    This figure uses campy module to demonstrate personality.
    A lot of faiths hold by people, just like the shape of circles or triangles,
    while eventually others can only see the polygon.
    """
    window=GWindow(600,600)

    # color of background
    rect=GRect(800,800)
    rect.filled=True
    rect.fill_color='lightgrey'
    window.add(rect)

    # polygon, circle ,rect and triangle with different colors
    polygon1=GPolygon()
    polygon1.add_vertex((550, 590))
    polygon1.add_vertex((570, 360))
    polygon1.add_vertex((100, 60))
    polygon1.filled=True
    polygon1.fill_color='greenyellow'
    window.add(polygon1)

    rect1=GRect(335,335,x=135,y=150)
    rect1.filled=True
    rect1.fill_color='sage'
    rect2=GRect(370,370,x=120,y=135)
    rect2.filled=True
    rect2.fill_color='magenta'
    rect3=GRect(400,400,x=105,y=120)
    rect3.filled=True
    rect3.fill_color='purple'
    rect4=GRect(440,440,x=85,y=100)
    rect4.filled=True
    rect4.fill_color='peachpuff'
    window.add(rect4)
    window.add(rect3)
    window.add(rect2)
    window.add(rect1)

    circle5=GOval(265,265,x=170,y=185)
    circle5.filled=True
    circle5.fill_color='lightsage'
    circle6=GOval(285,285,x=160,y=175)
    circle6.filled=True
    circle6.fill_color='tan'
    circle7=GOval(305,305,x=150,y=165)
    circle7.filled=True
    circle7.fill_color='midnightblue'
    circle8=GOval(325,325,x=140,y=155)
    circle8.filled=True
    circle8.fill_color='powderblue'
    window.add(circle8)
    window.add(circle7)
    window.add(circle6)
    window.add(circle5)

    triangle1=GPolygon()
    triangle1.add_vertex((300,230))
    triangle1.add_vertex((225,340))
    triangle1.add_vertex((375,340))
    triangle2=GPolygon()
    triangle2.add_vertex((300,215))
    triangle2.add_vertex((210,350))
    triangle2.add_vertex((390,350))
    triangle1.filled=True
    triangle1.fill_color='pink'
    triangle2.filled=True
    triangle2.fill_color='lightgrey'
    triangle3=GPolygon()
    triangle3.add_vertex((300,200))
    triangle3.add_vertex((195,360))
    triangle3.add_vertex((405,360))
    triangle4=GPolygon()
    triangle4.add_vertex((300,185))
    triangle4.add_vertex((180,370))
    triangle4.add_vertex((420,370))
    triangle3.filled=True
    triangle3.fill_color='linen'
    triangle4.filled=True
    triangle4.fill_color='yellow'
    window.add(triangle4)
    window.add(triangle3)
    window.add(triangle2)
    window.add(triangle1)

    circle1=GOval(20,20,x=290,y=290)
    circle1.filled=True
    circle1.fill_color='aquamarine'
    circle2=GOval(40,40,x=280,y=280)
    circle2.filled=True
    circle2.fill_color='aqua'
    circle3=GOval(60,60,x=270,y=270)
    circle3.filled=True
    circle3.fill_color='darkblue'
    circle4=GOval(80,80,x=260,y=260)
    circle4.filled=True
    circle4.fill_color='blueviolet'
    window.add(circle4)
    window.add(circle3)
    window.add(circle2)
    window.add(circle1)

    polygon=GPolygon()
    polygon.add_vertex((100, 60))
    polygon.add_vertex((50,100))
    polygon.add_vertex((40,180))
    polygon.add_vertex((20,400))
    polygon.add_vertex((30,550))
    polygon.add_vertex((180,580))
    polygon.add_vertex((400, 550))
    polygon.add_vertex((550, 590))
    polygon.filled=True
    polygon.fill_color='salmon'
    window.add(polygon)

    # logo
    sc101=GLabel('SC101-2020.Nov')
    sc101.font='Courier-15-bold-italic'
    window.add(sc101,0,window.height-sc101.height+20)
コード例 #16
0
class BreakoutGraphics:
    def __init__(self,
                 ball_radius=BALL_RADIUS,
                 paddle_width=PADDLE_WIDTH,
                 paddle_height=PADDLE_HEIGHT,
                 paddle_offset=PADDLE_OFFSET,
                 brick_rows=BRICK_ROWS,
                 brick_cols=BRICK_COLS,
                 brick_width=BRICK_WIDTH,
                 brick_height=BRICK_HEIGHT,
                 brick_offset=BRICK_OFFSET,
                 brick_spacing=BRICK_SPACING,
                 title='Breakout'):
        # Create a graphical window, with some extra space.
        window_width = brick_cols * (brick_width +
                                     brick_spacing) - brick_spacing
        window_height = brick_offset + 3 * (brick_rows *
                                            (brick_height + brick_spacing) -
                                            brick_spacing)
        self.game_start = False
        self.window = GWindow(width=window_width,
                              height=window_height,
                              title=title)
        # Create a paddle.
        self.paddle = GRect(width=paddle_width, height=paddle_height)
        self.paddle.filled = True
        self.paddle_offset = paddle_offset
        self.window.add(self.paddle, (window_width - paddle_width) / 2,
                        window_height - paddle_offset)
        # Center a filled ball in the graphical window.
        self.ball = GOval(ball_radius * 2, ball_radius * 2)
        self.ball.filled = True
        self.window.add(self.ball, window_width / 2 - ball_radius,
                        window_height / 2 - ball_radius)
        # Default initial velocity for the ball.
        self.__dy = 0
        self.__dx = 0
        # Calculate times of removing brick
        self.count = 0
        # Draw bricks.
        self.brick_rows = brick_rows
        self.brick_cols = brick_cols
        for i in range(self.brick_rows):
            for j in range(self.brick_cols):
                self.brick = GRect(brick_width, brick_height)
                self.brick.filled = True
                if j == 0 or j == 1:
                    color = 'red'
                elif j == 2 or j == 3:
                    color = 'gold'
                elif j == 4 or j == 5:
                    color = 'yellow'
                elif j == 6 or j == 7:
                    color = 'green'
                else:
                    color = 'blue'
                self.brick.fill_color = color
                self.brick.color = color
                self.window.add(self.brick, (brick_spacing + brick_width) * i,
                                (brick_spacing + brick_height) * j +
                                brick_offset)
        # Initialize our mouse listeners.
        onmousemoved(self.paddle_move)
        onmouseclicked(self.initialize_velocity)

    def set_dx(self):
        self.__dx = -self.__dx

    def set_dy(self):
        self.__dy = -self.__dy

    def reset_ball(self):
        self.window.add(self.ball, self.window.width / 2 - self.ball.width,
                        self.window.height / 2 - self.ball.width)
        self.__dy = 0
        self.__dx = 0
        self.game_start = False

    def initialize_velocity(self, mouse):
        if not self.game_start:
            self.set_ball_velocity()
            self.game_start = True

    def set_ball_velocity(self):
        self.__dx = random.randint(1, MAX_X_SPEED)
        self.__dy = INITIAL_Y_SPEED
        if random.random() > 0.5:
            self.__dx = -self.__dx

    def ball_out_of_window(self):
        is_ball_out_of_window = self.ball.y >= self.window.height
        return is_ball_out_of_window

    def paddle_move(self, mouse):
        if 0 <= mouse.x <= self.window.width - self.paddle.width:
            self.window.add(self.paddle, mouse.x,
                            self.window.height - self.paddle_offset)

    def get_dx(self):
        return self.__dx

    def get_dy(self):
        return self.__dy

    def count(self):
        self.count += 1
        return self.count

    def check_ball(self):
        # Name 4 point of ball
        maybe_1 = self.window.get_object_at(self.ball.x, self.ball.y)
        maybe_2 = self.window.get_object_at(self.ball.x + self.ball.width,
                                            self.ball.y)
        maybe_3 = self.window.get_object_at(self.ball.x,
                                            self.ball.y + self.ball.width)
        maybe_4 = self.window.get_object_at(self.ball.x + self.ball.width,
                                            self.ball.y + self.ball.width)
        # Check if one of point hit paddle or brick
        if maybe_1 is not None:
            # Check if first point hit brick because only bottom of ball will hid paddle
            if maybe_1 is not self.paddle:
                self.set_dy()
                self.window.remove(maybe_1)
                self.count += 1
        else:
            if maybe_2 is not None:
                # Check if second point hit brick because only bottom of ball will hid paddle
                if maybe_2 is not self.paddle:
                    self.set_dy()
                    self.window.remove(maybe_2)
                    self.count += 1
            else:
                if maybe_3 is not None:
                    if maybe_3 is self.paddle:
                        self.set_dy()
                    else:
                        self.set_dy()
                        self.window.remove(maybe_3)
                        self.count += 1
                else:
                    if maybe_4 is not None:
                        if maybe_4 is self.paddle:
                            self.set_dy()
                        else:
                            self.set_dy()
                            self.window.remove(maybe_4)
                            self.count += 1

    def all_clear(self):
        is_all_clear = self.count == self.brick_cols * self.brick_rows
        return is_all_clear

    def remove_ball(self):
        self.window.remove(self.ball)

    def game_over(self):
        game_over = GLabel('Game Over')
        game_over.font = 'Georgia-50-Bold'
        self.window.add(game_over, (self.window.width - game_over.width) / 2,
                        (self.window.height - game_over.height) / 2)
コード例 #17
0
class BreakoutGraphics:
    def __init__(self,
                 ball_radius=BALL_RADIUS,
                 paddle_width=PADDLE_WIDTH,
                 paddle_height=PADDLE_HEIGHT,
                 paddle_offset=PADDLE_OFFSET,
                 brick_rows=BRICK_ROWS,
                 brick_cols=BRICK_COLS,
                 brick_width=BRICK_WIDTH,
                 brick_height=BRICK_HEIGHT,
                 brick_offset=BRICK_OFFSET,
                 brick_spacing=BRICK_SPACING,
                 title='Breakout'):
        # only three lives
        self.num_lives = NUM_LIVES
        # win img
        self.img = GImage('WIN!!.png')

        # Create a graphical window, with some extra space.
        window_width = brick_cols * (brick_width +
                                     brick_spacing) - brick_spacing
        window_height = brick_offset + 3 * (brick_rows *
                                            (brick_height + brick_spacing) -
                                            brick_spacing)
        self.window = GWindow(width=window_width,
                              height=window_height,
                              title=title)

        # Start button
        self.button_back = GRect(250, 50)
        self.button_back.filled = True
        self.button_back.fill_color = 'darkgrey'
        self.window.add(self.button_back,
                        x=(self.window.width - self.button_back.width) // 2,
                        y=352.5)

        self.button = GRect(250, 50)
        self.button.filled = True
        self.button.fill_color = 'grey'
        self.window.add(self.button,
                        x=(self.window.width - self.button.width) // 2,
                        y=350)

        self.button_word = GLabel('CLICK TO START')
        self.button_word.font = '-30'
        self.window.add(self.button_word,
                        x=(self.window.width - self.button_word.width) // 2,
                        y=350 + self.button_word.height + 10)

        # Create a paddle.
        self.paddle = GRect(paddle_width,
                            paddle_height,
                            x=(window_width - paddle_width) // 2,
                            y=window_height - paddle_offset)
        self.paddle.filled = True
        self.window.add(self.paddle)

        # Center a filled ball in the graphical window.
        self.ball = GOval(ball_radius * 2,
                          ball_radius * 2,
                          x=window_width // 2 - ball_radius,
                          y=window_height // 2 - ball_radius)
        self.ball.filled = True
        self.window.add(self.ball)

        # Default initial velocity for the ball.
        self.__dx = self.set_ball_x_velocity()
        self.__dy = INITIAL_Y_SPEED

        # Initialize our mouse listeners.
        onmouseclicked(self.start)
        onmousemoved(self.control_paddle)

        # the switch of the game
        self.start = False

        # Score board.
        self.score = 0
        self.score_label = GLabel('Score: ' + str(self.score))
        self.score_label.font = '-22'
        self.window.add(self.score_label, x=0, y=self.score_label.height + 5)

        # how many lives
        self.life1 = GLabel('❤️')
        self.life1.font = '-20'
        self.window.add(self.life1, self.window.width - self.life1.width,
                        self.life1.height + 7)

        self.life2 = GLabel('❤️')
        self.life2.font = '-20'
        self.window.add(self.life2, self.window.width - self.life2.width * 2,
                        self.life2.height + 7.35)

        self.life3 = GLabel('❤️')
        self.life3.font = '-20'
        self.window.add(self.life3, self.window.width - self.life3.width * 3,
                        self.life3.height + 7.35)

        # Draw bricks.
        x = 0
        # to change row
        space = 0
        self.change = 0
        self.color = 'red'
        # 5 colors
        for i in range(brick_rows // 2):
            # each color 2 rows
            for j in range(2):
                # x bricks
                for k in range(brick_cols):
                    self.brick = GRect(brick_width,
                                       brick_height,
                                       x=0 + x,
                                       y=brick_offset + space)
                    x += (brick_width + brick_spacing)
                    self.brick.filled = True
                    self.brick.fill_color = self.color
                    self.brick.color = self.color
                    self.window.add(self.brick)
                x = 0
                space += (brick_height + brick_spacing)
            self.change_color()

    def change_color(self):
        """
        a method for making different color of the bricks
        :return: color
        """
        self.change += 1
        if self.change == 1:
            self.color = 'orange'
        elif self.change == 2:
            self.color = 'yellow'
        elif self.change == 3:
            self.color = 'green'
        elif self.change == 4:
            self.color = 'blue'

    def control_paddle(self, m):
        """
        This method controls the paddle by moving your mouse inside the window.
        The midpoint of the paddle follows the mouse
        :param m: mouse event
        """
        if self.paddle.width // 2 <= m.x <= self.window.width - self.paddle.width // 2:
            self.paddle.x = m.x - self.paddle.width // 2

    def start(self, m):
        """
        The switch of this game
        """
        self.window.remove(self.button)
        self.window.remove(self.button_back)
        self.window.remove(self.button_word)
        if self.num_lives > 0:
            self.start = True

    def set_ball_x_velocity(self):
        """
        This method gives random dx for the ball whenever the ball starts moving.
        """
        # ball start w/ different dx speed
        self.__dx = random.randint(1, MAX_X_SPEED)
        # ball start w/ different direction
        if random.random() > 0.5:
            self.__dx = -self.__dx
        return self.__dx

    # getter: ball dx
    def get_ball_x_velocity(self):
        return self.__dx

    # getter: ball dy
    def get_ball_y_velocity(self):
        return self.__dy

    def touch_thing(self):
        """
        This method checks whether the ball has touched something.
        No, keep moving
        Yes, return the thing to next place to check what is the thing
        """
        # object sensor: left up, right up, left down, right down
        obj1 = self.window.get_object_at(self.ball.x, self.ball.y)
        obj2 = self.window.get_object_at(self.ball.x + self.ball.width,
                                         self.ball.y)
        obj3 = self.window.get_object_at(self.ball.x,
                                         self.ball.y + self.ball.width)
        obj4 = self.window.get_object_at(self.ball.x + self.ball.width,
                                         self.ball.y + self.ball.width)

        # check whether ball touch object
        if obj1 is None:
            if obj2 is None:
                if obj3 is None:
                    if obj4 is None:
                        pass
                    else:
                        return obj4
                else:
                    return obj3
            else:
                return obj2
        else:
            return obj1

    def check_hit_wall(self):
        """
        This method checks whether the ball hits the top, left or right wall and changes
        its direction dx = -dx
        """
        if self.ball.x <= 0 or self.ball.x >= self.window.width - self.ball.width:
            self.__dx = -self.__dx
        if self.ball.y <= 0:
            self.__dy = -self.__dy

    def check_what_object(self):
        """
        This method checks what object did the ball hit
        """
        if self.touch_thing() is self.paddle:
            # avoid the situation: when the ball touches the edge of paddle, it will stuck in the paddle, up and down
            if self.__dy > 0:
                self.__dy = -self.__dy
            else:
                pass
        elif self.touch_thing() is self.score_label:
            pass
        elif self.touch_thing() is self.img:
            pass
        elif self.touch_thing() is not None:
            self.window.remove(self.touch_thing())
            self.score += 1
            self.score_label.text = 'Score: ' + str(self.score)
            self.__dy = -self.__dy
        elif self.touch_thing() is self.life1 or self.life2 or self.life3:
            pass

    # def bonus_ball(self):
    #     while self.ball.y < self.window.height//2:
    #         self.ball.fill_color = 'red'

    def win(self):
        """
        This method shows an image and label if the user wins the game by clearing
        all the bricks
        """
        if self.score == 100:
            win = GLabel('WIN!!')
            win.font = 'Times-50'
            self.window.add(win, 50, 235)
            self.window.add(self.img, 10, 25)
            self.window.remove(self.ball)

    def dead(self):
        """
        This method will check whether the ball falls below the window and will show a
        label 'Gameover' when there's no lives left.
        """
        if self.ball.y >= self.window.height:
            self.window.remove(self.ball)
            self.num_lives -= 1
            if self.num_lives > 0:
                self.reset_ball()
                # lives left
                if self.num_lives == 2:
                    self.window.remove(self.life3)
                elif self.num_lives == 1:
                    self.window.remove(self.life2)
            else:
                # last life
                if self.num_lives == 0:
                    self.window.remove(self.life1)
                lose = GLabel('GAMEOVER!!!')
                lose.font = 'Trattatello-60-italic'
                self.window.add(lose,
                                x=(self.window.width - lose.width) // 2,
                                y=(self.window.height + lose.height) // 2)

    def reset_ball(self):
        """
        This method resets the ball to the middle of the window and assign a new speed
        in order to reset the game.
        """
        self.ball = GOval(self.ball.width,
                          self.ball.width,
                          x=(self.window.width - self.ball.width) // 2,
                          y=(self.window.height - self.ball.width) // 2)
        self.ball.filled = True
        self.window.add(self.ball)
        self.start = False
        self.set_ball_x_velocity()
コード例 #18
0
class BreakoutGraphics:
    def __init__(self,
                 ball_radius=BALL_RADIUS,
                 paddle_width=PADDLE_WIDTH,
                 paddle_height=PADDLE_HEIGHT,
                 paddle_offset=PADDLE_OFFSET,
                 brick_rows=BRICK_ROWS,
                 brick_cols=BRICK_COLS,
                 brick_width=BRICK_WIDTH,
                 brick_height=BRICK_HEIGHT,
                 brick_offset=BRICK_OFFSET,
                 brick_spacing=BRICK_SPACING,
                 title='Breakout'):

        self.__ball_radius = ball_radius
        self.__paddle_width = paddle_width
        self.__paddle_height = paddle_height
        self.__paddle_offset = paddle_offset
        self.__brick_rows = brick_rows
        self.__brick_cols = brick_cols
        self.__brick_width = brick_width
        self.__brick_height = brick_height
        self.__brick_offset = brick_offset
        self.__brick_spacing = brick_spacing

        # Create a graphical window, with some extra space.
        window_width = brick_cols * (brick_width +
                                     brick_spacing) - brick_spacing
        window_height = brick_offset + 3 * (brick_rows *
                                            (brick_height + brick_spacing) -
                                            brick_spacing)
        self.window = GWindow(width=window_width,
                              height=window_height,
                              title=title)

        # Create a paddle.
        self.paddle = GRect(self.__paddle_width,
                            self.__paddle_height,
                            x=(self.window.width - paddle_width) / 2,
                            y=(self.window.height - paddle_height -
                               self.__paddle_offset))
        self.paddle.filled = True
        self.window.add(self.paddle)

        # Center a filled ball in the graphical window.
        self.ball = GOval(self.__ball_radius * 2,
                          self.__ball_radius * 2,
                          x=self.window.width / 2 - self.__ball_radius,
                          y=self.window.height / 2 - self.__ball_radius)
        self.ball.filled = True
        self.window.add(self.ball)

        # Default initial velocity for the ball.
        self._dy = INITIAL_Y_SPEED
        self._dx = random.randint(1, MAX_X_SPEED)
        if (random.random() > 0.5):
            self._dx = -self._dx

        # Initialize our mouse listeners.
        onmousemoved(self.paddle_move)
        onmouseclicked(self.ball_start)
        self.start = False

        # Draw bricks
        for i in range(self.__brick_rows):
            for j in range(self.__brick_cols):
                self.bricks = GRect(
                    self.__brick_width,
                    self.__brick_height,
                    x=j * (self.__brick_width + self.__brick_spacing),
                    y=self.__brick_offset + i *
                    (self.__brick_height + self.__brick_spacing))
                self.bricks.filled = True
                if i % 10 == 0 or i % 10 == 1:
                    self.bricks.fill_color = 'red'
                elif i % 10 == 2 or i % 10 == 3:
                    self.bricks.fill_color = 'orange'
                elif i % 10 == 4 or i % 10 == 5:
                    self.bricks.fill_color = 'yellow'
                elif i % 10 == 6 or i % 10 == 7:
                    self.bricks.fill_color = 'green'
                elif i % 10 == 8 or i % 10 == 9:
                    self.bricks.fill_color = 'blue'
                self.window.add(self.bricks)

    def paddle_move(self, paddle_position):
        if self.paddle.width <= paddle_position.x <= self.window.width - self.paddle.width:
            self.paddle.x = paddle_position.x - self.paddle.width / 2
            self.paddle.y = self.window.height - self.paddle.height - self.__paddle_offset
        elif paddle_position.x <= self.paddle.width:
            self.paddle.x = 0
            self.paddle.y = self.window.height - self.paddle.height - self.__paddle_offset
        elif paddle_position.x >= self.window.width - self.paddle.width:
            self.paddle.x = self.window.width - self.paddle.width
            self.paddle.y = self.window.height - self.paddle.height - self.__paddle_offset

    def ball_start(self, ball_position):
        ball_start_position = self.window.get_object_at(
            self.window.width / 2, self.window.height / 2)
        if ball_start_position is self.ball:
            self.start = True

    #Getter

    def get_dy(self):
        return self._dy

    def get_dx(self):
        return self._dx

    def get_paddle_height(self):
        return self.__paddle_height

    def get_paddle_width(self):
        return self.__paddle_width

    def get_ball_radius(self):
        return self.__ball_radius

    def get_brick_cols(self):
        return self.__brick_cols

    def get_brick_rows(self):
        return self.__brick_rows

    def get_brick_spacing(self):
        return self.__brick_spacing

    def get_brick_offset(self):
        return self.__brick_offset

    def get_brick_height(self):
        return self.__brick_height

    def get_brick_width(self):
        return self.__paddle_width
コード例 #19
0
def main():
    window = GWindow(width=800, height=500, title='Tater paws')
    paw1 = GOval(20, 20, x=200, y=50)
    window.add(paw1)
    paw2 = GOval(20, 20, x=230, y=50)
    window.add(paw2)
    paw3 = GOval(20, 20, x=260, y=50)
    window.add(paw3)
    dogf = GRect(80, 40, x=200, y=100)
    window.add(dogf)
    face = GOval(150, 150, x=165, y=40)
    window.add(face)
    paw1.filled = True
    paw1.fill_color = 'indigo'
    paw2.filled = True
    paw2.fill_color = 'khaki'
    paw3.filled = True
    paw3.fill_color = 'beige'
    dogf.filled = True
    dogf.fill_color = 'olive'
    label = GLabel('Hello world!')
    label.font = '-10'
    window.add(label, 200, 100)
コード例 #20
0
class BreakoutGraphics:

    def __init__(self, ball_radius = BALL_RADIUS, paddle_width = PADDLE_WIDTH,
                 paddle_height = PADDLE_HEIGHT, paddle_offset = PADDLE_OFFSET,
                 brick_rows = BRICK_ROWS, brick_cols = BRICK_COLS,
                 brick_width = BRICK_WIDTH, brick_height = BRICK_HEIGHT,
                 brick_offset = BRICK_OFFSET, brick_spacing = BRICK_SPACING,
                 title='Breakout'):

        # Create a graphical window, with some extra space
        window_width = brick_cols * (brick_width + brick_spacing) - brick_spacing
        window_height = brick_offset + 3 * (brick_rows * (brick_height + brick_spacing) - brick_spacing)
        self.window = GWindow(width=window_width, height=window_height, title=title)

        # Create a paddle
        self.paddle_touch = 0  # (0:untouch paddle; 1: touch paddle)

        # self.paddle = GRect(paddle_width, paddle_height)
        self.paddle = GRect(paddle_width, paddle_height)  # Test width "430"
        self.paddle.filled = True
        self.window.add(self.paddle, x=(window_width-paddle_width)/2, y=window_height-paddle_offset)

        # Center a filled ball in the graphical window
        self.ball_radius = ball_radius
        self.remove_succ = 0  # (0: untouch bricks; 1: touch bricks)
        self.ball = GOval(ball_radius*2, ball_radius*2)
        self.ball.filled = True
        self.window.add(self.ball, x=(window_width-ball_radius)/2, y=(window_height-ball_radius)/2)

        # Default initial velocity for the ball
        self.__dy = INITIAL_Y_SPEED
        self.__dx = random.randint(1, MAX_X_SPEED+1)
        if random.random() > 0.5:
            self.__dx = -self.__dx

        # Initialize our mouse listeners
        self.switch = 0  # This variable controls if the game start or not. (1:start, 0: unstart)
        onmouseclicked(self.click_m)
        onmousemoved(self.move_m)

        # Draw bricks
        self.sum_bricks = brick_rows * brick_cols
        self.bricks_remove = 0  # record how many bricks were removed
        brick_spacing = (window_width - (brick_width*brick_rows))/(brick_rows-1)
        position_height = brick_offset
        for i in range(brick_cols):
            position_width = 0
            for j in range(brick_rows):
                bricks = GRect(brick_width, brick_height)
                bricks.filled = True
                self.window.add(bricks, x=position_width, y=position_height)
                position_width += (brick_spacing + brick_width)
            position_height += (brick_spacing + brick_height)

        # The following variables are used to control user's life or die
        self.dead = 0  # (0: still life; 1: die)

    def click_m(self, mouse):
        """
         This method process when the mouse click.
         :param mouse: shows where the place of mouse
         :return: NA
        """
        if self.switch == 0:
            self.switch = 1
        else:
            pass

    def move_m(self,mouse):
        """
        This method will track where the mouse, and the paddle will follow the mouse
        :param mouse: shows where the place of the mouse
        :return: NA
        """
        if mouse.x >= self.paddle.width/2 and mouse.x <= self.window.width-(self.paddle.width/2):
            self.paddle.x = mouse.x - self.paddle.width/2

    def getter_dx(self):
        """
        The method will give the class user the variable, self.__dx.
        :return: if the game is processing, return the speed of x
        :return: if the game is stop, the speed of x is 0.
        """
        if self.switch == 1:
            return self.__dx
        return 0

    def getter_dy(self):
        """
        The method will give the class user the variable, self.__dy.
        :return: if the game is processing, return the speed of y
        :return: if the game is stop, the speed of y is 0.
        """
        if self.switch == 1:
            return self.__dy
        return 0

    def ball_tracker_bricks(self):
        """
        This method is charge of the following situation.
        1. When the ball touch the bricks.
        2. When the ball remove all the bricks.
        :return: if the situation is true, removing the ball.
        """
        ball_tracker_x = [self.ball.x, self.ball.x+2*self.ball_radius]
        ball_tracker_y = [self.ball.y, self.ball.y+2*self.ball_radius]

        for x in ball_tracker_x:
            for y in ball_tracker_y:
                ball_may = self.window.get_object_at(x=x, y=y)
                if ball_may is not self.paddle:
                    if ball_may is not None:
                        self.remove_succ = 1

                        # When the ball remove the bricks, adding one to the recorder
                        # The the brick remove recoder == the number of all bricks → stop the game
                        self.bricks_remove += 1
                        print(str(self.bricks_remove))
                        if self.bricks_remove == self.sum_bricks:
                            self.window.remove(self.ball)
                            # reset the ball on the middle of the window
                            self.window.add(self.ball, x=(self.window.width - self.ball.width) / 2,
                                            y=(self.window.height - self.ball.height) / 2)
                            print('YOU WIN in breakoutgraphics.py')

                        return self.window.remove(ball_may)

    def ball_tracker_paddle(self):
        """
        This method is charge of the following situation.
        1. When the ball touch paddle.
        2. When the ball below the bottom of the window.
        :return: NA
        """
        ball_tracker_x = [self.ball.x, self.ball.x+2*self.ball_radius]
        ball_tracker_y = [self.ball.y, self.ball.y+2*self.ball_radius]

        # When the ball touch the paddle.
        for x in ball_tracker_x:
            for y in ball_tracker_y:
                paddle_may = self.window.get_object_at(x=x, y=y)
                if paddle_may is self.paddle:
                    self.paddle_touch = 1

                    """
                    這行是時為了解決反彈的時候球黏在板子上,研判原因應該是板子快速的滑入,導致球的偵測點卡在板子上下。
                    我強制球碰到板子後會先跳到板子以上,才開始走反彈的code。
                    請問有什麼其他方法可以解決球的偵測點卡在板子上的問題??因為我強制讓球跳到板子以上,看起來會微微奇怪。
                    """
                    self.ball.y = self.paddle.y-self.ball.height
                    return

        # Checking if the ball below the bottom of the window
        if self.ball.y > self.window.height:
            self.dead = 1
            self.switch = 0  # restart the mouse click function
            self.window.remove(self.ball)

            # reset the ball on the middle of the window
            self.window.add(self.ball, x=(self.window.width - self.ball.width) / 2,
                            y=(self.window.height - self.ball.height) / 2)
コード例 #21
0
def main():
    """
    TODO:
    """
    window = GWindow(width=1200, height=600)
    body = GRect(200, 300, x=200, y=150)
    head = GOval(200, 200, x=200, y=50)
    eye = GOval(170, 120, x=250, y=130)
    left_foot = GRect(80, 100, x=200, y=450)
    right_foot = GRect(80, 100, x=320, y=450)
    back = GPolygon()
    back.add_vertex((200, 200))
    back.add_vertex((130, 220))
    back.add_vertex((130, 400))
    back.add_vertex((200, 400))
    handle_1 = GRect(40, 100, x=500, y=250)
    handle_2 = GRect(80, 40, x=420, y=280)
    knife = GPolygon()
    knife.add_vertex((540, 280))
    knife.add_vertex((570, 260))
    knife.add_vertex((590, 275))
    knife.add_vertex((610, 265))
    knife.add_vertex((640, 315))
    knife.add_vertex((540, 315))

    head.filled = True
    body.filled = True
    eye.filled = True
    back.filled = True
    handle_1.filled = True
    left_foot.filled = True
    right_foot.filled = True
    handle_2.filled = True
    knife.filled = True

    head.fill_color = 'red'
    body.fill_color = 'red'
    eye.fill_color = 'skyblue'
    left_foot.fill_color = 'red'
    right_foot.fill_color = 'red'
    back.fill_color = 'red'
    handle_1.fill_color = 'black'
    handle_2.fill_color = 'black'
    knife.fill_color = 'grey'

    head.color = 'red'
    body.color = 'red'
    left_foot.color = 'red'
    right_foot.color = 'red'

    window.add(body)
    window.add(head)
    window.add(eye)
    window.add(left_foot)
    window.add(right_foot)
    window.add(back)
    window.add(handle_1)
    window.add(handle_2)
    window.add(knife)

    body2 = GRect(200, 300, x=750, y=150)
    head2 = GOval(200, 200, x=750, y=50)
    eye2 = GOval(170, 120, x=730, y=130)
    left_foot2 = GRect(80, 100, x=750, y=450)
    right_foot2 = GRect(80, 100, x=870, y=450)
    back2 = GPolygon()
    back2.add_vertex((950, 200))
    back2.add_vertex((1020, 220))
    back2.add_vertex((1020, 400))
    back2.add_vertex((950, 400))

    knife2 = GPolygon()
    knife2.add_vertex((700, 200))
    knife2.add_vertex((680, 180))
    knife2.add_vertex((650, 200))
    knife2.add_vertex((650, 400))
    knife2.add_vertex((700, 400))

    head2.filled = True
    body2.filled = True
    eye2.filled = True
    back2.filled = True
    left_foot2.filled = True
    right_foot2.filled = True

    knife2.filled = True

    head2.fill_color = 'purple'
    body2.fill_color = 'purple'
    eye2.fill_color = 'skyblue'
    left_foot2.fill_color = 'purple'
    right_foot2.fill_color = 'purple'
    back2.fill_color = 'purple'
    knife2.fill_color = 'brown'

    head2.color = 'purple'
    body2.color = 'purple'
    left_foot2.color = 'purple'
    right_foot2.color = 'purple'
    knife2.color = 'brown'

    window.add(body2)
    window.add(head2)
    window.add(eye2)
    window.add(left_foot2)
    window.add(right_foot2)
    window.add(back2)

    label = GLabel('Among Us', x=450, y=500)
    label.font = 'Courier-50-italic'
    window.add(label)

    window.add(knife2)
コード例 #22
0
class Graphics:
	def __init__(self, width=500, height=500):
		"""
		width : the window's width
		height : the window's height
		"""
		# Setting variables
		self.brick_width = (width + BRICK_SPACE) // COLUMNS - BRICK_SPACE
		self.brick_height = int((height * BRICK_HEIGHT_FRACTION + BRICK_SPACE) / ROWS - BRICK_SPACE)
		self.brick_offset = int(height * BRICK_OFFSET_FRACTION)
		self.paddle_width = width // 4
		self.paddle_height = self.brick_height//2
		self.paddle_offset = height // 8
		self.ball_size = min(self.brick_width, self.brick_height)
		self.gift_speed = width // 200
		self.gift_size = self.ball_size

		# Create a graphical window.
		self.window = GWindow(width=width, height=height, title="Breakout")

		# Create a paddle.

		self.paddle = GRect(self.paddle_width, self.paddle_height)
		self.paddle.x = (self.window.width - self.paddle_width) // 2
		self.paddle.y = self.window.height - self.paddle_offset
		color_set(self.paddle, "blue")

		# Draw balls.
		self.ball_list = [GOval(0, 0)] * MAX_BALL_AMOUNT
		self.ball_set()
		self.lives = MAX_LIFE
		self.ball_lives = [0] * MAX_BALL_AMOUNT
		self.ball_amount = 1
		self.fake_ball_x = (self.window.width - self.ball_size) // 2
		self.fake_ball_y = self.paddle.y - self.ball_size

		# Default initial velocity for the ball.
		self.vx_list = [0] * MAX_BALL_AMOUNT
		self.vy_list = [0] * MAX_BALL_AMOUNT
		self.speed_set()
		self.slow_fraction = 1

		# Draw bricks.
		self.brick_list = [GRect(0, 0)] * (ROWS * COLUMNS)
		self.brick_score_list = [0] * (ROWS * COLUMNS)
		self.brick_lives = [1] * (ROWS * COLUMNS)
		self.brick_gift = [0] * (ROWS * COLUMNS)

		# Initial gift boxes
		self.gift_vy = [0] * (ROWS * COLUMNS)
		self.gift_switch = [0] * (ROWS * COLUMNS)
		self.gift_list = [GRect(0, 0)] * (ROWS * COLUMNS)
		self.example_gift = [GRect(0, 0)] * len(GIFT_COLOR)
		self.gift_explanation = [GLabel(0, 0)] * len(GIFT_COLOR)
		self.brick_set()
		self.gift_set()

		# Graphics label
		self.intro_text = GLabel("Breakout")
		self.intro_click_text = GLabel("Click to Start")
		self.loading_text = GLabel("Loading")
		self.progress_bar = GLabel("                       ")
		self.menu_text = GLabel("Symbols")
		self.ending_text = GLabel("")
		self.highscore_text = GLabel("Highscore")
		self.highscore = [GLabel("")] * HIGHSCORE_AMOUNT
		self.highscore_eg = GLabel("0.   "+str(sum(self.brick_score_list)))
		self.highscore_eg.font = "-25"
		self.highscore_eg.x = self.window.width//2 - self.highscore_eg.width//2
		self.retry_click_text = GLabel("Click to Restart ( 3 sec left )")

		# Score label
		self.score = 0
		self.score_text = GLabel("Score : " + str(self.score))
		self.score_text.font = "-20"
		self.score_text.x = 0
		self.score_text.y = self.window.height - 1
		self.life_score = 0

		# Life label
		self.life_label = GLabel("")
		for i in range(MAX_LIFE):
			self.life_label.text += "♥"
		self.life_label.font = "-30"
		self.life_label.x = self.window.width - self.life_label.width
		self.life_label.y = self.window.height - 1

		# mouse listener
		onmouseclicked(self.start)
		self.game_start = False
		onmousemoved(self.paddle_move)

	def full_reset(self):
		"""
		reset all the variables
		"""
		self.paddle_width = self.window.width // 4
		self.ball_size = min(self.brick_width, self.brick_height)
		self.paddle = GRect(self.paddle_width, self.paddle_height)
		self.paddle.x = (self.window.width - self.paddle_width) // 2
		self.paddle.y = self.window.height - self.paddle_offset
		color_set(self.paddle, "blue")
		self.ball_set()
		self.lives = MAX_LIFE
		self.ball_lives = [0] * MAX_BALL_AMOUNT
		self.ball_amount = 1
		self.fake_ball_x = (self.window.width - self.ball_size) // 2
		self.fake_ball_y = self.paddle.y - self.ball_size
		self.speed_set()
		self.slow_fraction = 1
		self.brick_lives = [1] * (ROWS * COLUMNS)
		self.brick_gift = [0] * (ROWS * COLUMNS)
		self.gift_vy = [0] * (ROWS * COLUMNS)
		self.gift_switch = [0] * (ROWS * COLUMNS)
		self.brick_set()
		self.gift_set()
		self.score = 0
		self.score_text.text = "Score : 0"
		self.score_text.x = 0
		self.score_text.y = self.window.height - 1
		self.life_score = 0
		self.life_label.text = ""
		for i in range(MAX_LIFE):
			self.life_label.text += "♥"
		self.life_label.x = self.window.width - self.life_label.width

	def speed_set(self):
		"""
		set a random speed for every ball, y direction is always negative
		"""
		for index in range(MAX_BALL_AMOUNT):
			self.vx_list[index] = random.randint(0, MAX_SPEED*2)-MAX_SPEED
			while abs(self.vx_list[index]) < MIN_SPEED:
				self.vx_list[index] = random.randint(0, MAX_SPEED*2)-MAX_SPEED
			self.vy_list[index] = -random.randint(MIN_SPEED, MAX_SPEED)

	def speed_change(self):
		"""
		change the speed by the effect of the score and the gifts
		"""
		vx = [0] * MAX_BALL_AMOUNT
		vy = [0] * MAX_BALL_AMOUNT
		gvy = [0] * (ROWS * COLUMNS)
		multiplier = (1 + min((self.score - self.life_score) / sum(self.brick_score_list)*4, 2)) * self.slow_fraction
		for index in range(MAX_BALL_AMOUNT):
			vx[index] = int(self.vx_list[index] * multiplier)
			vy[index] = int(self.vy_list[index] * multiplier)
		for num in range(ROWS*COLUMNS):
			gvy[num] = int(self.gift_vy[num] * multiplier)
		return vx, vy, gvy

	def object_show(self):
		"""
		show the object in the correct order 
		"""
		self.window.add(self.paddle)
		self.window.add(self.score_text)
		self.window.add(self.life_label)
		for index in range(self.ball_amount):
			self.window.add(self.ball_list[index])
			self.ball_lives[index] = 1
		for index in range(ROWS * COLUMNS):
			self.window.add(self.brick_list[index])

	def paddle_reset(self):
		"""
		reset the paddle
		"""
		self.paddle_width = self.window.width // 4
		self.window.remove(self.paddle)
		xcor = self.paddle.x
		ycor = self.paddle.y
		self.paddle = GRect(self.paddle_width, self.paddle_height, x=xcor, y=ycor)
		color_set(self.paddle, "blue")
		self.window.add(self.paddle)

	def paddle_resize(self):
		"""
		change the paddle width by replacing a new one
		"""
		self.window.remove(self.paddle)
		xcor = self.paddle.x
		ycor = self.paddle.y
		self.paddle = GRect(self.paddle_width, self.paddle_height, x=xcor, y=ycor)
		color_set(self.paddle, "blue")
		self.window.add(self.paddle)

	def ball_show(self):
		"""
		show the balls on the window for self.ball_amount of balls
		"""
		for index in range(self.ball_amount):
			self.window.add(self.ball_list[index])
			self.ball_lives[index] = 1

	def ball_set(self):
		"""
		setting the balls' graphics
		"""
		for index in range(MAX_BALL_AMOUNT):
			self.ball_list[index] = GOval(self.ball_size, self.ball_size)
			self.ball_list[index].x = (self.window.width - self.ball_size) // 2
			self.ball_list[index].y = self.window.height - self.paddle_offset - self.ball_size
			color_set(self.ball_list[index], "black")

	def ball_resize(self):
		"""
		changing the balls' size by replacing a new one
		"""
		self.fake_ball_y = self.paddle.y - self.ball_size
		for index in range(MAX_BALL_AMOUNT):
			self.window.remove(self.ball_list[index])
			xcor = self.ball_list[index].x
			ycor = self.ball_list[index].y
			self.ball_list[index] = GOval(self.ball_size, self.ball_size, x=xcor, y=ycor)
			color_set(self.ball_list[index], "black")
			self.window.add(self.ball_list[index])

	def ball_add(self):
		"""
		add one more ball to the game (maximum 10)
		"""
		self.window.add(self.ball_list[self.ball_amount-1])
		self.ball_lives[self.ball_amount-1] = 1

	def ball_amount_reset(self):
		"""
		set the ball amount to 1
		"""
		for index in range(1, self.ball_amount):
			self.window.remove(self.ball_list[index])
			self.ball_lives[index] = 0
		self.ball_amount = 1

	def ball_reset(self):
		"""
		reset all the balls position
		"""
		for index in range(MAX_BALL_AMOUNT):
			self.ball_list[index].x = self.fake_ball_x
			self.ball_list[index].y = self.fake_ball_y

	def brick_set(self):
		"""
		bricks' initial setting
		"""
		for by in range(ROWS):
			for bx in range(COLUMNS):
				index = bx + by * COLUMNS
				self.brick_list[index] = GRect(self.brick_width, self.brick_height)
				self.brick_list[index].x = bx * (self.brick_width + BRICK_SPACE)
				self.brick_list[index].y = self.brick_offset + by * (self.brick_height + BRICK_SPACE)
				color = (0xFFFFFF // ROWS) * (index // COLUMNS)
				self.brick_score_list[index] = (ROWS - by) * 10
				color_set(self.brick_list[index], color)
				if random.randint(1, int(1/GIFT_CHANCE)) == 1:
					self.brick_gift[index] = random.randint(1, 4)

	def gift_set(self):
		"""
		gifts' initial setting
		"""
		for num in range(ROWS*COLUMNS):
			self.gift_list[num] = GRect(self.gift_size, self.gift_size)
			color_set(self.gift_list[num], GIFT_COLOR[self.brick_gift[num]-1][0])
			self.gift_list[num].x = self.brick_list[num].x + self.brick_width // 2 - self.gift_size // 2
			self.gift_list[num].y = self.brick_list[num].y + self.brick_height // 2 - self.gift_size // 2

	def clear_gift(self):
		"""
		removing all the shown gifts from the window
		"""
		for index in range(ROWS * COLUMNS):
			if self.gift_switch[index] == 1:
				self.window.remove(self.gift_list[index])
				self.gift_switch[index] = 0
				self.gift_vy[index] = 0

	def paddle_move(self, event):
		"""
		change the paddle x position when the mouse moves
		"""
		if event.x < self.paddle.width // 2:
			self.paddle.x = 0
			self.fake_ball_x = (self.paddle.width - self.ball_size) // 2
		elif self.window.width - self.paddle.width // 2 < event.x:
			self.paddle.x = self.window.width - self.paddle.width
			self.fake_ball_x = self.window.width - self.paddle.width // 2 - self.ball_size // 2
		else:
			self.paddle.x = event.x - self.paddle.width // 2
			self.fake_ball_x = event.x - self.ball_size // 2

	def start(self, event):
		"""
		set the starting boolean to True
		"""
		self.game_start = True

	def life_check(self):
		"""
		check if the ball's life or the bricks' life hits zero
		if ball's life hits zero, return 1
		if bricks' life hits zero, return 2
		else, return 0
		"""
		if self.lives == 0:
			return 1
		elif sum(self.brick_lives) == 0:
			return 2
		return 0

	def lose_life(self):
		"""
		change settings when the ball fell to the bottom
		"""
		self.lives -= 1
		self.game_start = False
		self.speed_set()
		self.paddle_reset()
		self.ball_amount_reset()
		self.clear_gift()
		self.slow_fraction = 1
		for index in range(self.ball_amount):
			self.ball_lives[index] = 1
		self.ball_show()
		hearts = ""
		for i in range(self.lives):
			hearts += "♥"
		self.life_label.text = hearts
		self.life_label.x = self.window.width - self.life_label.width
		self.life_score = self.score

	def boundary_bump(self):
		"""
		check if the ball has contact with the boundary
		"""
		for index in range(MAX_BALL_AMOUNT):
			if self.ball_lives[index] == 1:
				if self.window.width - self.ball_size < self.ball_list[index].x:
					self.vx_list[index] = -abs(self.vx_list[index])
				elif self.ball_list[index].x < 0:
					self.vx_list[index] = abs(self.vx_list[index])
				if self.ball_list[index].y < 0:
					self.vy_list[index] = abs(self.vy_list[index])
				elif self.window.height - self.ball_size < self.ball_list[index].y:
					self.ball_lives[index] = 0
					self.window.remove(self.ball_list[index])
					if sum(self.ball_lives) == 0:
						self.lose_life()

	def single_brick(self, brick):
		"""
		brick : the brick object that the ball has contact with
		change settings when a ball collides into a single brick
		"""
		self.window.remove(brick)
		index = self.brick_list.index(brick)
		self.brick_lives[index] = 0
		self.score += self.brick_score_list[index]
		self.score_text.text = "Score : " + str(self.score)
		if self.brick_gift[index] >= 1:
			self.gift_switch[index] = 1
			self.gift_vy[index] = self.gift_speed
			self.window.add(self.gift_list[index])

	def ball_bump(self):
		"""
		check if the ball has contact with the bricks or the paddle
		"""
		for index in range(MAX_BALL_AMOUNT):
			if self.ball_lives[index] == 1:
				lx = self.ball_list[index].x
				mx = self.ball_list[index].x + self.ball_size // 2
				rx = self.ball_list[index].x + self.ball_size
				uy = self.ball_list[index].y
				my = self.ball_list[index].y + self.ball_size // 2
				dy = self.ball_list[index].y + self.ball_size
				up_object = self.window.get_object_at(mx, uy-1)
				down_object = self.window.get_object_at(mx, dy+1)
				left_object = self.window.get_object_at(lx-1, my)
				right_object = self.window.get_object_at(rx+1, my)
				if up_object is self.paddle or left_object is self.paddle or right_object is self.paddle or down_object is self.paddle:
					self.vy_list[index] = -abs(self.vy_list[index])
				elif up_object in self.brick_list:
					self.vy_list[index] = abs(self.vy_list[index])
					self.single_brick(up_object)
				elif down_object in self.brick_list:
					self.vy_list[index] = -abs(self.vy_list[index])
					self.single_brick(down_object)
				elif left_object in self.brick_list:
					self.vx_list[index] = abs(self.vx_list[index])
					self.single_brick(left_object)
				elif right_object in self.brick_list:
					self.vx_list[index] = -abs(self.vx_list[index])
					self.single_brick(right_object)

	def object_move(self):
		"""
		move the objects(shown balls, shown gifts)
		"""
		vx, vy, gvy = self.speed_change()
		for index in range(MAX_BALL_AMOUNT):
			if self.ball_lives[index] == 1:
				self.ball_list[index].x += vx[index]
				self.ball_list[index].y += vy[index]
			else:
				self.ball_list[index].x = self.fake_ball_x
				self.ball_list[index].y = self.fake_ball_y
		for num in range(ROWS * COLUMNS):
			self.gift_list[num].y += self.gift_vy[num]

	def gift_bump(self):
		"""
		check if the gifts has contact with the paddle
		"""
		for index in range(ROWS * COLUMNS):
			if self.gift_switch[index] == 1:
				lx = self.gift_list[index].x
				mx = self.gift_list[index].x + self.gift_size // 2
				rx = self.gift_list[index].x + self.gift_size
				uy = self.gift_list[index].y
				my = self.gift_list[index].y + self.gift_size // 2
				dy = self.gift_list[index].y + self.gift_size
				up_object = self.window.get_object_at(mx, uy-1)
				down_object = self.window.get_object_at(mx, dy+1)
				left_object = self.window.get_object_at(lx-1, my)
				right_object = self.window.get_object_at(rx+1, my)
				if up_object is self.paddle or left_object is self.paddle or right_object is self.paddle or down_object is self.paddle:
					self.gift_switch[index] = 0
					self.window.remove(self.gift_list[index])
					self.gift_vy[index] = 0
					if self.brick_gift[index] == 1:
						self.paddle_width += self.window.width//20
						self.paddle_resize()
					elif self.brick_gift[index] == 2:
						self.ball_amount += 1
						self.ball_add()
					elif self.brick_gift[index] == 3:
						self.slow_fraction *= 0.9
					elif self.brick_gift[index] == 4:
						if self.paddle_width >= self.window.width//8:
							self.paddle_width -= self.window.width//10 
						self.paddle_resize()

	def intro(self):
		"""
		the intro page setup
		"""
		self.intro_text.font = "-80"
		self.intro_text.x = (self.window.width - self.intro_text.width) // 2
		self.intro_text.y = self.window.height//2 + self.intro_text.height // 2
		self.window.add(self.intro_text)
		self.intro_click_text.font = "-20"
		self.intro_click_text.x = (self.window.width - self.intro_click_text.width) // 2
		self.intro_click_text.y = (self.intro_text.y + self.window.height)//2
		self.window.add(self.intro_click_text)

	def loading(self):
		"""
		the loading page setup
		"""
		self.loading_text.font = "-70"
		self.loading_text.x = (self.window.width - self.loading_text.width) // 2
		self.loading_text.y = self.window.height // 3
		self.window.add(self.loading_text)
		self.progress_bar.font = "-40"
		self.progress_bar.x = (self.window.width - self.progress_bar.width) // 2
		self.progress_bar.y = self.loading_text.y + self.loading_text.height
		self.window.add(self.progress_bar)
		self.menu_text.x = (self.window.width - self.menu_text.width) // 2
		self.menu_text.y = self.progress_bar.y + int(self.progress_bar.height*1.2)
		self.window.add(self.menu_text)
		for num in range(len(GIFT_COLOR)):
			self.example_gift[num] = GRect(self.gift_size, self.gift_size)
			color_set(self.example_gift[num], GIFT_COLOR[num][0])
			self.example_gift[num].x = self.window.width//2 - self.gift_size*3
			self.example_gift[num].y = self.menu_text.y + int(self.gift_size*1.5*(num+0.7)) - self.gift_size//3
			self.gift_explanation[num] = GLabel(GIFT_COLOR[num][1])
			self.gift_explanation[num].x = self.window.width//2 - self.gift_size*1
			self.gift_explanation[num].y = self.menu_text.y + int(self.gift_size*1.5*(num+0.7)) + self.gift_explanation[num].height
			self.window.add(self.example_gift[num])
			self.window.add(self.gift_explanation[num])
		for tick in range(6):
			self.single_bar(["▏", "▎", "▍", "▌", "▋", "▊", "▉", "█"], tick)

	def single_bar(self, sign, tick):
		"""
		sign : the progress bar sign
		tick : the index of the changing bar sign
		changing the progress bar
		"""
		for i in range(8):
			self.progress_bar.text = self.progress_bar.text[:tick]+sign[i]+self.progress_bar.text[tick+1:len(self.progress_bar.text)-1]
			pause(50)

	def win(self):
		"""
		the winning label setting
		"""
		self.ending_text.text = "Congratulations!!!"
		self.ending_text.font = "-45"
		self.ending_text.x = (self.window.width - self.ending_text.width) // 2
		self.ending_text.y = (self.window.height + self.ending_text.height) // 3
		self.window.add(self.ending_text)

	def lose(self):
		"""
		the losing label setting
		"""
		self.ending_text.text = "Game Over"
		self.ending_text.font = "-70"
		self.ending_text.color = "red"
		self.ending_text.x = (self.window.width - self.ending_text.width) // 2
		self.ending_text.y = (self.window.height + self.ending_text.height) // 3
		self.window.add(self.ending_text)

	def final_score(self):
		"""
		the final score page setup
		"""
		self.score_text.text = "Score : " + str(self.score) + " / " + str(sum(self.brick_score_list))
		self.score_text.x = (self.window.width - self.score_text.width) // 2
		self.score_text.y = self.ending_text.y + self.score_text.height * 5
		self.window.add(self.score_text)
		self.retry_click_text.font = "-15"
		self.retry_click_text.x = (self.window.width - self.retry_click_text.width) // 2
		self.retry_click_text.y = (self.window.height + self.score_text.y) // 2
		self.window.add(self.retry_click_text)
		self.game_start = False
		for tick in range(3):
			pause(1000)
			self.retry_click_text.text = self.retry_click_text.text[:19] + str(2-tick) + self.retry_click_text.text[20:]
		pause(1000)


	def high_score(self, all_score):
		"""
		the high score page setup
		"""
		all_score.sort(reverse=True)
		self.highscore_text.font = "-40"
		self.highscore_text.x = self.window.width//2 - self.highscore_text.width//2
		self.highscore_text.y = self.window.height//5
		self.window.add(self.highscore_text)
		nan_text = ""
		for i in range(len(str(sum(self.brick_score_list)))):
			nan_text += "- "
		for num in range(HIGHSCORE_AMOUNT):
			if num < len(all_score):
				spacing = ""
				for s in range(len(str(sum(self.brick_score_list))) - len(str(all_score[num]))):
					spacing += "  "
				self.highscore[num] = GLabel(str(num+1)+".   "+spacing+str(all_score[num]))
			else:
				self.highscore[num] = GLabel(str(num+1)+".   "+nan_text)
			self.highscore[num].font = "-25"
			self.highscore[num].x = self.highscore_eg.x
			self.highscore[num].y = self.highscore_text.y + self.highscore[num].height*2*(num+1)
			self.window.add(self.highscore[num])
コード例 #23
0
class BreakoutGraphics:
    def __init__(self,
                 ball_radius=BALL_RADIUS,
                 paddle_width=PADDLE_WIDTH,
                 paddle_height=PADDLE_HEIGHT,
                 paddle_offset=PADDLE_OFFSET,
                 brick_rows=BRICK_ROWS,
                 brick_cols=BRICK_COLS,
                 brick_width=BRICK_WIDTH,
                 brick_height=BRICK_HEIGHT,
                 brick_offset=BRICK_OFFSET,
                 brick_spacing=BRICK_SPACING,
                 title='Breakout'):

        # Create a graphical window, with some extra space
        window_width = brick_cols * (brick_width +
                                     brick_spacing) - brick_spacing
        window_height = brick_offset + 3 * (brick_rows *
                                            (brick_height + brick_spacing) -
                                            brick_spacing)
        self.window = GWindow(width=window_width,
                              height=window_height,
                              title='Breakout')

        # Element score label
        self.score = 0
        self.score_label = GLabel('Score: ' + str(self.score))

        # Element for game winning
        self.win_show = GLabel('Create by Mike Lin', x=100, y=100)
        self.win_show2 = GLabel('March 20 stanCode SC101', x=135, y=115)

        # Create a paddle
        self.paddle = GRect(paddle_width,
                            paddle_height,
                            x=(window_width - paddle_width) / 2,
                            y=window_height - paddle_offset)
        self.window.add(self.paddle)
        self.paddle.filled = True

        # Center a filled ball in the graphical window
        self.ball = GOval(2 * ball_radius,
                          2 * ball_radius,
                          x=window_width / 2 - ball_radius,
                          y=window_height / 2 - ball_radius)
        self.ball_x = window_width / 2 - ball_radius
        self.ball_y = window_height / 2 - ball_radius

        # Default initial velocity for the ball
        self.__dx = 0
        self.__dy = 0

        # Other variables
        self.total_bricks = 0

        # Initialize our mouse listeners
        onmousemoved(
            self.paddle_move)  # using own method must add 'self.' in the front
        onmouseclicked(self.clicked)
        self.draw_bricks_and_ball()

    def draw_bricks_and_ball(self):
        """
        set the bricks and balls
        """
        self.window.add(self.score_label, x=0, y=15)
        self.window.add(self.ball)
        self.ball.filled = True
        color_num = BRICK_COLS / 5
        for i in range(BRICK_ROWS):
            for j in range(BRICK_COLS):
                if j // color_num == 0:
                    color = 'red'
                elif j // color_num == 1:
                    color = 'orange'
                elif j // color_num == 2:
                    color = 'yellow'
                elif j // color_num == 3:
                    color = 'green'
                else:
                    color = 'blue'
                bricks = GRect(BRICK_WIDTH, BRICK_HEIGHT)
                self.window.add(bricks,
                                x=0 + i * (BRICK_WIDTH + BRICK_SPACING),
                                y=BRICK_OFFSET + j *
                                (BRICK_HEIGHT + BRICK_SPACING))
                bricks.filled = True
                bricks.fill_color = color
                self.total_bricks += 1

    def paddle_move(self, m):
        """
        :param m: mouse you move
        this function controls the moving of the paddle and prevents it from disappearing
        """
        if self.paddle.width / 2 <= m.x <= self.window.width - self.paddle.width / 2:
            self.paddle.x = m.x - self.paddle.width / 2
        elif m.x >= self.window.width:
            self.paddle.x = self.window.width - self.paddle.width
        elif m.x < 0:
            self.paddle.x = 0

    def clicked(self, m):
        """
        the boolean that controls the start of the game once you clicked the mouse
        """
        if (self.ball.x, self.ball.y) == (self.ball_x, self.ball_y):
            self.__dx = random.randint(1, MAX_X_SPEED)
            if random.random() > 0.5:
                self.__dx = -self.__dx
            self.__dy = INITIAL_Y_SPEED

    def set_ball_direct(self):
        """
        to set the ball's direction and the action the ball takes when hitting the walls, bricks, paddle
        """
        self.ball.move(self.__dx, self.__dy)
        self.meet_the_wall()
        if self.meet_object() is self.paddle:
            self.__dy = -abs(self.__dy)
        elif self.meet_object() is self.ball:
            pass
        elif self.meet_object() is self.score_label:
            pass
        elif self.meet_object() is not None:
            self.window.remove(self.meet_object())
            self.__dy *= -1
            self.total_bricks -= 1
            self.score += 1
            self.score_label.text = 'Score: ' + str(self.score)
            if self.total_bricks == 0:
                self.ball.x = self.ball_x
                self.ball.y = self.ball_y
                self.window.add(self.win_show)
                self.window.add(self.win_show2)
                self.win_show.font = '-30'

    def meet_the_wall(self):
        """
        the function that determines the ball's vy
        """
        if self.ball.x <= 0:
            self.__dx *= -1
        elif self.ball.x + self.ball.width >= self.window.width:
            self.__dx *= -1
        elif self.ball.y <= 0:
            self.__dy *= -1
        elif self.ball.y + self.ball.height >= self.window.height:
            self.__dx = 0
            self.__dy = 0

    def dead(self):
        """
        to set the ball to start point when falling under the bottom window
        """
        if self.ball.y + self.ball.height >= self.window.height:
            self.ball.x = self.ball_x
            self.ball.y = self.ball_y
            return True

    def meet_object(self):
        """
        the detector for checking what the ball hits
        :return: the obstacle that ball hits
        """
        obstacle1 = self.window.get_object_at(self.ball.x, self.ball.y)
        obstacle2 = self.window.get_object_at(self.ball.x + self.ball.width,
                                              self.ball.y)
        obstacle3 = self.window.get_object_at(self.ball.x + self.ball.width,
                                              self.ball.y + self.ball.height)
        obstacle4 = self.window.get_object_at(self.ball.x,
                                              self.ball.y + self.ball.height)
        if obstacle1 is not None and not self.ball:
            return obstacle1
        elif obstacle2 is not None:
            return obstacle2
        elif obstacle3 is not None:
            return obstacle3
        elif obstacle4 is not None:
            return obstacle4
        else:
            return None

    def get_dx(self):
        """
        to get dx speed
        :return: dx speed
        """
        return self.__dx

    def get_dy(self):
        """
        to get dy speed
        :return: dy speed
        """
        return self.__dy
コード例 #24
0
class BreakoutGraphics:
    def __init__(self,
                 ball_radius=BALL_RADIUS,
                 paddle_width=PADDLE_WIDTH,
                 paddle_height=PADDLE_HEIGHT,
                 paddle_offset=PADDLE_OFFSET,
                 brick_rows=BRICK_ROWS,
                 brick_cols=BRICK_COLS,
                 brick_width=BRICK_WIDTH,
                 brick_height=BRICK_HEIGHT,
                 brick_offset=BRICK_OFFSET,
                 brick_spacing=BRICK_SPACING,
                 title='Breakout'):

        # Initialize variable
        self.state = 0
        self.ball_radius = ball_radius
        self.brick_width = brick_width
        self.__bullets = BULLETS
        self.__paddle_width = paddle_width
        self.__paddle_height = paddle_height
        color = 'black'

        # Create a graphical window, with some extra space.
        window_width = brick_cols * (brick_width +
                                     brick_spacing) - brick_spacing
        window_height = brick_offset + 3 * (brick_rows *
                                            (brick_height + brick_spacing) -
                                            brick_spacing)
        self.window = GWindow(width=window_width,
                              height=window_height,
                              title=title)

        # Loading Animation
        self.icon = GImage('icon/breakoutico.png')
        self.window.add(self.icon, (self.window.width - self.icon.width) / 2,
                        self.window.height / 9)
        loading = GRect(30, 30)
        loading_width = 30
        loading.filled = True
        self.window.add(loading, 50, self.window.height / 2)
        for i in range(11):
            self.window.remove(loading)
            loading_width += 30
            loading = GRect(loading_width, 30)
            loading.filled = True
            self.window.add(loading, 50, self.window.height * 2 / 3)
            pause(200)
        # Loading Animation End

        # Create a paddle.
        paddle = GRect(paddle_width, paddle_height)
        paddle.filled = True
        paddle.fill_color = 'black'
        self.paddle = paddle
        self.paddle_height = self.window.height - paddle_offset
        self.window.add(paddle, (self.window.width - self.paddle.width) / 2,
                        self.paddle_height)

        # Center a filled ball in the graphical window.
        self.ball = []
        self.ball.append(
            Ball(ball_radius * 2,
                 ball_radius * 2,
                 dx=MAX_X_SPEED,
                 dy=INITIAL_Y_SPEED))
        self.window.add(self.ball[0], (self.window.width / 2 - ball_radius),
                        (self.window.height / 2 - ball_radius))

        # Create treasure array
        self.treasure = []
        self.bullet = []

        # Draw bricks and initial brick lives
        self.brick = []
        self.brick_live = []
        for i in range(0, brick_cols):
            for j in range(0, brick_rows):
                life = 1
                if j // 2 == 0:
                    color = 'red'
                    life = 5
                elif j // 2 == 1:
                    color = 'orange'
                    life = 4
                elif j // 2 == 2:
                    color = 'yellow'
                    life = 3
                elif j // 2 == 3:
                    color = 'green'
                    life = 2
                elif j // 2 == 4:
                    color = 'blue'
                    life = 1
                self.brick.append(GRect(brick_width, brick_height))
                self.brick_live.append(life)
                self.brick[-1].filled = True
                self.brick[-1].fill_color = color
                self.brick[-1].color = color
                self.window.add(self.brick[-1],
                                x=i * (brick_width + brick_spacing),
                                y=j * (brick_height + brick_spacing) +
                                brick_offset)

        # Loading page end
        self.window.remove(loading)
        self.icon.move(0, 200)

    def start(self, e):
        """
        Start the game
        :param e: event
        :return: None
        """
        onmousemoved(self.paddle_move)
        onmouseclicked(self.click)
        self.window.remove(self.icon)

    def paddle_move(self, e):
        """
        The paddle will follow the mouse
        :param e: the mouse coordinate
        :return: None
        """
        if self.paddle.width / 2 < e.x < self.window.width - self.paddle.width / 2:
            self.paddle.x = e.x - self.paddle.width / 2
        elif e.x < self.paddle.width / 2:
            self.paddle.x = 0
        else:
            self.paddle.x = self.window.width - self.paddle.width

    def click(self, e):
        """
        The event when mouse clicked (Start game of fire bullet)
        :param e: mouse event
        :return: None
        """
        if not self.state:
            self.state = 1
        elif self.bullets:
            self.bullet_fire(x=e.x)

    def reset(self):
        """
        Reset the game when lose ball
        :return: None
        """
        self.state = 0
        self.ball.append(Ball(self.ball_radius * 2, self.ball_radius * 2))
        self.window.add(self.ball[-1],
                        self.window.width / 2 - self.ball_radius,
                        self.window.height / 2 - self.ball_radius)
        for i in range(len(self.treasure)):
            self.window.remove(self.treasure[len(self.treasure) - i - 1])
            del self.treasure[len(self.treasure) - i - 1]
        if self.paddle.width != self.__paddle_width:
            self.window.remove(self.paddle)
            paddle = GRect(self.__paddle_width, self.__paddle_height)
            paddle.filled = True
            paddle.fill_color = 'black'
            self.paddle = paddle
            self.window.add(paddle,
                            (self.window.width - self.paddle.width) / 2,
                            self.paddle_height)

    def if_collide(self, x, y):
        """
        Return if (x, y) have object
        :param x: x-coordinate
        :param y: y-coordinate
        :return: (Bool) If have object
        """
        maybe_object = self.window.get_object_at(x, y)
        if maybe_object is not None:
            return True
        else:
            return False

    def add_ball(self, x, y):
        """
        Add ball at (x, y)
        :param x: x-coordinate
        :param y: y-coordinate
        :return: None
        """
        self.ball.append(Ball(self.ball_radius * 2, self.ball_radius * 2))
        self.window.add(self.ball[-1], x, y)

    def add_treasure(self, types, brick_index):
        """
        Add treasure at brick center
        :param types: (int) the type of treasure
        :param brick_index: (int) the index of the brick where treasure being add
        :return: None
        """
        self.treasure.append(Treasure(types))
        self.window.add(self.treasure[-1],
                        self.brick[brick_index].x + self.brick_width,
                        self.brick[brick_index].y)

    def paddle_increase(self):
        """
        Double the width of paddle
        :return: None
        """
        x = self.paddle.x + self.paddle.width / 2
        self.window.remove(self.paddle)
        if self.paddle.width >= self.__paddle_width:
            paddle = GRect(self.__paddle_width * 2, self.__paddle_height)
        else:
            paddle = GRect(self.__paddle_width, self.__paddle_height)
        paddle.filled = True
        paddle.fill_color = 'black'
        self.paddle = paddle
        self.window.add(paddle, x - (self.paddle.width / 2),
                        self.paddle_height)

    def paddle_decrease(self):
        """
        Decrease paddle width by 1/2
        :return: None
        """
        x = self.paddle.x + self.paddle.width / 2
        self.window.remove(self.paddle)
        if self.paddle.width <= self.__paddle_width:
            paddle = GRect(self.__paddle_width / 2, self.__paddle_height)
        else:
            paddle = GRect(self.__paddle_width, self.__paddle_height)
        paddle.filled = True
        paddle.fill_color = 'black'
        self.paddle = paddle
        self.window.add(paddle, x - (self.paddle.width / 2),
                        self.paddle_height)

    def brick_collide(self, index):
        """
        Handles the brick related function when being hit
        :param index: (int) the brick index which being hit
        :return: None
        """
        self.brick_live[index] -= 1
        self.brick[index].fill_color = (BRICK_LIFE[self.brick_live[index]])
        self.brick[index].color = (BRICK_LIFE[self.brick_live[index]])
        if self.brick_live[index] <= 0:
            if_treasure = random.randint(0, 800)
            if if_treasure < 80:
                self.add_treasure(if_treasure % 8, index)
            self.brick_remove(index)

    def brick_remove(self, index):
        """
        Remove brick from window
        :param index: (int) the brick index to remove
        :return: None
        """
        self.window.remove(self.brick[index])
        del self.brick[index]
        del self.brick_live[index]

    def bullet_fire(self, x=0):
        """
        Fire the bullet
        :param x: the x-coordinate to fire the bullet
        :return: None
        """
        self.bullet.append(Bullet())
        self.window.add(self.bullet[-1], x, self.paddle_height)
        self.__bullets -= 1

    def add_bullets(self, number):
        """
        Add bullets storage
        :param number: (int) how many bullets to add
        :return:
        """
        self.__bullets += number

    @property
    def bullets(self):
        return self.__bullets
コード例 #25
0
class BreakoutGraphics:
    def __init__(self,
                 ball_radius=BALL_RADIUS,
                 paddle_width=PADDLE_WIDTH,
                 paddle_height=PADDLE_HEIGHT,
                 paddle_offset=PADDLE_OFFSET,
                 brick_rows=BRICK_ROWS,
                 brick_cols=BRICK_COLS,
                 brick_width=BRICK_WIDTH,
                 brick_height=BRICK_HEIGHT,
                 brick_offset=BRICK_OFFSET,
                 brick_spacing=BRICK_SPACING,
                 title='Breakout'):

        # Create a graphical window, with some extra space.
        window_width = brick_cols * (brick_width +
                                     brick_spacing) + brick_spacing
        window_height = brick_offset + 3 * (brick_rows *
                                            (brick_height + brick_spacing) +
                                            brick_spacing)
        self.window = GWindow(width=window_width,
                              height=window_height,
                              title=title)

        # Create a paddle.
        self.paddle = GRect(paddle_width,
                            paddle_height,
                            x=(window_width - paddle_width) / 2,
                            y=window_height - paddle_height - paddle_offset)
        self.obj_fill_color_add(self.paddle, "black")

        # Center a filled ball in the graphical window.
        self.ball = GOval(ball_radius,
                          ball_radius,
                          x=(window_width - ball_radius) / 2,
                          y=(window_height - ball_radius) / 2)
        self.obj_fill_color_add(self.ball, "black")

        # Default initial velocity and direction control for the ball.
        self.init_ball_velocity()

        # Game flow control related
        self.ball_active = False
        self.remained_life = 0
        self.remained_bricks = brick_cols * brick_rows

        # Initialize our mouse listeners.
        #only when mouse clicked would active the game
        onmouseclicked(self.game_active)
        onmousemoved(self.move_paddle)

        # Draw bricks.
        # brick colors selections
        bricks_colors = ["red", "orange", "yellow", "green", "blue"]
        # init bricks[1] ~ bricks[101], bricks[0] no use leave it as "None"
        self.bricks = [None] * 101
        for col in range(1, brick_cols + 1):
            for row in range(1, brick_rows + 1):
                self.bricks[col * row] = GRect(
                    brick_width,
                    brick_height,
                    x=col * (brick_spacing + brick_width) - brick_width,
                    y=row * (brick_spacing + brick_height) - brick_height)
                self.obj_fill_color_add(self.bricks[col * row],
                                        bricks_colors[(row - 1) // 2])

    # getter for ball dx
    def get_ball_dx(self):
        return self.__dx

    # setter for ball dx
    def set_ball_dx(self, val):
        self.__dx = val
        return self.__dx

    # getter for ball dx_right
    def get_ball_dx_right(self):
        return self.__dx_right

    # setter for ball dx_right
    def set_ball_dx_right(self, val):
        self.__dx_right = val
        return self.__dx_right

    # getter for ball dy
    def get_ball_dy(self):
        return self.__dy

    # setter for ball dy
    def set_ball_dy(self, val):
        self.__dy = val
        return self.__dy

    # getter for ball dy_down
    def get_ball_dy_down(self):
        return self.__dy_down

    # setter for ball dy_down
    def set_ball_dy_down(self, val):
        self.__dy_down = val
        return self.__dy_down

    def init_ball_velocity(self):
        self.__dx = random.randint(MIN_X_SPEED, MAX_X_SPEED)
        if random.random() > 0.5:
            self.__dx = -self.__dx

        if self.__dx > 0:
            self.__dx_right = True
        else:
            self.__dx_right = False

        self.__dy = INITIAL_Y_SPEED
        self.__dy_down = True

    # func for paddle track mouse.x position
    def move_paddle(self, mouse):
        if 0 + self.paddle.width / 2 <= mouse.x <= self.window.width - self.paddle.width / 2:
            self.paddle.x = mouse.x - self.paddle.width / 2

    # func to active game
    def game_active(self, mouse):
        self.ball_active = True

    # reset ball's position
    def reset_ball_position(self):
        self.ball.x = (self.window.width - self.ball.width) / 2
        self.ball.y = (self.window.height - self.ball.height) / 2

    # func helps fill and add object
    def obj_fill_color_add(self, obj, color):
        obj.color = color
        obj.filled = True
        obj.fill_color = color
        self.window.add(obj)
コード例 #26
0
ファイル: breakoutgraphics.py プロジェクト: fredi5566/SC101
class BreakoutGraphics:
    '''
    Description:
    1. Set up initial attributes.
    2. Create graphical window
    3. Create a paddle & filled ball in the graphical window
    4. Draw bricks
    5. Default initial velocity for the ball & Initialize our mouse listeners
    6. Make method to check collision between ball and wall or bricks
    '''
    def __init__(self,
                 ball_radius=BALL_RADIUS,
                 paddle_width=PADDLE_WIDTH,
                 paddle_height=PADDLE_HEIGHT,
                 paddle_offset=PADDLE_OFFSET,
                 brick_rows=BRICK_ROWS,
                 brick_cols=BRICK_COLS,
                 brick_width=BRICK_WIDTH,
                 brick_height=BRICK_HEIGHT,
                 brick_offset=BRICK_OFFSET,
                 brick_spacing=BRICK_SPACING,
                 title='Breakout'):  # 方便改constant

        # Create a graphical window, with some extra space
        window_width = brick_cols * (brick_width +
                                     brick_spacing) - brick_spacing
        window_height = brick_offset + 3 * (brick_rows *
                                            (brick_height + brick_spacing) -
                                            brick_spacing)
        self.window = GWindow(width=window_width,
                              height=window_height,
                              title=title)

        # Create a paddle
        self.paddle = GRect(paddle_width, paddle_height)
        self.paddle_offset = paddle_offset
        self.paddle.filled = True
        self.paddle.color = 'gray'
        self.paddle.fill_color = 'gray'

        # Center a filled ball in the graphical window
        self.ball = GOval(ball_radius * 2, ball_radius * 2)
        self.ball.filled = True
        self.ball.color = 'pink'
        self.ball.fill_color = 'pink'
        self.window.add(self.ball, (self.window.width - self.ball.width) / 2,
                        (self.window.height - self.ball.height) / 2)

        # Default initial velocity for the ball
        self.__dx = random.randint(
            1, MAX_X_SPEED)  # Set up one velocity randomly, then change
        self.__dy = INITIAL_Y_SPEED  # direction of velocity by conditions of methods

        # Initialize our mouse listeners
        onmousemoved(self.track)
        onmouseclicked(self.switch)
        self.is_in_a_move = False

        # Draw bricks
        self.brick_r = brick_rows
        self.brick_c = brick_cols
        self.brick_width = brick_width
        self.brick_height = brick_height
        self.brick_spacing = brick_spacing
        self.brick_offset = brick_offset
        self.draw_bricks()

        # Ball's attributes
        self.ball.r = ball_radius

        # maybe_brick attributes
        self.maybe_brick = self.window.get_object_at(self.ball.x, self.ball.y)
        self.brick_x0 = 0
        self.brick_y0 = 0

        # Setup label
        self.score = 0  # 小心!! 要放在method之前
        self.label = GLabel('Scores:' + str(self.score))
        self.setup_label()

        # Setup life
        self.setup_life()
        self.rect0 = GRect(12, 12)
        self.time = 0
        self.ball_is_out = False

        # Minus life

    def setup_label(self):
        # self.score = 0                          # 為什麼要有這一行??
        # print(self.score)
        self.label = GLabel('Scores:' + str(self.score))  # 跨method 所以要再上面寫
        self.label.color = 'black'
        self.label.font = 'Courier-12-bold'
        self.window.add(self.label, x=10, y=30)

    def setup_life(self):
        for i in range(3):
            self.rect0 = GRect(12, 12)
            self.rect0.filled = True
            self.rect0.color = 'magenta'
            self.rect0.fill_color = 'magenta'
            self.window.add(self.rect0, x=420 - 20 * i, y=15)
        # remove1 = self.window.get_object_at(x=420-20*1, y=610)       # 如果用loop製造多個物件,電腦"當下"只會儲存最新的一個物件
        # self.window.remove(remove1)                                  # 要移除其餘物件的話要先用get_object_at 來取得物件,再移除

    def check_wall(self):
        print('time:', self.time)
        if self.ball.y <= 0:
            self.__dy = -self.__dy

        elif self.ball.x <= 0:
            self.__dx = -self.__dx

        elif self.ball.x + self.ball.width >= self.window.width:
            self.__dx = -self.__dx

        elif self.ball.y >= self.window.height:  # For testing
            self.ball_is_out = True
            remove1 = self.window.get_object_at(x=380 + 20 * self.time, y=15)
            self.window.remove(remove1)
            self.time += 1
            print('New time:', self.time)

    def check_brick2(
        self
    ):  # Set up four corners to determine whether there is an object  # 碰到板子就直接把球往上移就不會抖
        self.left_up = self.window.get_object_at(self.ball.x, self.ball.y)
        self.right_up = self.window.get_object_at(
            self.ball.x + self.ball.width, self.ball.y)
        self.left_down = self.window.get_object_at(
            self.ball.x, self.ball.y + self.ball.height)
        self.right_down = self.window.get_object_at(
            self.ball.x + self.ball.width, self.ball.y + self.ball.height)

        if self.ball.y + self.ball.height < self.paddle.y:  # Brick
            if self.left_up is not None and self.left_up is not self.label:
                self.window.remove(self.left_up)
                self.__dy = -self.__dy
                self.score += 1
            elif self.right_up is not None and self.right_up is not self.label:
                self.window.remove(self.right_up)
                self.__dy = -self.__dy
                self.score += 1
            elif self.left_down is not None and self.left_down is not self.label:
                self.window.remove(self.left_down)
                self.__dy = -self.__dy
                self.score += 1
            elif self.right_down is not None and self.right_down is not self.label:
                self.window.remove(self.right_down)
                self.__dy = -self.__dy
                self.score += 1
            self.label.text = 'Scores:' + str(self.score)
            # print(self.score)
            return self.score

        elif self.ball.y + self.ball.height >= self.paddle.y:  # Paddle
            if self.left_up is not None:
                self.__dy = -self.__dy
            elif self.right_up is not None:
                self.__dy = -self.__dy
            elif self.left_down is not None:
                self.__dy = -self.__dy
            elif self.right_down is not None:
                self.__dy = -self.__dy

    def check_brick(
            self):  # 要設四個corner,還有 if 跟 else if 來檢查。才不會同時偵測到兩個,因此速度負負得正而沒有反彈
        num = 0
        for i in range(2):
            for j in range(2):
                self.maybe_brick = self.window.get_object_at(
                    self.ball.x + i * self.ball.height,
                    self.ball.y + j * self.ball.height)
                if self.maybe_brick is not None:
                    if self.ball.y + self.ball.height <= self.paddle.y:  # brick
                        self.window.remove(self.maybe_brick)
                        self.__dy *= -1
                        num += 1
                    elif self.ball.y + self.ball.height >= self.paddle.y:  # paddle
                        self.__dy = -self.__dy

    def switch(self, m):
        self.is_in_a_move = True
        print('----------')
        # self.set_ball_velocity()

    def set_ball_velocity(self):  # Increase the fun of game
        self.__dx = random.randint(1, MAX_X_SPEED)
        self.__dy = INITIAL_Y_SPEED
        if random.random() > 0.5:
            # print(random.random())                  # Each random.random is different from 0 to 1
            self.__dx = -self.__dx
            self.__dy = self.__dy

    def get_dx(self):
        return self.__dx

    def get_dy(self):
        return self.__dy

    def track(self, m):  # Function in onmousemoved, m is data of mouse
        # 用 if 設兩個 x 與 y 的邊界
        self.paddle.x = m.x - self.paddle.width / 2
        if m.x <= self.paddle.width / 2:  # left m.x boundary
            self.paddle.x = 0
        if m.x >= self.window.width - self.paddle.width / 2:  # right m.x boundary
            self.paddle.x = self.window.width - self.paddle.width

        self.paddle.y = self.window.height - self.paddle_offset  # paddle.y is a constant
        self.window.add(self.paddle, x=self.paddle.x, y=self.paddle.y)

    def draw_bricks(self):
        for i in range(self.brick_r):  # 上限不包含
            for j in range(self.brick_c):
                brick = GRect(self.brick_width, self.brick_height)
                brick.filled = True
                if 0 <= j < 2:
                    brick.fill_color = 'red'
                    brick.color = 'red'
                elif 2 <= j < 4:
                    brick.fill_color = 'orange'
                    brick.color = 'orange'
                elif 4 <= j < 6:
                    brick.fill_color = 'yellow'
                    brick.color = 'yellow'
                elif 6 <= j < 8:
                    brick.fill_color = 'green'
                    brick.color = 'green'
                else:
                    brick.fill_color = 'blue'
                    brick.color = 'blue'
                self.window.add(brick, x=0 + i * self.brick_width + i * self.brick_spacing, \
                                y=self.brick_offset + j * self.brick_height + j * self.brick_spacing)

    def the_end(self):
        num = 0
        vx = 1
        vy = 0
        if self.score <= 4:
            gameover = GLabel('Game Over')
            gameover.color = 'goldenrod'
            gameover.font = 'Courier-35-bold'
            self.window.add(gameover, x=80, y=400)
            while True:
                pause(1000 / 120)
                if num == 10:
                    break
                else:
                    gameover.move(vx, vy)
                    if gameover.x + gameover.width >= self.window.width or gameover.x == 0:
                        vx = -vx
                        num += 1
        elif self.score >= 5:
            goodgame = GLabel('Congratulation!')
            goodgame.color = 'red'
            goodgame.font = 'Courier-30-bold'
            self.window.add(goodgame, x=30, y=400)
            while True:
                pause(1000 / 120)
                if num == 100:
                    break
                else:
                    goodgame.move(vx, vy)
                    if 0 <= goodgame.x <= 20:
                        goodgame.color = 'red'
                    elif 20 <= goodgame.x <= 40:
                        goodgame.color = 'orange'
                    elif 40 <= goodgame.x <= 60:
                        goodgame.color = 'yellow'
                    elif 60 <= goodgame.x <= 80:
                        goodgame.color = 'green'
                    elif 80 <= goodgame.x <= 100:
                        goodgame.color = 'blue'
                    elif 100 <= goodgame.x <= 109:
                        goodgame.color = 'purple'
                    if goodgame.x + goodgame.width >= self.window.width or goodgame.x == 0:
                        vx = -vx
                        num += 1
                        print(goodgame.x)
コード例 #27
0
class BreakoutGraphics:

    def __init__(self, ball_radius=BALL_RADIUS, paddle_width=PADDLE_WIDTH,
                 paddle_height=PADDLE_HEIGHT, paddle_offset=PADDLE_OFFSET,
                 brick_rows=BRICK_ROWS, brick_cols=BRICK_COLS,
                 brick_width=BRICK_WIDTH, brick_height=BRICK_HEIGHT,
                 brick_offset=BRICK_OFFSET, brick_spacing=BRICK_SPACING,
                 title='Breakout'):

        # Create a graphical window, with some extra space
        self.__window_width = brick_cols * (brick_width + brick_spacing) - brick_spacing
        self.__window_height = brick_offset + 3 * (brick_rows * (brick_height + brick_spacing) - brick_spacing)
        self.__window = GWindow(width=self.__window_width, height=self.__window_height, title=title)

        # Create a paddle
        self.__paddle = GRect(paddle_width, paddle_height)
        self.__paddle.filled = True
        self.__window.add(self.__paddle, self.__window.width / 2 - self.__paddle.width / 2, self.__window.height - paddle_offset)

        # Center a filled ball in the graphical window
        self.__ball = GOval(ball_radius * 2, ball_radius * 2)
        self.__ball.filled = True
        self.__window.add(self.__ball, self.__window.width / 2 - self.__ball.width / 2, self.__window.height / 2 + self.__ball.height / 2)

        # Default initial velocity for the ball
        self.__dx = 0
        self.__dy = 0

        # Initialize our mouse listeners
        self.__restart_game = False
        self.__game_start = False
        onmouseclicked(self.click_event)
        onmousemoved(self.move_event)

        # Draw bricks
        self.__brick_rows = brick_rows
        self.__brick_cols = brick_cols
        self.__brick_width = brick_width
        self.__brick_height = brick_height
        self.__brick_spacing = brick_spacing
        self.__brick_offset = brick_offset
        self.__brick_nums = 0
        self.set_bricks(self.__brick_rows, self.__brick_cols, self.__brick_width, self.__brick_height, self.__brick_spacing, self.__brick_offset)

        # Prepare label
        self.__score = 0
        self.__top_score = 0
        self.__game_end_label = GLabel("GAME OVER")
        self.__game_end_label.font = "Verdana-17"
        self.__game_end_label.color = (150, 0, 0)
        self.__score_label = GLabel("Your Score : " + str(self.__score))
        self.__score_label.font = "Verdana-15"
        self.__score_label.color = (100, 100, 100)
        self.__top_score_label = GLabel("Top Score : " + str(self.__top_score))
        self.__top_score_label.font = "Verdana-15"
        self.__top_score_label.color = (100, 100, 100)
        self.__hint_label = GLabel("Click to Start")
        self.__hint_label.font = "Verdana-15"
        self.__hint_label.color = (100, 100, 100)
        self.__window.add(self.__game_end_label, self.__window.width / 2 - self.__game_end_label.width / 2, 0)
        self.__window.add(self.__score_label, 0, self.__score_label.height)
        self.__window.add(self.__top_score_label, self.__window.width - self.__top_score_label.width, self.__top_score_label.height)
        self.__window.add(self.__hint_label, self.__window.width / 2 - self.__hint_label.width / 2, self.__window.height / 2 + self.__ball.height / 2 + self.__ball.height + self.__hint_label.height * 4)
        self.__life_point_text = ""
        for i in range(3):
            self.__life_point_text += "❤"
        self.__life_point_label = GLabel(self.__life_point_text)
        self.__life_point_label.font = "-22"
        self.__life_point_label.color = (150, 0, 0)
        self.__window.add(self.__life_point_label, self.__window.width - self.__life_point_label.width, self.__window.height)

    def set_bricks(self, brick_rows, brick_cols, brick_width, brick_height, brick_spacing, brick_offset):
        """
        Setting the bricks depends on the brick_rows and brick_cols.
        """
        for x in range(brick_rows):
            for y in range(brick_cols):
                __brick = GRect(brick_width, brick_height)
                __brick.filled = True
                if y < 2:
                    __brick.fill_color = (RED_R, RED_G, RED_B)
                elif y < 4:
                    __brick.fill_color = (ORANGE_R, ORANGE_G, ORANGE_B)
                elif y < 6:
                    __brick.fill_color = (YELLOW_R, YELLOW_G, YELLOW_B)
                elif y < 8:
                    __brick.fill_color = (GREEN_R, GREEN_G, GREEN_B)
                else:
                    __brick.fill_color = (BLUE_R, BLUE_G, BLUE_B)
                __brick.color = (0, 0, 0)
                # if y == 9: (This line switch for building only one row of bricks.)
                #     self.__window.add(__brick, x * (brick_width + brick_spacing), brick_offset + y * (brick_height + brick_spacing))
                #     self.__brick_nums += 1
                self.__window.add(__brick, x * (brick_width + brick_spacing), brick_offset + y * (brick_height + brick_spacing))
                self.__brick_nums += 1


    def refill_bricks(self):
        """
        Refill the bricks when game restart.
        """
        for x in range(self.__brick_rows):
            for y in range(self.__brick_cols):
                __x_coordinate = x * (self.__brick_width + self.__brick_spacing)
                __y_coordinate = self.__brick_offset + y * (self.__brick_height + self.__brick_spacing)
                if self.__window.get_object_at(__x_coordinate, __y_coordinate) is None:
                    __brick = GRect(self.__brick_width, self.__brick_height)
                    __brick.filled = True
                    if y < 2:
                        __brick.fill_color = (RED_R, RED_G, RED_B)
                    elif y < 4:
                        __brick.fill_color = (ORANGE_R, ORANGE_G, ORANGE_B)
                    elif y < 6:
                        __brick.fill_color = (YELLOW_R, YELLOW_G, YELLOW_B)
                    elif y < 8:
                        __brick.fill_color = (GREEN_R, GREEN_G, GREEN_B)
                    else:
                        __brick.fill_color = (BLUE_R, BLUE_G, BLUE_B)
                    __brick.color = (0, 0, 0)
                    # if y == 9: (This line switch for building only one row of bricks.)
                    #     self.__window.add(__brick, __x_coordinate, __y_coordinate)
                    #     self.__brick_nums += 1
                    self.__window.add(__brick, __x_coordinate, __y_coordinate)
                    self.__brick_nums += 1

    def click_event(self, mouse_obj):
        """
        Setting events when mouse clicked on different pages/conditions.
        """
        if self.__restart_game:
            self.clean_record()
            self.set_ball_position()
            self.__game_end_label.y = 0
            self.refill_bricks()
            self.update_life_point(3)
            self.__restart_game = False
        elif not self.__game_start:
            self.__game_start = True
            self.__hint_label.y = 0
            self.initial_velocity()

    def move_event(self, mouse_obj):
        """
        Setting events when mouse moved on different pages/conditions.
        """
        if mouse_obj.x <= 0:
            self.__paddle.x = 0
        elif mouse_obj.x + self.__paddle.width >= self.__window_width:
            self.__paddle.x = self.__window_width - self.__paddle.width
        else:
            self.__paddle.x = mouse_obj.x

    def initial_velocity(self):
        """
        initial the velocity to make ball move.
        """
        self.__dx = random.randint(1, MAX_X_SPEED)
        if random.random() > 0.5:
            self.__dx = -self.__dx
        self.__dy = INITIAL_Y_SPEED

    def set_ball_position(self):
        """
        Set ball's position to the default on center of screen.
        """
        self.__dx = 0
        self.__dy = 0
        self.__ball.x = self.__window.width / 2 - self.__ball.width / 2
        self.__ball.y = self.__window.height / 2 + self.__ball.height / 2

    def one_more_chance(self):
        """
        When losing one life point but still have chances to challenge.
        """
        self.set_ball_position()
        self.__hint_label.text = "Click to Start"
        self.__hint_label.y = self.__window.height / 2 + self.__ball.height / 2 + self.__ball.height + self.__hint_label.height * 4
        self.update_score()
        self.__game_start = False

    def game_over(self):
        """
        When losing all life then game over.
        """
        self.__dx = 0
        self.__dy = 0
        self.__game_end_label.text = "GAME OVER"
        self.__game_end_label.y = self.__window.height / 2 + self.__ball.height / 2 - self.__game_end_label.height
        self.__score_label.text = "Your Score : " + str(self.__score)
        self.__hint_label.text = "Click to Restart"
        self.__hint_label.y = self.__window.height / 2 + self.__ball.height / 2 + self.__ball.height + self.__hint_label.height * 4
        self.update_score()

        self.__game_start = False
        self.__restart_game = True

    def update_score(self):
        """
        Update the current score and top score.
        """
        if self.__score > self.__top_score:
            self.__top_score = self.__score
        self.__score_label.text = "Your Score : " + str(self.__score)
        self.__top_score_label.text = "Top Score : " + str(self.__top_score)
        self.__top_score_label.x = self.__window.width - self.__top_score_label.width

    def clean_record(self):
        """
        Reset the scores record.
        """
        self.__score = 0

    def hit_something(self):
        """
        For ball on screen detecting is hitting something or not.
        """
        for x in range(2):
            for y in range(2):
                maybe_hit_obj = self.__window.get_object_at(self.__ball.x + x * 2 * BALL_RADIUS, self.__ball.y + y * 2 * BALL_RADIUS)
                if maybe_hit_obj is None or maybe_hit_obj is self.__game_end_label or maybe_hit_obj is self.__score_label or maybe_hit_obj is self.__top_score_label or maybe_hit_obj is self.__life_point_label or maybe_hit_obj is self.__hint_label:
                    pass
                else:
                    # when hit bricks
                    if maybe_hit_obj.y < self.__paddle.y:
                        self.__window.remove(maybe_hit_obj)
                        self.__score += 1
                        self.__brick_nums -= 1
                        self.update_score()
                        self.all_bricks_clear()
                    # when hit paddle, prevent loop in +-dy
                    if maybe_hit_obj.y >= self.__paddle.y and self.__dy < 0:
                        return False
                    return True

    def all_bricks_clear(self):
        """
        Check the is all bricks are down to decide if it's game clear.
        """
        if self.__brick_nums == 0:
            self.update_score()
            self.__game_end_label.color = (0, 0, 150)
            self.__game_end_label.text = "GAME CLEAR"
            self.__game_end_label.y = self.__window.height / 2 + self.__ball.height / 2 - self.__game_end_label.height
            self.__hint_label.text = "Click to Restart"
            self.__hint_label.y = self.__window.height / 2 + self.__ball.height / 2 + self.__ball.height + self.__hint_label.height * 4
            self.__game_start = False
            self.__restart_game = True
            return True

    def get_window(self):
        """
        Return the GWindow in use.
        """
        return self.__window

    def get_paddle(self):
        """
        Return the paddle.
        """
        return self.__paddle

    def get_ball(self):
        """
        Return the ball.
        """
        return self.__ball

    def get_dx(self):
        """
        Return the ball's x-pace.
        """
        return self.__dx

    def set_dx(self, dx):
        """
        Set the ball's x-pace.
        """
        self.__dx = dx

    def get_dy(self):
        """
        Return the ball's y-pace.
        """
        return self.__dy

    def set_dy(self, dy):
        """
        Set the ball's y-pace.
        """
        self.__dy = dy

    def update_life_point(self, life_point):
        """
        Update current life point left.
        """
        self.__life_point_text = ""
        for i in range(life_point):
            self.__life_point_text += "❤"
        self.__life_point_label.text = self.__life_point_text
コード例 #28
0
class BreakoutGraphics:
    def __init__(self,
                 ball_radius=BALL_RADIUS,
                 paddle_width=PADDLE_WIDTH,
                 paddle_height=PADDLE_HEIGHT,
                 paddle_offset=PADDLE_OFFSET,
                 brick_rows=BRICK_ROWS,
                 brick_cols=BRICK_COLS,
                 brick_width=BRICK_WIDTH,
                 brick_height=BRICK_HEIGHT,
                 brick_offset=BRICK_OFFSET,
                 brick_spacing=BRICK_SPACING,
                 title='Breakout'):

        # Create a graphical window, with some extra space.
        window_width = brick_cols * (brick_width +
                                     brick_spacing) - brick_spacing
        window_height = brick_offset + 3 * (brick_rows *
                                            (brick_height + brick_spacing) -
                                            brick_spacing)
        self.window = GWindow(width=window_width,
                              height=window_height,
                              title=title)

        # Create a paddle.
        self.paddle = GRect(paddle_width, paddle_height)
        self.paddle.filled = True
        self.window.add(self.paddle,
                        x=(self.window.width - paddle_width) / 2,
                        y=self.window.height - paddle_offset - paddle_height)

        # Center a filled ball in the graphical window.
        self.ball = GOval(ball_radius * 2, ball_radius * 2)
        self.ball.filled = True
        self.window.add(self.ball, self.window.width * 1 / 2 - ball_radius * 2,
                        self.window.height * 1 / 2 - ball_radius * 2)
        self.ball_start_x = self.window.width * 1 / 2 - ball_radius * 2
        self.ball_start_y = self.window.height * 1 / 2 - ball_radius * 2

        # Default initial velocity for the ball.
        self.__dx = 0
        self.__dy = 0

        # Initialize our mouse listeners.
        self.count = 0

        onmouseclicked(self.click)
        onmousemoved(self.paddle_move)

        # Draw bricks.
        for i in range(brick_rows):
            for j in range(brick_cols):

                self.brick = GRect(brick_width, brick_height)
                self.brick.filled = True

                fill_the_color(self.brick, i)
                self.window.add(self.brick,
                                x=0 + (brick_width + BRICK_SPACING) * j,
                                y=BRICK_OFFSET +
                                (brick_height + BRICK_SPACING) * i)

        self.how_many_bricks = brick_rows * brick_cols

    def click(self, mouse):
        """
        int, how many times the user clicks the mouse
        :param mouse: the information which the coder get when the user clicks the mouse
        """
        self.count += 1

    def paddle_move(self, k):
        """
        int, the place of the paddle and set the boundaries of the paddle can move
        :param k: the place where the paddle is
        """
        self.paddle.x = k.x - PADDLE_WIDTH / 2
        self.paddle.y = self.window.height - PADDLE_OFFSET - PADDLE_HEIGHT

        if self.paddle.x >= self.window.width - PADDLE_WIDTH:
            self.paddle.x = self.window.width - PADDLE_WIDTH
        if self.paddle.x <= 0:
            self.paddle.x = 0

    def set_ball_velocity(self):
        """
        int, the velocity of the ball and change the horizontal speed randomly
        """
        self.__dx = random.randint(1, MAX_X_SPEED)
        self.__dy = INITIAL_Y_SPEED

        if random.random() > 0.5:
            self.__dx = -self.__dx

    def collision_and_bounce(self):
        """
        check the object that the ball collides.
        If the ball collides the paddle, it will change the vertical speed.
        If the ball collides the brick, it will change the vertical speed and remove the brick.
        """
        ball_upperleft = self.window.get_object_at(self.ball.x, self.ball.y)
        ball_upperright = self.window.get_object_at(
            self.ball.x + 2 * BALL_RADIUS, self.ball.y)
        ball_lowerleft = self.window.get_object_at(
            self.ball.x, self.ball.y + 2 * BALL_RADIUS)
        ball_lowerright = self.window.get_object_at(
            self.ball.x + 2 * BALL_RADIUS, self.ball.y + 2 * BALL_RADIUS)

        if ball_upperleft is not None:
            if ball_upperleft is not self.paddle:
                self.__dy *= -1
                self.window.remove(ball_upperleft)
                self.how_many_bricks -= 1
                print(self.how_many_bricks)
            if ball_upperleft is self.paddle:
                self.__dy = -INITIAL_Y_SPEED

        elif ball_upperright is not None:
            if ball_upperright is not self.paddle:
                self.__dy *= -1
                self.window.remove(ball_upperright)
                self.how_many_bricks -= 1
                print(self.how_many_bricks)
            if ball_upperright is self.paddle.x:
                self.__dy = -INITIAL_Y_SPEED

        elif ball_lowerleft is not None:
            if ball_lowerleft is not self.paddle:
                self.__dy *= -1
                self.window.remove(ball_lowerleft)
                self.how_many_bricks -= 1
                print(self.how_many_bricks)
            if ball_lowerleft is self.paddle:
                self.__dy = -INITIAL_Y_SPEED

        elif ball_lowerright is not None:
            if ball_lowerright is not self.paddle:
                self.__dy *= -1
                self.window.remove(ball_lowerright)
                self.how_many_bricks -= 1
                print(self.how_many_bricks)
            if ball_lowerright is self.paddle:
                self.__dy = -INITIAL_Y_SPEED

    def get_x_velocity(self):
        """
        :return: int, the horizontal speed for the ball
        """
        return self.__dx

    def get_y_velocity(self):
        """
        :return: int, the vertical speed for the ball
        """
        return self.__dy

    def set_x_velocity(self):
        """
        int, change the horizontal speed for the ball
        """
        self.__dx *= -1

    def set_y_velocity(self):
        """
        int, change the vertical speed for the ball
        """
        self.__dy *= -1

    def get_ball_start_x(self):
        """
        :return: int, the initial horizontal place of the ball
        """
        return self.ball_start_x

    def get_ball_start_y(self):
        """
        :return: int, the initial vertical place of the ball
        """
        return self.ball_start_y

    def remove_ball(self):
        """
        remove the ball from the window
        """
        self.window.remove(self.ball)
コード例 #29
0
class BreakoutGraphics:
    def __init__(self,
                 ball_radius=BALL_RADIUS,
                 paddle_width=PADDLE_WIDTH,
                 paddle_height=PADDLE_HEIGHT,
                 paddle_offset=PADDLE_OFFSET,
                 brick_rows=BRICK_ROWS,
                 brick_cols=BRICK_COLS,
                 brick_width=BRICK_WIDTH,
                 brick_height=BRICK_HEIGHT,
                 brick_offset=BRICK_OFFSET,
                 brick_spacing=BRICK_SPACING,
                 title='Breakout'):

        # Create a graphical window, with some extra space.
        self.window_width = brick_cols * (brick_width +
                                          brick_spacing) - brick_spacing
        self.window_height = brick_offset + 3 * (
            brick_rows * (brick_height + brick_spacing) - brick_spacing)
        self.window = GWindow(width=self.window_width,
                              height=self.window_height,
                              title=title)

        # create score label
        self.score = 0
        self.score_label = GLabel("Score: " + str(self.score))
        self.score_label.font = "Comic Sans MS-20-bold"
        self.window.add(self.score_label, 0,
                        self.window_height - self.score_label.height)

        # create three hit points
        self.point1 = GOval(ball_radius * 2,
                            ball_radius * 2,
                            x=self.window_width - ball_radius * 3,
                            y=self.window_height - self.window_height * 0.06)
        self.point2 = GOval(ball_radius * 2,
                            ball_radius * 2,
                            x=self.window_width - ball_radius * 6,
                            y=self.window_height - self.window_height * 0.06)
        self.point3 = GOval(ball_radius * 2,
                            ball_radius * 2,
                            x=self.window_width - ball_radius * 9,
                            y=self.window_height - self.window_height * 0.06)
        self.point1.filled = True
        self.point2.filled = True
        self.point3.filled = True
        self.point1.color = "white"
        self.point2.color = "white"
        self.point3.color = "white"
        self.point1.fill_color = "salmon"
        self.point2.fill_color = "salmon"
        self.point3.fill_color = "salmon"
        self.window.add(self.point1)
        self.window.add(self.point2)
        self.window.add(self.point3)

        # create a paddle
        self.paddle = GRect(paddle_width, paddle_height)
        self.paddle.filled = True
        self.window.add(self.paddle,
                        x=(self.window_width - paddle_width) / 2,
                        y=self.window_height - paddle_offset - paddle_height)

        # center a filled ball in the graphical window
        self.ball = GOval(ball_radius * 2,
                          ball_radius * 2,
                          x=(self.window_width / 2 - ball_radius),
                          y=(self.window_height / 2 - ball_radius))
        self.ball.filled = True
        self.window.add(self.ball)

        # default initial velocity for the ball
        self.__dx = random.randint(1, MAX_X_SPEED)
        self.__dy = INITIAL_Y_SPEED
        self.reset_dx()
        # Initialize our mouse listeners.
        self.running = False
        onmouseclicked(self.start_running)
        onmousemoved(self.reset_paddle_position)

        # Draw bricks.
        for i in range(brick_cols):
            x_position = 0
            x_position += (brick_width + brick_spacing) * i
            for j in range(brick_rows):
                y_position = brick_offset
                y_position += (brick_height + brick_spacing) * j
                self.bricks = GRect(brick_width, brick_height)
                # coloring
                self.bricks.filled = True
                self.bricks.color = "white"
                if j == 0 or j == 1:
                    self.bricks.fill_color = "black"
                elif j == 2 or j == 3:
                    self.bricks.fill_color = "navy"
                elif j == 4 or j == 5:
                    self.bricks.fill_color = "steelblue"
                elif j == 6 or j == 7:
                    self.bricks.fill_color = "skyblue"
                else:
                    self.bricks.fill_color = "lightblue"
                self.window.add(self.bricks, x=x_position, y=y_position)
        self.bricks_num = brick_cols * brick_rows

    def start_running(self, event):
        self.running = True

    def reset_dx(self):
        if random.random() > 0.5:
            self.__dx = -self.__dx

    def get_dx(self):  # makes breakout.py file can get values of dx & dy
        return self.__dx

    def get_dy(self):
        return self.__dy

    def reset_paddle_position(self, mouse):
        self.paddle.x = mouse.x - self.paddle.width / 2
        if 0 + self.paddle.width / 2 > mouse.x:
            self.paddle.x = 0
        if mouse.x > self.window.width - self.paddle.width / 2:
            self.paddle.x = self.window.width - self.paddle.width
コード例 #30
0
class BreakoutGraphics:

    def __init__(self, ball_radius=BALL_RADIUS, paddle_width=PADDLE_WIDTH,
                 paddle_height=PADDLE_HEIGHT, paddle_offset=PADDLE_OFFSET,
                 brick_rows=BRICK_ROWS, brick_cols=BRICK_COLS,
                 brick_width=BRICK_WIDTH, brick_height=BRICK_HEIGHT,
                 brick_offset=BRICK_OFFSET, brick_spacing=BRICK_SPACING,
                 title='Breakout'):
        # Create a graphical window, with some extra space.
        window_width = brick_cols * (brick_width + brick_spacing) - brick_spacing
        window_height = brick_offset + 3 * (brick_rows * (brick_height + brick_spacing) - brick_spacing)
        self.window = GWindow(width=window_width, height=window_height, title=title)

        # Create a paddle.
        self.paddle = GRect(paddle_width, paddle_height)
        self.window.add(self.paddle, (self.window.width - paddle_width) / 2,
                        self.window.height - paddle_offset - paddle_height)
        self.paddle.filled = True
        self.paddle.fill_color = 'blue'
        self.paddle.color = 'blue'

        # Center a filled ball in the graphical window.
        self.ball = GOval(ball_radius * 2, ball_radius * 2)
        self.ball.filled = True
        self.reset_ball()

        # Default initial velocity for the ball.
        self.__dx = 0
        self.__dy = 0
        self.switch = False

        # Initialize our mouse listeners.
        onmouseclicked(self.game_start)
        onmousemoved(self.move_paddle)

        # Draw bricks.
        by = 0
        for i in range(brick_rows):
            bx = 0
            for j in range(brick_cols):
                self.brick = GRect(brick_width, brick_height)
                self.brick.filled = True
                if i < brick_cols / 5:
                    self.brick.fill_color = 'red'
                elif brick_cols / 5 <= i < brick_cols / 5 * 2:
                    self.brick.fill_color = 'orange'
                elif brick_cols / 5 * 2 <= i < brick_cols / 5 * 3:
                    self.brick.fill_color = 'yellow'
                elif brick_cols / 5 * 3 <= i < brick_cols / 5 * 4:
                    self.brick.fill_color = 'green'
                else:
                    self.brick.fill_color = 'blue'
                self.window.add(self.brick, bx, brick_offset+by)
                bx += brick_width + brick_spacing
            by += brick_height + brick_spacing

        # scoreboard
        self.earned_score = 0
        self.total_score = brick_cols * brick_rows
        self.scoreboard = GLabel(f'score: {self.earned_score}/{self.total_score}', x=10, y=30)
        self.scoreboard.font = 'courier-20'
        self.window.add(self.scoreboard)

    def update_scoreboard(self):
        self.window.remove(self.scoreboard)
        self.scoreboard = GLabel(f'score: {self.earned_score}/{self.total_score}', x=10, y=30)
        self.window.add(self.scoreboard)

    def reset_ball(self):
        self.window.add(self.ball, (self.window.width - self.ball.width) / 2,
                        (self.window.height - self.ball.height) / 2)
        self.__dx = 0
        self.__dy = 0
        self.switch = False

    def move_paddle(self, event):
        self.paddle.x = event.x - self.paddle.width/2

    def game_start(self, event):
        if self.__dx == 0:
            self.__dx = random.randint(1, MAX_X_SPEED)
            if random.random() > 0.5:
                self.__dx = -self.__dx
            self.__dy = INITIAL_Y_SPEED
            self.switch = True

    def get_dx(self):
        return self.__dx

    def get_dy(self):
        return self.__dy