APCS 從考題到專題

112學年度高雄中學 | 程式設計培訓增能計畫

張老師

2023年11月11日(六)

09:00 ~ 12:00

  • Python基礎語法與結構
  • APCS考題範例
  • Pygame專題

Selection(選擇) - 選擇式(分支或選擇結構)

比較運算子

條件式: 項目一 比較運算 項目二 (條件成立 True / 條件不成立 False)

  • ==: 是否相等
  • !=: 是否不相等
  •  >: 大於
  • >=: 大於等於
  •  <: 小於
  • <=: 小於等於
  • 邏輯運算子

  • and: 連接 2 個條件。所有條件成立才為 True
  •  or: 連接 2 個條件。任一條件成立即為 True
  • 4種if區段結構

    if 和 elif 都必須接條件式

    • (1) if
    • (2) if-else
    • (3) if-elif... (可以有多個 elif)
    • (4) if-elif...else

    if區段

                
                print("Beebo: Let's hang out.")
                weather = input("How is the weather? ")
                if weather == "sunny":
                    print("(1) Sure. Why not?")
                
            

    if-else區段

                
                print("Beebo: Let's hang out.")
                weather = input("How is the weather? ")
                if weather == "sunny":
                    print("(1) Sure. Why not?")
                else:
                    print("(2) I want to stay home.")
                
            

    if-elif...區段

    可以有多個 elif,都必須接條件式

                
                print('L.Left')
                print('R.Right')
                print('U.Up')
                print('D.Down')
                op = input('> ').upper()
                # 依選項輸出方向
                if op == 'L':
                    print('Left')
                elif op == 'R':
                    print('Right')
                elif op == 'U':
                    print('Up')
                elif op == 'D':
                    print('Down')
                
            

    if-elif...else區段

                
                print('L.Left')
                print('R.Right')
                print('U.Up')
                print('D.Down')
                op = input('> ').upper()
                # 依選項輸出方向
                if op == 'L':
                    print('Left')
                elif op == 'R':
                    print('Right')
                elif op == 'U':
                    print('Up')
                elif op == 'D':
                    print('Down')
                else:
                    print('Wrong direction')
                
            

    Repetition(重複) - for loop迴圈式(迴圈或重複結構)

    for迴圈結構

    • for 迴圈變數 in 一堆數據:
    • 每次迴圈,從一堆數據中讀取一個,存到迴圈變數
    • 迴圈變數,不一定要在迴圈中使用
    • 數據讀完,就離開迴圈

    限定步數

                
                for i in range(7):
                    print(f'#{i}')
                    print('L.Left')
                    print('R.Right')
                    print('U.Up')
                    print('D.Down')
                    op = input('> ').upper()
                    # 依選項輸出方向
                    if op == 'L':
                        print('Left')
                    elif op == 'R':
                        print('Right')
                    elif op == 'U':
                        print('Up')
                    elif op == 'D':
                        print('Down')
                    else:
                        print('Wrong direction')
                
            

    Repetition(重複) - while loop迴圈式(迴圈或重複結構)

    任意步數

                
                while True:
                    print('L.Left')
                    print('R.Right')
                    print('U.Up')
                    print('D.Down')
                    print('Q.Quit')
                    op = input('> ').upper()
                    # 依選項輸出方向或離開
                    if op == 'Q':
                        break
                    elif op == 'L':
                        print('Left')
                    elif op == 'R':
                        print('Right')
                    elif op == 'U':
                        print('Up')
                    elif op == 'D':
                        print('Down')
                    else:
                        print('Wrong direction')
                
            

    一維與二維

    一維轉二維

                
                rows = 4
                cols = 3
                nums = rows * cols
                # 一維轉二維
                for i in range(nums):
                    ri = i // cols
                    ci = i % cols
                    print(f'{i} -> ({ri}, {ci})')
                
            

    二維轉一維

                
                rows = 4
                cols = 3
                nums = rows * cols
                # 二維轉一維
                for ri in range(rows):
                    for ci in range(cols):
                        i = ri * cols + ci
                        print(f'({ri}, {ci}) -> {i}')
                
            

    一維亂數存到二維

                
                import random
                random.seed(1)
                rows = 4
                cols = 3
                # 一維串列
                alist = list(range(1, rows*cols+1))
                print(*alist)
                print()
                # 洗牌
                random.shuffle(alist)
                print('1D-list')
                print(*alist)
                print()
                # 一維亂數存到二維
                atable = []
                for ri in range(rows):
                    arow = []
                    for ci in range(cols):
                        arow.append(alist[ri*cols+ci])
                    atable.append(arow)
                print('2D-table')
                for row in atable:
                    print(*row)
                
            

    二維亂數存到一維

                
                import random
                random.seed(1)
                rows = 4
                cols = 3
                # 一維串列
                nlist = list(range(1, rows*cols+1))
                print(*nlist)
                print()
                # 二維亂數串列
                atable = []
                for ri in range(rows):
                    arow = []
                    for ci in range(cols):
                        # 從一維串列隨機選取一數存到二維中的一列
                        arow.append(nlist.pop(random.randrange(len(nlist))))
                    atable.append(arow)
                print('2D-table')
                for row in atable:
                    print(*row)
                print()
                # 串列合併
                alist = []
                for row in atable:
                    alist = alist + row
                print('1D-list')
                print(*alist)
                print()
                
            

    矩陣題選題

    數字龍捲風

    Pygame專題

    Pygame文字

                
                import os
                import sys
                import pygame
                from pygame.locals import *
                from random import randrange
                # 背景色碼
                def get_bgcolor():
                    R = randrange(64)
                    G = randrange(64)
                    B = randrange(64)
                    return (R, G, B)
                # 前景色碼
                def get_fgcolor():
                    R = randrange(224, 256)
                    G = randrange(224, 256)
                    B = randrange(224, 256)
                    return (R, G, B)
                # 基本設定
                os.environ['SDL_VIDEO_CENTERED'] = '1'
                pygame.init()
                surface = pygame.display.set_mode((400, 400))
                fpsclock = pygame.time.Clock()
                pygame.display.set_caption('Cover')
                # 主迴圈
                while True:
                    # 事件處理
                    for event in pygame.event.get():
                        if event.type == QUIT:
                            pygame.quit()
                            sys.exit()
                    # 視窗背景填色
                    surface.fill(get_bgcolor())
                    # 設定字型
                    font1 = pygame.font.SysFont('Times New Roman', 24, bold=True)
                    font2 = pygame.font.SysFont('Times New Roman', 20, italic=True)
                    font3 = pygame.font.SysFont('Consolas', 16)
                    # 產生文字圖形
                    text1 = font1.render('Pyone Code School', True, get_fgcolor())
                    text2 = font2.render('From Problem to Project', True, get_fgcolor())
                    text3 = font3.render('- Bug Chang', True, get_fgcolor())
                    # 繪製文字圖形
                    surface.blit(text1, (20, 20))
                    surface.blit(text2, (20, 60))
                    surface.blit(text3, (20, 100))
                    # 更新畫面
                    pygame.display.update()
                    # 每秒幀數
                    fpsclock.tick(1)
                
            

    Pygame幾何圖形

                
                import os
                import sys
                from random import randrange
                import pygame
                from pygame.locals import *
                # 顏色
                # https://htmlcolorcodes.com/color-names/
                BGCOLOR    = (255, 250, 240)
                SALMON     = (250, 128, 114)
                DODGERBLUE = ( 30, 144, 255)
                DRAKORANGE = (255, 140,   0)
                OLIVEDRAB  = (107, 142,  35)
                DARKCYAN   = (  0, 139, 139)
                ORCHID     = (218, 112, 214)
                # 基本設定
                os.environ['SDL_VIDEO_CENTERED'] = '1'
                pygame.init()
                surface = pygame.display.set_mode((400, 400))
                fpsclock = pygame.time.Clock()
                pygame.display.set_caption('Drawable')
                surface.fill(BGCOLOR)
                # 矩形
                # rect(surface, color, rect)
                # rect: x, y width, height
                pygame.draw.rect(surface, SALMON, (50, 20, 40, 40))
                pygame.draw.rect(surface, SALMON, (100, 20, 80, 40))
                pygame.draw.rect(surface, SALMON, (190, 20, 40, 40), border_radius=4)
                # 正圓與橢圓
                # circle(surface, color, center, radius, width)
                pygame.draw.circle(surface, DODGERBLUE, (60, 100), 10, 10)
                pygame.draw.circle(surface, DODGERBLUE, (120, 100), 20, 20)
                # ellipse(surface, color, rect)
                pygame.draw.ellipse(surface, DRAKORANGE, (200, 90, 40, 20))
                pygame.draw.ellipse(surface, DRAKORANGE, (260, 80, 20, 40))
                # 線條
                # line(surface, color, start_pos, end_pos, width)
                pygame.draw.line(surface, OLIVEDRAB, (50, 200), (100, 200), 2)
                pygame.draw.line(surface, OLIVEDRAB, (130, 150), (130, 200), 2)
                pygame.draw.line(surface, OLIVEDRAB, (160, 200), (190, 150), 3)
                pygame.draw.line(surface, OLIVEDRAB, (220, 150), (250, 200), 3)
                # 多邊形或特別圖形
                # 點的順序,影響構圖,同樣的點,順序不同,圖就不同
                # polygon(surface, color, points, width)
                # width=0 填滿顏色
                # 平行四邊形
                points = [(50, 300), (90, 350), (110, 300), (70, 250)]
                pygame.draw.polygon(surface, DARKCYAN, points, 3)
                # 六邊形
                points = [(200, 300), (230, 250), (280, 250), (310, 300), (280, 350), (230, 350)]
                pygame.draw.polygon(surface, ORCHID, points, 0)
                # 三個三角形
                points = [(280, 250), (310, 300), (200, 300), (230, 250), (280, 350), (230, 350)]
                pygame.draw.polygon(surface, DARKCYAN, points, 0)
                # 主迴圈
                while True:
                    for event in pygame.event.get():
                        if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
                            pygame.quit()
                            sys.exit()
                    pygame.display.update()
                    fpsclock.tick(1)
                
            

    格點串列

                
                import os
                import sys
                from random import randrange
                import pygame
                from pygame.locals import *
                # 顏色
                # https://htmlcolorcodes.com/color-names/
                BGCOLOR = (255, 255, 255)
                COLORC  = (  0,   0,   0)
                COLORT  = (255, 255, 255)
                # 基本設定
                os.environ['SDL_VIDEO_CENTERED'] = '1'
                pygame.init()
                surface = pygame.display.set_mode((400, 400))
                fpsclock = pygame.time.Clock()
                pygame.display.set_caption('Points')
                surface.fill(BGCOLOR)
                font1 = pygame.font.SysFont('Consolas', 24)
                # 頂點串列
                points = []
                stop = 1
                # circle(surface, color, center, radius, width)
                for x in range(60, 300+1, 60):
                    points.append((x, 100))
                # 主迴圈
                while True:
                    for event in pygame.event.get():
                        if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
                            pygame.quit()
                            sys.exit()
                    # 繪製頂點
                    for p in points[:stop]:
                        x, y = p
                        pygame.draw.circle(surface, COLORC, (x, y), 20, 20)
                        text = font1.render(str(randrange(10)), True, COLORT)
                        surface.blit(text, (x-7, y-10))
                    stop += 1
                    pygame.display.update()
                    fpsclock.tick(1)
                
            

    數字龍捲風專題版

    自由練習