《Python程式設計 從入門到實踐》13-1練習題(建立一組星星)錯誤摘記
阿新 • • 發佈:2018-12-17
正確程式碼
import pygame, sys from pygame.sprite import Group from settings import Settings from star import Star def run_game(): '''遊戲主程式''' # 初始化遊戲設定 pygame.init() settings = Settings() screen = pygame.display.set_mode((settings.screen_width, settings.screen_height)) pygame.display.set_caption('STAR SKY') # 建立star例項 stars = Group() def create_stars(settings, screen, stars): '''建立一群星星''' number_stars_x = calculate_number_stars_x(screen, settings) number_lines = calculate_line_stars(screen, settings) for number_line in range(number_lines): # print('這是第幾行:' + str(number_line)) for number_star in range(number_stars_x): # print('星星這行有: ' + str(number_star)) create_star(screen, number_star, number_line, stars) def create_star(screen, number_star, number_line, stars): '''建立一個星星''' star = Star(screen) # star_width = star.rect.width # star_height = star.rect.height star.rect.x = number_star * (30 + star.rect.width) star.rect.y = number_line * (30 + star.rect.height) print('(' + str(star.rect.x) + ',' + str(star.rect.y) + ')') stars.add(star) def calculate_line_stars(screen, settings): '''計算可以容納幾行星星''' star = Star(screen) star_height = star.rect.height available_space_y = settings.screen_height - 300 number_lines = int(available_space_y / (30 + star_height)) return number_lines print(number_lines) def calculate_number_stars_x(screen, settings): '''計算一行可以容納多少星星''' star = Star(screen) star_width = star.rect.width available_space_x = settings.screen_width - 200 number_stars_x = int(available_space_x / (30 + star_width)) return number_stars_x create_stars(settings, screen, stars) # 遊戲主迴圈 while True: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() screen.fill(settings.bg_color) stars.draw(screen) pygame.display.flip() run_game()
錯在建立一組星星的父函式時,調入create_star(screen, number_stars_x, number_lines, stars),而不是正確的create_star(screen, number_star, number_line, stars),導致行數和列數被定義為固定值,輸出的星星位置引數都在一個點上。
錯誤輸出結果
(924,560) (924,560) (924,560) (924,560) (924,560) (924,560) (924,560) (924,560) (924,560) (924,560) (924,560) (924,560) (924,560) (924,560) (924,560) (924,560) (924,560) (924,560) (924,560) (924,560) (924,560) (924,560) (924,560) (924,560) (924,560) (924,560) (924,560) (924,560)
正確位置引數輸出結果
(0,0)
(132,0)
(264,0)
(396,0)
(528,0)
(660,0)
(792,0)
(0,140)
(132,140)
(264,140)
(396,140)
(528,140)
(660,140)
(792,140)
(0,280)
(132,280)
(264,280)
(396,280)
(528,280)
(660,280)
(792,280)
(0,420)
(132,420)
(264,420)
(396,420)
(528,420)
(660,420)
(792,420)
第一次在這裡做筆記,對編輯器還不是很熟悉。 就為了這麼兩個引數錯誤,試了一個多小時……