Pygame自动化蛇拒绝撞墙?

2024-05-15 03:47:50 发布

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

我正在创建传统蛇游戏的Pygame脚本,该脚本可以自动运行,即蛇应该知道周围环境(如果撞到墙,会撞碎)并占据食物

为此,我只需从各个方向检查蛇的下一个像素位置NSWE
通过这个PythonnextMove函数确定蛇的轨迹

我将屏幕分辨率设置为600*400,即当蛇接近墙壁时,坐标值变为0到600(最小到最大高度)和0到400(最小到最大宽度)

def nextMove(snake_head):

    x1=snake_head[0]
    y1=snake_head[1]
    next_left=x1-10
    next_right=x1+10
    next_top=y1-10
    next_down=y1+10
    print(next_left,next_right,next_top,next_down)

    if next_left<0:
        x1_change=10
        y1_change=0
        x1+=x1_change
        y1+=y1_change
    if next_right>= dis_width:
        x1_change=-10
        y1_change=0
        x1+=x1_change
        y1+=y1_change
    if next_top<0:
        x1_change=0
        y1_change=10
        x1+=x1_change
        y1+=y1_change
    if next_down>=dis_height:
        x1_change=0
        y1_change=-10
        x1+=x1_change
        y1+=y1_change

蛇头是一个列表,给出x1,y1坐标的值 尽管代码没有错误,蛇还是拒绝了,撞到了墙上

完整代码

import pygame
import time
import random
import math

pygame.init()

white = (255, 255, 255)
yellow = (255, 255, 102)
black = (0, 0, 0)
red = (213, 50, 80)
green = (0, 255, 0)
blue = (50, 153, 213)

dis_width = 600
dis_height = 400

dis = pygame.display.set_mode((dis_width, dis_height))
pygame.display.set_caption('Snake Game')

clock = pygame.time.Clock()

snake_block = 10
snake_speed = 15

font_style = pygame.font.SysFont("bahnschrift", 25)
score_font = pygame.font.SysFont("comicsansms", 35)


def Your_score(score):
    value = score_font.render("Your Score: " + str(score), True, yellow)
    dis.blit(value, [0, 0])



def our_snake(snake_block, snake_list):
    for x in snake_list:
        pygame.draw.rect(dis, black, [x[0], x[1], snake_block, snake_block])

def nextMove(snake_head):

    x1=snake_head[0]
    y1=snake_head[1]
    next_left=x1-10
    next_right=x1+10
    next_top=y1-10
    next_down=y1+10
    print(next_left,next_right,next_top,next_down)

    if next_left<0:
        x1_change=10
        y1_change=0
        x1+=x1_change
        y1+=y1_change
    if next_right>= dis_width:
        x1_change=-10
        y1_change=0
        x1+=x1_change
        y1+=y1_change
    if next_top<0:
        x1_change=0
        y1_change=10
        x1+=x1_change
        y1+=y1_change
    if next_down>=dis_height:
        x1_change=0
        y1_change=-10
        x1+=x1_change
        y1+=y1_change



def message(msg, color):
    mesg = font_style.render(msg, True, color)
    dis.blit(mesg, [dis_width / 6, dis_height / 3])


def gameLoop():
    game_over = False
    game_close = False

    x1 = dis_width / 2
    y1 = dis_height / 2

    x1_change = 0
    y1_change = 0

    snake_List = []
    Length_of_snake = 1

    foodx = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0
    foody = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0

    while not game_over:

        while game_close == True:
            dis.fill(blue)
            message("You Lost! Press C-Play Again or Q-Quit", red)
            Your_score(Length_of_snake - 1)
            pygame.display.update()

            for event in pygame.event.get():
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_q:
                        game_over = True
                        game_close = False
                    if event.key == pygame.K_c:
                        gameLoop()

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                game_over = True
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    x1_change = -snake_block
                    y1_change = 0
                elif event.key == pygame.K_RIGHT:
                    x1_change = snake_block
                    y1_change = 0
                elif event.key == pygame.K_UP:
                    y1_change = -snake_block
                    x1_change = 0
                elif event.key == pygame.K_DOWN:
                    y1_change = snake_block
                    x1_change = 0




        if x1 >= dis_width or x1 < 0 or y1 >= dis_height or y1 < 0:
            game_close = True
        x1 += x1_change
        y1 += y1_change

        dis.fill(blue)
        pygame.draw.rect(dis, green, [foodx, foody, snake_block, snake_block])
        snake_Head = []
        snake_Head.append(x1)
        snake_Head.append(y1)
        snake_List.append(snake_Head)
        print(snake_Head)
        #print(snake_List)
        if len(snake_List) > Length_of_snake:
            del snake_List[0]

        for x in snake_List[:-1]:
            if x == snake_Head:
                game_close = True


        our_snake(snake_block, snake_List)
        nextMove(snake_Head)
        Your_score(Length_of_snake - 1)
        pygame.display.update()
        #determibe next move



        """    
        #calculating distance
        def Distance():
            x=snake_Head[0]
            y=snake_Head[1]
            dis_wleft=dis_width-x
            dis_wright=x-dis_wleft
            dis_wtop=dis_height-y
            dis_wdown=y-dis_wtop
            dis_food=math.sqrt(((foodx-x)**2)+((foody-y)**2))
            print(dis_wleft,dis_wright,dis_wtop,dis_wdown,dis_food)
        Distance()
        """


        if x1 == foodx and y1 == foody:
            foodx = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0
            foody = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0
            Length_of_snake += 1

        clock.tick(snake_speed)

    pygame.quit()
    quit()


gameLoop()


Tags: eventgameifdefchangewidthblockpygame
1条回答
网友
1楼 · 发布于 2024-05-15 03:47:50

x1_changey1_changenextMove范围内的局部变量。在gameLoop范围内存在同名变量。这是不同的变量,它们只有相同的名称。 当您在nextMove中更改x1_changey1_change时,请不要更改gameLoop中同名的变量

nextMove添加参数并返回x1_changey1_change的更改值:

def nextMove(snake_head, x_ch, y_ch):
    x1_change, y1_change = x_ch, y_ch

    # chang x1_change, y1_change
    # [...]

    return x1_change, y1_change

x1_changey1_change传递到gameLoop中的nextMove并从中获取新值:

def gameLoop():

    # [...]

    while not game_over:

        # [...]

        our_snake(snake_block, snake_List)

        x1_change, y1_change = nextMove(snake_Head, x1_change, y1_change)

        Your_score(Length_of_snake - 1)
        pygame.display.update()

如果蛇的长度增加,当它改变方向到相反方向时,它会击中自己。
我建议将方向改为向左或向右:

def nextMove(snake_head, x_ch, y_ch):

    x1_change, y1_change = x_ch, y_ch
    x1, y1 = snake_head
    next_x, next_y = x1 + x1_change, y1 + y1_change

    if next_x < 0 or next_x >= dis_width:
        x1_change = 0
        y1_change = 10 if y1 < dis_height // 2 else -10
    if next_y < 0 or next_y >= dis_height:
        x1_change = 10 if x1 < dis_width // 2 else -10
        y1_change = 0

    return x1_change, y1_change

相关问题 更多 >

    热门问题