如何刷新变量而不丢失其值?

2024-09-30 01:27:46 发布

您现在位置:Python中文网/ 问答频道 /正文

最近我开始用python编写Snake。我想出了一个主意,让蛇记住它最后的位置。我必须刷新名为body的变量才能使其工作,因为我在主循环开始之前调用了它。当蛇吃苹果时,body变量应该扩展,我不想丢失它的扩展值。你能帮帮我吗? 这是我的代码:

import pygame, math, random

pygame.init()

screen = pygame.display.set_mode((640,640))
pygame.display.set_caption('Snake')


score = 0


x, y = 320,320
dirUp, dirDown = False, False
dirLeft, dirRight = False, False
body = [(x, y)]
snakeImg = [pygame.image.load('snakeblock.png') for i in range(len(body))]





squares = []
for i in range(640):
    if i % 32 == 0:
        squares.append(i)
food = pygame.image.load('fruit.png')
foodx,foody = random.choice(squares), random.choice(squares)

def isCollision(obsX, obsY, x, y):
    return math.sqrt(math.pow(obsX - x, 2) + math.pow(obsY - y, 2)) <= 0

def show_text():
    score_font = pygame.font.Font('freesansbold.ttf',32)
    score_text = score_font.render('Score: {}'.format(score), True, (255,255,255))
    screen.blit(score_text, (0,0))

running = True
i = 0
while running:
    i += 1
    body = body
    pygame.time.Clock().tick(10)
    screen.fill((0,128,0))

    if x > 608 or x < 0:
        running = False
    elif y > 608 or y < 0:
        running = False

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP:
                dirUp = True
                dirLeft, dirDown, dirRight = False, False, False
            if event.key == pygame.K_DOWN:
                dirDown = True
                dirUp, dirLeft, dirRight = False, False, False
            if event.key == pygame.K_RIGHT:
                dirRight = True
                dirUp, dirDown, dirLeft = False, False, False
            if event.key == pygame.K_LEFT:
                dirLeft = True
                dirUp, dirDown, dirRight = False, False, False

    if dirUp:
        y -= 32
    elif dirDown:
        y += 32
    elif dirRight:
        x += 32
    elif dirLeft:
        x -= 32

    for i in range(len(body)):
        if isCollision(foodx,foody,x,y):
            foodx, foody = random.choice(squares), random.choice(squares)
            score += 1
            print( body)
        screen.blit(food, (foodx, foody))
        screen.blit(snakeImg[i], (x, y))

    show_text()

    pygame.display.update()

Tags: eventfalsetrueifbodyrandomscreenpygame

热门问题