【问题标题】:Snake game in pygame borderspygame边框中的蛇游戏
【发布时间】:2020-08-29 02:11:16
【问题描述】:

所以我对 Python、PyGame 和任何类型的编程都是全新的。我遵循了在 PyGame 中制作蛇游戏的教程。现在它完成了,但为了给自己一个挑战,我正在尝试改变游戏。首先,我想添加边框,但我真的迷路了。我曾尝试观看其他教程,但他们使用的图像似乎有所不同。 这是我的代码(因为我不知道什么能帮助你帮助我,所以我把它全部发送了。):

class cube (object):
    rows = 20
    w = 500
    def __init__(self,start,dirnx=1,dirny=0,color = (255,0,0)):
        self.pos = start
        self.dirnx = 1
        self.dirny = 0
        self.color = color

    def move(self, dirnx, dirny):
        self.dirnx = dirnx
        self.dirny = dirny
        self.pos = (self.pos[0] + self.dirnx, self.pos[1] + self.dirny)

    def draw(self, surface, eyes=False):
        dis = self.w // self.rows
        i = self.pos[0]
        j = self.pos[1]

        pygame.draw.rect(surface, self.color, (i*dis+1,j*dis+1, dis-2, dis-2))
        if eyes:
            centre = dis//2
            radius = 3
            circleMiddle = (i*dis+centre-radius,j*dis+8)
            circleMiddle2 = (i*dis + dis -radius*2,j*dis+8)
            pygame.draw.circle(surface, (0,0,0), circleMiddle, radius)
            pygame.draw.circle(surface, (0,0,0), circleMiddle2, radius)

