「無数の」はどのように書けばよいのでしょうか?
ループ内で時間経過を元にして、fireを生成すればよいかと。
無限に生成するとメモリが枯渇するため、生成したfireの生存管理は必須です。
描画範囲外から出たら、リストから削除してくださいな。
◇過去の質問で参考になりそうなもの。
0. pygame spriteで画像ではなく図形を扱いたい(動かしたい)
0. pygameでスペースを押すと、上に動く四角を表示させたい。
結構悩んでらっしゃるみたいなので、サンプルコードを添付します。
こんな感じで次 x,y座標のどこに位置するかを求めればよいのではないでしょうか。
Python
1# -*- coding: utf-8 -*-
2from sys import exit
3import math
4from random import randint
5from itertools import cycle
6import pygame
7from pygame.locals import *
8
9pygame.init()
10screen = pygame.display.set_mode((640, 480))
11pygame.display.set_caption("A126871")
12
13#クラス名は大文字で
14class Fire(object):
15 def __init__(self, x, y):
16 super().__init__()
17 self.w = 10
18 self.h = 10
19 self.rect = Rect(x, y, self.w, self.h)
20 # x方向の増分は固定値:5
21 self.vx = 5
22 # 描画色
23 self.color = (randint(0, 255), randint(0, 255), randint(0, 255))
24
25 def move(self):
26 radians = self.rect.x % 360
27 vy = 2 * math.sin(math.radians(radians)) * self.h
28 # 移動
29 self.rect.move_ip(self.vx, vy)
30
31 def draw(self):
32 pygame.draw.rect(screen, self.color, self.rect)
33
34 @property
35 def is_destroy(self) -> bool:
36 return any([self.rect.x < -self.w, self.rect.y < -self.h, self.rect.x > 640, self.rect.y > 480])
37 #以下の5行と判定は同じです。
38 #if self.rect.x < -self.w or self.rect.y < -self.h:
39 # return True
40 #if self.rect.x > 640 or self.rect.y > 480:
41 # return True
42 #return False
43
44 def __str__(self):
45 return ','.join(map(str, [self.rect.x, self.rect.y, self.rect.width, self.rect.height, self.is_destroy]))
46
47def application_exit():
48 pygame.quit()
49 exit()
50
51def main():
52 clock = pygame.time.Clock()
53 note_list = []
54 # 生成間隔:20、数値が小さいほど生成間隔が短くなります。
55 t = cycle(list(range(20)))
56 while True:
57 clock.tick(30)
58 screen.fill((0, 0, 0))
59 # 時間経過を元に生成
60 i = next(t)
61 if i == 0:
62 note_list.append(Fire(0, 40))
63
64 #生成したオブジェクトに対して移動と描画を行う
65 for note in note_list:
66 note.move()
67 note.draw()
68 #リストからスクリーン範囲外の物を削除
69 note_list = list(filter(lambda x: not x.is_destroy, note_list))
70 pygame.display.update()
71 for event in pygame.event.get():
72 if event.type == QUIT:
73 application_exit()
74 if event.type == KEYDOWN:
75 if event.key == K_ESCAPE:
76 application_exit()
77
78if __name__ == "__main__":
79 main()
80
◇参考情報
0. 9.2.3. 三角関数
0. itertools.cycle
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/05/26 14:24
2018/05/27 12:31