for fish in fish_list: fish_pos=Vector2(fish[2],fish[3]) distanse2 = sp - fish_pos if distanse2.length() <= 50: img_fish = pygame.transform.rotozoom(img_fish, 0, 1.1) fish_list.remove(fish)需要怎样改写出大鱼吃小鱼碰撞代码,详细注释
时间: 2023-11-27 14:05:58 浏览: 32
以下是一个简单的大鱼吃小鱼碰撞代码,详细注释:
```python
import pygame
from pygame.math import Vector2
# 初始化pygame
pygame.init()
# 设置屏幕大小
screen_width = 640
screen_height = 480
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("大鱼吃小鱼")
# 加载图片
img_fish_big = pygame.image.load("fish_big.png").convert_alpha()
img_fish_small = pygame.image.load("fish_small.png").convert_alpha()
# 定义鱼的类
class Fish:
def __init__(self, pos, img):
self.pos = pos
self.img = img
self.rect = img.get_rect(center=pos)
self.speed = Vector2(0, 0)
def update(self):
# 移动鱼
self.pos += self.speed
self.rect.center = self.pos
# 限制鱼在屏幕范围内
if self.rect.left < 0:
self.rect.left = 0
self.speed.x *= -1
elif self.rect.right > screen_width:
self.rect.right = screen_width
self.speed.x *= -1
if self.rect.top < 0:
self.rect.top = 0
self.speed.y *= -1
elif self.rect.bottom > screen_height:
self.rect.bottom = screen_height
self.speed.y *= -1
def draw(self, surface):
# 绘制鱼
surface.blit(self.img, self.rect)
# 创建大鱼和小鱼
big_fish = Fish(Vector2(screen_width/2, screen_height/2), img_fish_big)
small_fish_list = []
for i in range(10):
x = pygame.math.Vector2(pygame.math.randint(0, screen_width), pygame.math.randint(0, screen_height))
small_fish_list.append(Fish(x, img_fish_small))
# 游戏循环
running = True
while running:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# 检测大鱼和小鱼是否碰撞
for small_fish in small_fish_list:
distance = big_fish.rect.center - small_fish.rect.center
if distance.length() < 50:
# 大鱼吃掉小鱼
img_fish_big = pygame.transform.rotozoom(img_fish_big, 0, 1.1)
small_fish_list.remove(small_fish)
# 更新大鱼和小鱼
big_fish.update()
for small_fish in small_fish_list:
small_fish.update()
# 绘制画面
screen.fill((255, 255, 255))
big_fish.draw(screen)
for small_fish in small_fish_list:
small_fish.draw(screen)
pygame.display.update()
# 退出pygame
pygame.quit()
```
这个代码中,我们创建了一个 `Fish` 类来表示鱼,其中包含了位置、图片、速度等属性,以及更新位置、绘制鱼等方法。
在游戏循环中,我们先检测大鱼和小鱼是否碰撞,如果距离小于50像素,则大鱼吃掉小鱼,并将大鱼图片放大。然后更新大鱼和小鱼的位置,并绘制画面。
注意,为了让程序更加健壮,我们对鱼的位置进行了限制,保证鱼不会飞出屏幕。同时,我们使用了 `pygame.math` 中的 `Vector2` 类来方便地计算距离和速度。