class snake(object):
    body = []
    turns = {}
    def __init__(self, color, pos):
        self.color = color
        self.head = cube(pos)
        self.body.append(self.head)
        self.dirnx = 0
        self.dirny = 1

    def move(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
        keys = pygame.key.get_pressed()
        for key in keys:
            if keys[pygame.K_LEFT]:
                self.dirnx = -1
                self.dirny = 0
                self.turns[self.head.pos[:]] = [self.dirnx, self.dirny]
            elif keys[pygame.K_RIGHT]:
                self.dirnx = 1
                self.dirny = 0
                self.turns[self.head.pos[:]] = [self.dirnx, self.dirny]
            elif keys[pygame.K_UP]:
                self.dirnx = 0
                self.dirny = -1
                self.turns[self.head.pos[:]] = [self.dirnx, self.dirny]
            elif keys[pygame.K_DOWN]:
                self.dirnx = 0
                self.dirny = 1
                self.turns[self.head.pos[:]] = [self.dirnx, self.dirny]
        for i, c in enumerate(self.body):
            p = c.pos[:]
            if p in self.turns:
                turn = self.turns[p]
                c.move(turn[0], turn[1])
                if i == len(self.body)-1:
                    self.turns.pop(p)
            else:
                if c.dirnx == -1 and c.pos[0] <= 0: c.pos = (c.rows-1, c.pos[1])
                elif c.dirnx == 1 and c.pos[0] >= c.rows-1: c.pos = (0,c.pos[1])
                elif c.dirny == 1 and c.pos[1] >= c.rows-1: c.pos = (c.pos[0], 0)
                elif c.dirny == -1 and c.pos[1] <= 0: c.pos = (c.pos[0],c.rows-1)
                else: c.move(c.dirnx,c.dirny) 

    def reset(self, pos):
        self.head = cube(pos)
        self.body = []
        self.body.append(self.head)
        self.turns = {}
        self.dirnx = 0
        self.dirny = 1

    def addCube(self):
        tail = self.body[-1]
        dx, dy = tail.dirnx, tail.dirny

        if dx == 1 and dy == 0:
            self.body.append(cube((tail.pos[0]-1,tail.pos[1])))
        elif dx == -1 and dy == 0:
            self.body.append(cube((tail.pos[0]+1,tail.pos[1])))
        elif dx == 0 and dy == 1:
            self.body.append(cube((tail.pos[0],tail.pos[1]-1)))
        elif dx == 0 and dy == -1:
            self.body.append(cube((tail.pos[0],tail.pos[1]+1)))

        self.body[-1].dirnx = dx
        self.body[-1].dirny = dy

    def draw(self, surface):
        for i, c in enumerate(self.body):
            if i==0:
                c.draw(surface, True)
            else:
                c.draw(surface)

def drawGrid(w,rows,surface):
    rows_space = w // rows

    x = 0
    y = 0

    for l in range(rows):
        x += rows_space
        y += rows_space
        pygame.draw.line(surface, (255,255,255), (x,0), (x,w))
        pygame.draw.line(surface, (255,255,255), (0,y), (w,y))

def redrawWindow(surface):
    global rows, display_width, s, snack
    surface.fill((0,0,0))
    s.draw(surface)
    snack.draw(surface)
    drawGrid(display_width, rows, surface)
    pygame.display.update()

def randomSnack(rows,items):
    positions = items.body
    while True:
        x = random.randrange(rows)
        y = random.randrange(rows)
        if len(list(filter(lambda z:z.pos == (x,y), positions))) > 0:
            continue
        else:
            break
    return (x,y)

def message_box(subject,content):
    root = tk.Tk()
    root.attributes('-topmost', True)
    root.withdraw()
    messagebox.showinfo(subject, content)
    try:
        root.destroy()
    except:
        pass

def main():
    global rows, display_width, s, snack
    display_width = 500
    rows = 20
    win = pygame.display.set_mode((display_width, display_width))
    s = snake((255,0,0), (10,10))
    snack = cube(randomSnack(rows, s), color=(0,255,0))
    alive = True

    clock = pygame.time.Clock()

    while alive:
        pygame.time.delay(50)
        clock.tick(7)
        s.move()
        if s.body[0].pos == snack.pos:
            s.addCube()
            snack = cube(randomSnack(rows, s), color=(0,255,0))
        for x in range(len(s.body)):
            if s.body[x].pos in list(map(lambda z:z.pos,s.body[x+1:])):
                print('Score: ', len(s.body))
                message_box('You Lost!', 'Play again!')
                s.reset((10,10))
                break

        redrawWindow(win)

main()

基本上,我希望当我的蛇撞到边界时发生与撞到自己时相同的事情。 如果你能帮助我,非常感谢!

【问题讨论】:

    标签: python pygame


    【解决方案1】:

    好吧,让窗口变大,让它变大一个立方体大小

    win = pygame.display.set_mode((display_width + (500//20), display_width + (500//20)))
    

    现在我们有了更多的空间,让我们把所有东西都移过来,这样整个东西周围就有一个均匀的边框

    drawGrid() 中从一个立方体大小上绘制

    pygame.draw.line(surface, (255,255,255), (x,rows_space), (x,w))
    pygame.draw.line(surface, (255,255,255), (rows_space,y), (w,y))
    

    现在如果你想给它上色,你可以在它周围画一个你想要的颜色的矩形

    pygame.draw.rect(surface,(0,0,200),(0,0,w,rows_space)) #top
    pygame.draw.rect(surface,(0,0,200),(0,0,rows_space,w)) #left
    pygame.draw.rect(surface,(0,0,200),(0,w,w + rows_space,rows_space)) #bottom
    pygame.draw.rect(surface,(0,0,200),(w,0,rows_space,w + rows_space)) #right
    

    如果你想挑战,做同样的事情(你可以使用方法),但不是增加窗口,而是减少网格大小以制作边框。

    另外,既然你已经做了蛇,试着用尽可能少的线条来做,我会先看看别人,但这是一件好事。因为我个人认为你对身体的每个立方体都使用了一个类来过度复杂化它。

    要在蛇撞到边缘时结束游戏,请执行与蛇撞到其身体时相同的操作,但是当蛇在边界上时,您有代码检查蛇是否离开屏幕并且把它绕到另一边,所以你可以在那里做

            else:
                #if snake off edge
                if c.dirnx == -1 and c.pos[0] <= 0: c.pos = (c.rows-1, c.pos[1]);
                elif c.dirnx == 1 and c.pos[0] >= c.rows-1: c.pos = (0,c.pos[1])
                elif c.dirny == 1 and c.pos[1] >= c.rows-1: c.pos = (c.pos[0], 0)
                elif c.dirny == -1 and c.pos[1] <= 0: c.pos = (c.pos[0],c.rows-1)
                else: c.move(c.dirnx,c.dirny) 
    

    复制粘贴不好

    但现在我们可以将这段代码从移动蛇变为结束游戏

            outside = False
                if c.pos[0] <= 1: outside = True
                elif c.pos[0] >= c.rows-1: outside = True
                elif c.pos[1] >= c.rows-1: outside = True
                elif c.pos[1] <= 1: outside = True
                else: c.move(c.dirnx,c.dirny) 
                if outside:
                    print('Score: ', len(s.body))
                    message_box('You Lost!', 'Play again!')
                    s.reset((10,10))     
    

    要修复蛇进入边界,将上面的代码更改为&gt;= 1 而不是 0,这部分是我的错,这不是做边界的最佳方法,但它是一个作品,我'我敢肯定,当你再次去制作蛇时,你会做得更好

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多