Python Snake游戏定稿问题

问题描述 投票:2回答:1

我正在使用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()
python keyboard pygame collision game-development
1个回答
0
投票

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

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


[...]当我与苹果碰撞时,我不会长大,苹果也不会消失

有一个变量和一个名为score的函数。重命名变量,例如scoreval。另请参见[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

参考评论:

[...]我仍然遇到的是,如果蛇与自身发生碰撞或撞到墙上,游戏就不会结束。我有那些陈述,所以我有点迷失为什么没有发生[...]

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

def over():
    global run
    run = False
© www.soinside.com 2019 - 2024. All rights reserved.