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

APCS 從考題到專題

碼寶程式教育 張老師

課程大綱

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

選擇結構 - 4種if區段

  • (1) if
  • (2) if-else
  • (3) if-elif... (可以有多個 elif,都必須接條件式)
  • (4) if-elif...else

(1) if


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

(2) 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.")
                        

(3) if-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')
                        

(4) 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')
                        

重複結構 - 迴圈

  • for 迴圈
  • while 迴圈

for 迴圈


                            for i in range(10):
                                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')
                        

while 迴圈


                            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()
                        

數字龍捲風 - 考題討論

APCS - 實作題_題型範例 - P18

c292. APCS2017-0304-3數字龍捲風

Pygame小專題

  • Pygame文字
  • Pygame幾何圖形
  • 格點串列
  • 數字龍捲風專題版

Pygame文字


                            import os
                            import sys
                            import pygame
                            from pygame.locals import *
                            from random import randrange

                            # 背景色碼
                            def get_bgcolor():
                                return (randrange(64), randrange(64), randrange(64))

                            # 前景色碼
                            def get_fgcolor():
                                return (randrange(224, 256), randrange(224, 256), randrange(224, 256))

                            # 基本設定
                            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)
                        

THE END