for i inrange(4): snakebody = Actor('snake1') snakebody.x = Snake[i].x - TILE_SIZE snakebody.y = Snake[i].y Snake.append(snakebody)
direction = 'right' score = 0
defdraw(): screen.clear() cookie.draw() for snakebody in Snake: snakebody.draw() if isLose: screen.draw.text("Game over!", (180, HEIGHT / 2 - 100), fontsize=100, color='skyblue') screen.draw.text("Score: " + str(score), (20, 20), fontsize=25, color='white')
defupdate(): global direction, isLose, score if keyboard.left: direction = 'left' if keyboard.right: direction = 'right' if keyboard.up: direction = 'up' if keyboard.down: direction = 'down' newSnakeHead = Actor('snake1') # 创建新蛇头 if direction == 'up': newSnakeHead.x = Snake[0].x newSnakeHead.y = Snake[0].y - TILE_SIZE if direction == 'down': newSnakeHead.x = Snake[0].x newSnakeHead.y = Snake[0].y + TILE_SIZE if direction == 'left': newSnakeHead.x = Snake[0].x - TILE_SIZE newSnakeHead.y = Snake[0].y if direction == 'right': newSnakeHead.x = Snake[0].x + TILE_SIZE newSnakeHead.y = Snake[0].y
if newSnakeHead.y < 0or newSnakeHead.y > HEIGHT or newSnakeHead.x < 0or newSnakeHead.x > WIDTH: isLose = True for body in Snake: if newSnakeHead.x == body.x and newSnakeHead.y == body.y: isLose = True break
if newSnakeHead.x == cookie.x and newSnakeHead.y == cookie.y: score += 1 cookie.x = random.randint(5, 35) * TILE_SIZE cookie.y = random.randint(5, 25) * TILE_SIZE else: del Snake[len(Snake) - 1] Snake.insert(0, newSnakeHead)