関数を作成する
繰り返し行う命令は関数にします。
与える引数を変えることによって、カスタマイズできるようにします。
しましまを描く関数
shimashima(n, color1, color2)
#画面全体にn本の縞模様を描く。指定した2種類の色を交互に使う
#n 縞の本数
#color1, color2 色
#(screen はグローバル定数として定義)
def shimashima(n, color1, color2): #画面全体に横縞を描く for x in range(0, n): #n回繰り返す if (x%2)==0: color = color1 #偶数の時はcolor1 else: color = color2 #奇数の時はcolor2 height = screen.get_height() #画面の高さを取得 width = screen.get_width() #画面の幅を取得 heightw = height/n #画面の高さをnで割る #n回、y座標をずらしながら指定された色で四角を描く pygame.draw.rect(screen, color, (0, heightw*x, width, heightw))
星を描く関数
hoshi(n, color, center, r1, r2)
#指定された位置に星を描く
#n でっぱりの数
#color 色 (R, G, B)
#center 中心座標 (x, y)
#r1 星の中心からでっぱりまでの距離
#r2 星の中心からへっこみまでの距離
#(screenはグローバル変数として定義)
def hoshi(n, color, center, r1, r2): #星を描く coords = [] #空リストを作成 for x in range(0, n): #n回繰り返す #星の外側の座標を計算 ocoord = (center[0]+r1*math.sin(math.radians(360/n)*x), center[1]-r1*math.cos(math.radians(360/n)*x)) #(x,y) 中心座標に外側の円(半径r1)上の座標を加える 回転角度は(360/n)*x 度 #coordsのリスト に 外の座標(x座標,y座標) を追加する coords.append(ocoord) #星の内側の座標を計算 icoord = (center[0]+r2*math.sin(math.radians(360/n)*(x+0.5)), center[1]-r2*math.cos(math.radians(360/n)*(x+0.5))) #(x,y) 中心座標に内側の円(半径r2)上の座標を加える 回転角度は(360/n)*(x+0.5) 度 coords.append(icoord) #coordsのリスト に 内の座標(x座標,y座標) を追加する pygame.draw.polygon(screen, color, coords, 0) #coordsのリストをもとに多角形を描く
関数を使う
import pygame #モジュールpygameの読み込み import sys import math from pygame.locals import * #ここに関数の定義を入れる pygame.init() #pygameモジュールの初期化 screen = pygame.display.set_mode( (800,600) ) #ウィンドウの表示 #国旗を描く screen.fill( (0,0,0) ) #黒で塗りつぶす shimashima(10, (255,0,0), (255,255,255)) #関数を使ってしましまを描く hoshi(5, (0,0,255), (100,100), 100, 38) #関数を使って星を描く pygame.display.update() #画面を更新 #プログラムの終了処理 while True: #無限ループ for event in pygame.event.get(): #pygameからくるイベントを順に取り出す if event.type == QUIT: #もしイベントがQUITなら pygame.image.save(screen,"kokki.png") #画面をpngファイルとしてセーブ pygame.quit() #pygameモジュールの終了 sys.exit() #プログラムの強制終了