如何为蛇游戏生成食物

时间:2016-06-26 18:27:26

标签: python-3.x pygame

我无法弄清楚如何为蛇吃食物。我知道蛇在第97和98行的位置,我已经创建了一个类来生成一个像素,我想在第22行绘制一份食物(编辑:应该是一个函数,注释#def(?)in代码)。我所要做的就是在随机分配的位置的x和y坐标处添加15个像素并打印它以获得块。

问题是要检查我是否吃了它。它应该是这样的:

if x >= x_food && x <= x_food + 15 || y >= y_food && y <= y_food + 15:
    ...add a point and make snake longer...

问题是由于某种原因将它们放在一起..有人可以给我一个提示或解决我应该如何编写这个类以便我可以继续处理其他问题吗?谢谢!

import pygame
import random

#Global variables
#Color
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)

#Start length of snake
snake_length = 3

#Set the width of the segments of the snake
segment_width = 15
segment_height = 15
# Margin within each segment
segment_margin = 3

#Set initial speed
x_change = segment_width + segment_margin
y_change = 0

#def (?)
class Food():
    #Class to print food
    x_food = random.randint(0, 785)
    y_food = random.randint(0, 585)


class Segment(pygame.sprite.Sprite):
    """ Class to represent the segment of the snake. """
    # Methods
    # Constructer function
    def __init__(self, x, y):
        #Call the parents constructor
        super().__init__()

        #Set height, width
        self.image = pygame.Surface([segment_width, segment_height])
        self.image.fill(WHITE)

        #Make our top-left corner the passed-in location.
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y

#Call this function so the Pygame library can initialize itself
pygame.init()

#Create an 800x600 size screen
screen = pygame.display.set_mode([800, 600])

#Set the title of the window
pygame.display.set_caption("Snake")

allspriteslist = pygame.sprite.Group()

#Create an initial snake
snake_segments = []
for i in range(snake_length):
    x = 250 - (segment_width + segment_margin) * i
    y = 30
    segment = Segment(x, y)
    snake_segments.append(segment)
    allspriteslist.add(segment)

clock = pygame.time.Clock()
done = False

while not done:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True

        #Set the speed based on the key pressed
        #We want the speed to be enough that we move a full
        #Segment, plus the margin
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                x_change = (segment_width + segment_margin) * -1
                y_change = 0
            if event.key == pygame.K_RIGHT:
                x_change = (segment_width + segment_margin)
                y_change = 0
            if event.key == pygame.K_UP:
                x_change = 0
                y_change = (segment_height + segment_margin) * -1
            if event.key == pygame.K_DOWN:
                x_change = 0
                y_change = (segment_width + segment_margin)

    #Get rid of last segment of the snake
    #.pop() command removes last item in list
    old_segment = snake_segments.pop()
    allspriteslist.remove(old_segment)

    #Figure out where new segment will be
    x = snake_segments[0].rect.x + x_change
    y = snake_segments[0].rect.y + y_change
    segment = Segment(x, y)

    #Insert new segment to the list
    snake_segments.insert(0, segment)
    allspriteslist.add(segment)

    #Draw
    #Clear screen
    screen.fill(BLACK)

    allspriteslist.draw(screen)

    #Flip screen
    pygame.display.flip()

    #Pause
    clock.tick(5)

pygame.quit()

4 个答案:

答案 0 :(得分:1)

如何使用:

if snake_headx == foodx and snake_heady == foody:

    food_eated()
    snake_grow()

只是建议

没有阅读所有你的代码,只是认为你可能会觉得它很有用。

我已经找到了一个解决方案,所以基本上你想要的是一个正方形,当蛇接近那个正方形时会发生什么事情?我有一个赛车游戏,当你撞到一辆方形车时会让你崩溃,所以il只需复制代码:

if y < thing_starty+thing_height:
        if x > thing_startx and x < thing_startx+thing_width or     x+car_width > thing_startx and x+car_width<thing_startx+thing_width:
            snake_eated()
            snake_grow()

