Pygame蛇游戏中的蛇长

时间:2019-03-15 17:22:14

标签: python pygame pycharm

我一直在尝试增加每次在正常工作的苹果上移动时蛇的长度,但是一旦蛇停止移动,蛇的长度就会缩回单个单元,我无法修复那个。

关于游戏

  • 仅当用户按下任意箭头键时,蛇才会移动。

问题2 -我也一直在尝试让蛇自行移动。也就是说,即使用户不按任何键,蛇也应该移动,并且用户将按键来改变蛇的方向。

import pygame
pygame.init()
import time
import random

def gameloop():
    x_width, y_width = 500, 500
    win = pygame.display.set_mode((x_width, y_width))
    pygame.display.set_caption("Snake")

    bgcolor = white = (255, 255, 255)
    red = (255, 0, 0)
    green = (0, 255, 0)
    blue = (0, 0, 255)
    black = (0, 0, 0)

    x_cord, y_cord = x_width/2, y_width/2
    width, height = 10, 10
    x_snake_change, y_snake_change = 10,10

    apple_width = 15
    apple_height = 15

    font = pygame.font.SysFont(None, 20)
    def gameover_message(msg, color):
        text_on_screen = font.render(msg, True, color)
        win.blit(text_on_screen, [x_width/4, y_width/3])
        pygame.display.update()

    rand_apple_x = round(random.randrange(0, x_width-width)/10)*10
    rand_apple_y = round(random.randrange(0, y_width-height)/10)*10
    def apple():
        win.fill(red, rect=[rand_apple_x,rand_apple_y, apple_width, apple_height])

    snake_list=[]
    snake_length = 1

    def snake():
        if len(snake_list) > snake_length:
            del snake_list[0]
            for XnY in snake_list[:-1]:
                win.fill(black, rect=[XnY[0], XnY[1], width, height])

    run = True
    gameover = False
    while run:
        while gameover:
            gameover_message("You Have LOSE, press c to continue and Q to quit", red)
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    run = False
                    gameover = False
                key_press = pygame.key.get_pressed()
                if key_press[pygame.K_c]:
                    gameloop()
                if key_press[pygame.K_q]:
                    win.fill(white)
                    gameover_message("QUITTING", black)
                    time.sleep(1)
                    run = False
                    pygame.quit()
                    quit()

        for event in pygame.event.get():
            print(event)
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()
        # Bg-Color
        win.fill(bgcolor)

        # key_press

        key_press = pygame.key.get_pressed()
        if key_press[pygame.K_DOWN]:# and y_cord < y_width - height:
            y_cord += y_snake_change
        if key_press[pygame.K_RIGHT]:# and x_cord < x_width - width:
            x_cord += x_snake_change
        if key_press[pygame.K_UP]:# and y_cord >0 :
            y_cord -= y_snake_change
        if key_press[pygame.K_LEFT]:# and x_cord > 0:
            x_cord -= x_snake_change

        if x_cord > x_width - width or x_cord < 0 or y_cord < 0 or y_cord > y_width - height:
            gameover = True


        # apple
        apple()


        #  cords apple //   Apple Funciton
        if x_cord >= rand_apple_x and x_cord<=rand_apple_x + apple_width and y_cord >= rand_apple_y  and y_cord <= rand_apple_y + apple_height  :
            rand_apple_x = round(random.randrange(0, x_width - width) / 10) * 10
            rand_apple_y = round(random.randrange(0, y_width - height) / 10) * 10
            snake_length += 1
        snake_XnY_cord = []
        snake_XnY_cord.append(x_cord)
        snake_XnY_cord.append(y_cord)
        snake_list.append(snake_XnY_cord)


        snake()

        # snake
        win.fill(black, rect=[x_cord, y_cord, width, height])

        pygame.display.update()

        time.sleep(0.05)
    pygame.quit()
    quit()
gameloop()

2 个答案:

答案 0 :(得分:1)

两个问题都可以用相同的解决方案解决。

基本上,在游戏循环中,您将有一个像这样的变量:

snake_direction = 'Put Direction Here'

稍后在游戏代码中,注册按键时,您可以更改此变量,例如:

if event.type == pygame.K_LEFT:
    snake_direction = 'Left'

if event.type == pygame.K_RIGHT:
    snake_direction = 'Right'

# And so on with the other directions...

最后,在事件循环即将结束时,在绘制所有内容的位置附近。您可以这样做:

if snake_direction == 'Left':
    x_cord -= x_snake_change

elif snake_direction == 'Right':
    x_cord -= x_snake_change

# And so on with down and up...

这应该允许蛇通过简单的按键改变方向,也可以使其无限期地移动。现在蛇也不会停止,尾巴也不会再收缩到1个单位。

答案 1 :(得分:1)

跳过每一帧中的snake_list

snake_XnY_cord = []
snake_XnY_cord.append(x_cord)
snake_XnY_cord.append(y_cord)
snake_list.append(snake_XnY_cord)

仅在蛇首移动时才更改snake_list。相反,它必须是:

if not snake_list or snake_list[-1] != (x_cord, y_cord):
    snake_list.append((x_cord, y_cord))
snake()

但是要画出整条蛇。整个窗口都填满了每一帧(win.fill(bgcolor)),因此必须重画蛇。更改功能snake

def snake():
    if len(snake_list) > snake_length:
        del snake_list[0]
    for XnY in snake_list:
        win.fill(black, rect=[XnY[0], XnY[1], width, height])

如果要自行移动蛇,则必须存储当前移动。将方向矢量存储到(move_xmove_y)并在按下按钮时对其进行更改。将方向矢量添加到每帧的当前位置:

while run:
move_x, move_y = (0, 0)
while run:

    // [...]

    key_press = pygame.key.get_pressed()
    if key_press[pygame.K_DOWN]:# and y_cord < y_width - height:
        move_x, move_y = (0, y_snake_change)
    elif key_press[pygame.K_RIGHT]:# and x_cord < x_width - width:
        move_x, move_y = (x_snake_change, 0)
    elif key_press[pygame.K_UP]:# and y_cord >0 :
        move_x, move_y = (0, -y_snake_change)
    elif key_press[pygame.K_LEFT]:# and x_cord > 0:
        move_x, move_y = (-x_snake_change, 0)

    x_cord += move_x
    y_cord += move_y