contain_of
跟pycharm没关系 索引超出了范围 你看看snake.body是不是空的
不是空的啊,这咋改好,不知道咋弄 import sys
import pygame
SCREEN_X = 600
SCREEN_Y = 600
class Snake(object):
def __init__(self):
self.direction = pygame.K_RIGHT
self.body = []
for _ in range(5):
self.addnode()
def addnode(self):
_, prev_top = 0, 0
if self.body:
prev_left, prev_top = self.body[0].left, self.body[0].top
node = pygame.Rect(prev_left, prev_top, 25, 25)
if self.direction == pygame.K_LEFT:
node.left -= 25
elif self.direction == pygame.K_RIGHT:
node.left += 25
elif self.direction == pygame.K_UP:
node.top -= 25
elif self.direction == pygame.K_DOWN:
node.top += 25
self.body.insert(0, node)
def delnode(self):
pass
def isdead(self):
pass
def move(self):
self.addnode()
self.delnode()
def change_direction(self, curkey):
LR = [pygame.K_LEFT, pygame.K_RIGHT]
UD = [pygame.K_UP, pygame.K_DOWN]
if (curkey in LR) and (self.direction in LR):
return
if (curkey in UD) and (self.direction in UD):
return
self.direction = curkey
class Food:
def __init__(self):
self.rect = pygame.Rect(0, 0, 25, 25)
self.set()
def set(self):
while True:
x = pygame.time.get_ticks() % (SCREEN_X // 25) * 25
y = pygame.time.get_ticks() % (SCREEN_Y // 25) * 25
new_rect = pygame.Rect(x, y, 25, 25)
is_overlap = False
for rect in Snake().body:
if new_rect.colliderect(rect):
is_overlap = True
break
if not is_overlap:
self.rect = new_rect
break
def remove(self):
pass
def show_text(screen):
font = pygame.font.Font(None, 36)
text = font.render("Game Over", True, (255, 0, 0))
screen.blit(text, (SCREEN_X // 2 - 100, SCREEN_Y // 2))
def main(is_dead=None):
pygame.init()
screen_size = (SCREEN_X, SCREEN_Y)
screen = pygame.display.set_mode(screen_size)
pygame.display.set_caption('Snake')
clock = pygame.time.Clock()
scores = 0
snake = Snake()
food = Food()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
if event.type == pygame.KEYDOWN:
snake.change_direction(event.key)
# 死后按 space 重新开始
if event.key == pygame.K_SPACE and snake.isdead():
return main()
# 背景颜色 RGB
screen.fill((255, 255, 255))
if not snake.isdead():
scores += 1
snake.move()
for rect in snake.body:
# 用于绘制矩形
pygame.draw.rect(screen, (20, 220, 39), rect, 0)
snake.isdead()
if is_dead:
show_text(screen)
if food.rect == snake.body[100]:
scores += 50
food.remove()
snake.addnode()
food.set()
pygame.draw.rect(screen, (132, 0, 21), food.rect, 0)
show_text(screen)
pygame.display.update()
clock.tick(10)
if __name__ == '__main__':
main()