Python Snake游戏终结问题

时间:2019-03-29 19:56:07

标签: python keyboard pygame collision game-development

我正在使用python中的pygame模块编写一个蛇游戏,并且快要结束了,但遇到了一些无法预料的问题。我的代码运行了,但是我的蛇不会向左拐,当我与一个苹果碰撞时,它的大小不会增加,并且苹果也不会消失。此外,当我的角色撞到墙上时,也不会出现最终屏幕。我很肯定这是由于我的代码中的一些小问题引起的,感谢任何人看看我是否可以将其根除,因为我无法这样做。同样,任何改进代码的技巧也将不胜感激。

import sys, time, random, pygame
from random import randrange
pygame.init()
fps_controller = pygame.time.Clock()
#Screen Dimensions
screen_width = 800
screen_height = 800

#Screen Set Up
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("Snake by Bela Zumbansen")
pygame.mouse.set_visible(0)

#Colours
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLACK  = (0, 0, 0)
GREY = (200, 200, 200)
BLUE = (0, 0, 255)
WHITE = (255, 255, 255)
LIGHTBLUE = (0, 155, 155)

#Directions
RIGHT = 1
LEFT = 2
UP = 3
DOWN = 4

#Game Set Up
snake_pos = [100, 100]
snake_body = [[100, 100], [190, 100], [180, 400]]
snake_speed = 10

apple_pos = [random.randrange(1,80)*10, random.randrange(1,80)*10]
apple_spawn = True

direction = RIGHT
update = direction

score = 0

def over():
    run = False
    return run
def game_over():
    screen.fill(LIGHTBLUE)
    draw_text("GAME OVER", 48, WHITE, screen_width/2, screen_height/4)
    draw_text("Score: " + str(score), 22, WHITE,  screen_width / 2, screen_height / 3)
    draw_text("Press SPACE to play again or ESC to exit", 22, WHITE, screen_width/2, screen_height / 4)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE:
                run = True
            if event.key == pygame.K_ESCAPE:
                pygame.quit()
        return run
def draw_text(text, size, color, x, y):
    font = pygame.font.Font('freesansbold.ttf', size)
    TextSurf, TextRect = text_objects(text, font, color)
    TextRect.center = (x, y)
    screen.blit(TextSurf, TextRect)

def text_objects(text, font, color):
    textSurface = font.render(text, True, color)
    return textSurface, textSurface.get_rect()

def eating_apple():
    global score, apple_spawn
    score += 1
    apple_spawn = False

def spawnApple():
    global apple_pos
    apple_pos = [random.randrange(1,80)*10, random.randrange(1,80)*10]

def score(score):
    font = pygame.font.SysFont(None, 25)
    text = font.render("Score: "+str(score), True, WHITE)
    screen.blit(text,(10,10))

def main():
    global update, direction, run, snake_pos, snake_speed, apple_spawn, apple_pos
    pygame.time.delay(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT]:
        update = 'LEFT'
    elif keys[pygame.K_RIGHT]:
        update = RIGHT
    elif keys[pygame.K_UP]:
        update = UP
    elif keys[pygame.K_DOWN]:
        update = DOWN

    if update == RIGHT and direction != LEFT:
        direction = RIGHT
    if update == LEFT and direction != RIGHT:
        direction = LEFT
    if update == UP and direction != DOWN:
        direction = UP
    if update == DOWN and direction != UP:
        direction = DOWN

    if direction == RIGHT:
        snake_pos[0] += snake_speed
    if direction == LEFT:
        snake_pos[0] -= snake_speed
    if direction == UP:
        snake_pos[1] -= snake_speed
    if direction == DOWN:
        snake_pos[1] += snake_speed

    snake_body.insert(0, list(snake_pos))
    if snake_pos[0] == apple_pos[0] and snake_pos[1] == apple_pos[1]:
        eating_apple()
    else:
        snake_body.pop()
    if not apple_spawn:
        spawnApple()

    screen.fill(BLACK)
    for pos in snake_body:
        # Snake body
        # .draw.rect(play_surface, color, xy-coordinate)
        # xy-coordinate -> .Rect(x, y, size_x, size_y)
        pygame.draw.rect(screen, GREEN, pygame.Rect(pos[0], pos[1], 20, 20))

    pygame.draw.rect(screen, RED, pygame.Rect(apple_pos[0], apple_pos[1], 20, 20))

    if snake_pos[0] < 0 or snake_pos[0] > screen_width-20:
        over()
    if snake_pos[1] < 0 or snake_pos[1] > screen_height-20:
        over()

    for block in snake_body[1:]:
        if snake_pos[0] == block[0] and snake_pos[1] == block[1]:
            over()

 #   score(score)
    pygame.display.update()
    fps_controller.tick(25)

#main loop
run = True
while run:
    main()
while not run:
    game_over()

1 个答案:

答案 0 :(得分:0)

  

[...]我的蛇不会向左转[...]

它必须是update = LEFT而不是update = 'LEFT'


  

[...]当我与一个苹果碰撞时,我的大小没有变大,并且苹果没有消失

有一个名为score的变量和函数。重命名变量,例如评分另请参见[Python:具有相同名称的函数和变量](Python:具有相同名称的函数和变量):

scoreval = 0 
def eating_apple():
    global scoreval, apple_spawn
    scoreval += 1
    apple_spawn = False

使用pygame.Rect.colliderect(),检查蛇的头是否吃了苹果:

if pygame.Rect(*snake_pos, 20, 20).colliderect(*apple_pos, 20, 20):
    eating_apple()
else:
    snake_body.pop()

产生苹果后,必须重置状态apple_spawn

def spawnApple():
    global apple_pos, apple_spawn
    apple_pos = [random.randrange(1,80)*10, random.randrange(1,80)*10]
    apple_spawn = True

引用评论:

  

[...]我仍然遇到的问题是,如果蛇与自己碰撞或撞到墙壁,游戏不会结束。我有这些的if陈述,所以我对为什么什么也没发生感到有点困惑[...]

您必须使用global statement在函数run中的全局范围内更改变量over的值:

def over():
    global run
    run = False