这会监控你的汽车(或蛇)的x和y,并检查什么东西(或食物)'sy小于你的汽车,然后检查x和其他很多东西,基本上它创造了一个大的在你的广场周围你不能穿越你的情况,你只需要添加剩下的,这会有效吗?

答案 1 :(得分:1)

if x >= x_food && x <= x_food + 15 || y >= y_food && y <= y_food + 15:

为什么你OR这些条件对?难道不是所有的4个测试都必须同时成立吗?

if x >= x_food && x <= x_food + 15 && y >= y_food && y <= y_food + 15:

答案 2 :(得分:1)

我拿了你的代码,我觉得我工作了一些东西,请注意,这只会监视当蛇越过块时,然后打印:美味,所以你必须添加细节,还要注意我不使用你的班级要产生食物:

import pygame
import random

#Global variables
#Color
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)

#Start length of snake
snake_length = 3

#Set the width of the segments of the snake
segment_width = 15
segment_height = 15
# Margin within each segment
segment_margin = 3

#Set initial speed
x_change = segment_width + segment_margin
y_change = 0

#def (?)
class Food():
    #Class to print food
    x_food = random.randint(0, 785)
    y_food = random.randint(0, 585)


class Segment(pygame.sprite.Sprite):
    """ Class to represent the segment of the snake. """
    # Methods
    # Constructer function
    def __init__(self, x, y):
        #Call the parents constructor
        super().__init__()

        #Set height, width
        self.image = pygame.Surface([segment_width, segment_height])
        self.image.fill(WHITE)

        #Make our top-left corner the passed-in location.
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y

#Call this function so the Pygame library can initialize itself
pygame.init()

#Create an 800x600 size screen
screen = pygame.display.set_mode([800, 600])

#Set the title of the window
pygame.display.set_caption("Snake")

allspriteslist = pygame.sprite.Group()

#Create an initial snake
snake_segments = []
for i in range(snake_length):
    x = 250 - (segment_width + segment_margin) * i
    y = 30
    segment = Segment(x, y)
    snake_segments.append(segment)
    allspriteslist.add(segment)

clock = pygame.time.Clock()
done = False
x_food = random.randint(0, 785)
y_food = random.randint(0, 585)

while not done:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True

        #Set the speed based on the key pressed
        #We want the speed to be enough that we move a full
        #Segment, plus the margin
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                x_change = (segment_width + segment_margin) * -1
                y_change = 0
            if event.key == pygame.K_RIGHT:
                x_change = (segment_width + segment_margin)
                y_change = 0
            if event.key == pygame.K_UP:
                x_change = 0
                y_change = (segment_height + segment_margin) * -1
            if event.key == pygame.K_DOWN:
                x_change = 0
                y_change = (segment_width + segment_margin)

            if y < y_food+30:
                if x > x_food and x < x_food+30 or x+20 > x_food and x+20<x_food+30:
                    print('yummy')



    #Get rid of last segment of the snake
    #.pop() command removes last item in list
    old_segment = snake_segments.pop()
    allspriteslist.remove(old_segment)

    #Figure out where new segment will be
    x = snake_segments[0].rect.x + x_change
    y = snake_segments[0].rect.y + y_change
    segment = Segment(x, y)

    #Insert new segment to the list
    snake_segments.insert(0, segment)
    allspriteslist.add(segment)

    #Draw
    #Clear screen
    screen.fill(BLACK)
    pygame.draw.rect(screen, WHITE, [x_food, y_food, 30, 30])

    allspriteslist.draw(screen)

    #Flip screen
    pygame.display.flip()

    #Pause
    clock.tick(5)

pygame.quit()

希望这有帮助,谢谢!

答案 3 :(得分:1)

使用简单的填充矩形作为图像,使您的食物变成精灵,然后使用精灵碰撞pygame.sprite.spritecollide()检查您的蛇是否与食物碰撞。 Pygame会处理两个矩形是否重叠的实际逻辑。

另外,由于你已经在使用sprite组,我建议你为你的蛇段编写一个更新函数,它会移动它们而不是每回合创建一个新的段。然后你可以简单地在主游戏循环中调用allspriteslist.update(),这将为每个蛇段调用更新函数。

最后,您可能想要查看pygame网站上的众多snake examples