From 485b7e97400137e9a0566b4460930714493349ee Mon Sep 17 00:00:00 2001 From: lipj <2117123431@qq.com> Date: Sat, 20 Jul 2024 00:00:30 +0800 Subject: [PATCH] =?UTF-8?q?=E8=A7=A3=E5=86=B3=E9=A3=9F=E7=89=A9=E5=87=BA?= =?UTF-8?q?=E7=8E=B0=E5=9C=A8=E8=9B=87=E8=BA=AB=E4=B8=8A=E7=9A=84=E9=97=AE?= =?UTF-8?q?=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- main.py | 26 +++++++++++++++----------- 1 file changed, 15 insertions(+), 11 deletions(-) diff --git a/main.py b/main.py index 724fc84..0600e3e 100644 --- a/main.py +++ b/main.py @@ -69,23 +69,27 @@ class Snake(object): # 食物类 # 方法: 放置/移除 # 点以25为单位 -class Food: +class Food(object): def __init__(self): self.rect = pygame.Rect(-25,0,25,25) def remove(self): self.rect.x=-25 - def set(self): + + def set(self, snake): if self.rect.x == -25: - allpos = [] - # 不靠墙太近 25 ~ SCREEN_X-25 之间 - for pos in range(25,SCREEN_X-25,25): - allpos.append(pos) - self.rect.left = random.choice(allpos) - self.rect.top = random.choice(allpos) - print(self.rect) - + while True: + allpos = [] + # 不靠墙太近 25 ~ SCREEN_X-25 之间 + for pos in range(25, SCREEN_X - 25, 25): + allpos.append(pos) + self.rect.left = random.choice(allpos) + self.rect.top = random.choice(allpos) + + # Check if the new position overlaps with any part of the snake's body + if not any(self.rect.colliderect(node) for node in snake.body): + break def show_text(screen, pos, text, color, font_bold = False, font_size = 60, font_italic = False): #获取系统字体,并设置文字大小 @@ -147,7 +151,7 @@ def main(): snake.addnode() # 食物投递 - food.set() + food.set(snake) pygame.draw.rect(screen,(136,0,21),food.rect,0) # 显示分数文字 -- Gitee