回答編集履歴

2

2024/02/20 16:14

投稿

melian
melian

スコア19860

test CHANGED
@@ -17,12 +17,15 @@
17
17
  basket_x += basket_speed
18
18
 
19
19
  # かごと接触したリンゴを消去
20
+ overlap = []
21
+ basket_rect = pygame.Rect(basket_x, basket_y, 50, 20)
20
22
  for i, (apple_x, apple_y) in enumerate(apples):
21
- apple_rect = pygame.Rect(apple_x, apple_y, 20, 20)
23
+ apple_rect = pygame.Rect(apple_x-20, apple_y-20, 40, 40)
22
- basket_rect = pygame.Rect(basket_x, basket_y, 50, 20)
23
24
  if apple_rect.colliderect(basket_rect):
25
+ overlap.append(i)
26
+
27
+ for i in overlap:
24
- del apples[i]
28
+ del apples[i]
25
- break
26
29
 
27
30
  # 画面をクリア
28
31
  screen.fill((255, 255, 255))

1

2024/02/20 15:16

投稿

melian
melian

スコア19860

test CHANGED
@@ -1,21 +1,20 @@
1
- かごと接触したリンゴを `apples` から削除します。(削除されたリンゴは描画されません)
1
+ かごと接触したリンゴを apples から削除します。(削除されたリンゴは描画されません) また、画面外へ移動したリンゴは除去しておきます。
2
- ※ 本題とは関係ありませんが、画面外へ移動したリンゴオブジェクトを適宜消去する処理(`apples` から削除)を追加するとよいかと思います。
2
+
3
3
  ```python
4
+ # リンゴを下に移動
5
+ new_apples = []
6
+ for apple_x, apple_y in apples:
7
+ apple_y += apple_speed
8
+ # 画面外へ移動したリンゴは追加しない
9
+ if apple_y < HEIGHT:
10
+ new_apples.append((apple_x, apple_y))
11
+ apples = new_apples
4
12
  # かごを左右に移動
5
13
  keys = pygame.key.get_pressed()
6
14
  if keys[pygame.K_LEFT]:
7
15
  basket_x -= basket_speed
8
16
  if keys[pygame.K_RIGHT]:
9
17
  basket_x += basket_speed
10
-
11
- # # リンゴの座標(仮の値)
12
- # apple_x, apple_y = WIDTH//2, 100
13
- #
14
- # apple_rect = pygame.Rect(apple_x, apple_y, 20, 20)
15
- # basket_rect = pygame.Rect(basket_x, basket_y, 50, 20)
16
- #
17
- # if apple_rect.colliderect(basket_rect):
18
- # apple_x, apple_y = -100, -100
19
18
 
20
19
  # かごと接触したリンゴを消去
21
20
  for i, (apple_x, apple_y) in enumerate(apples):