简体   繁体   中英

Why does my sprite move at a constant speed

I am writing a game that involves similar mechanics to snake but the difference is the player should grow as they move and not when they reach the apple. My problem is that when the game starts, because of the snake code i was using as a reference, the player grows from behind to the edge of the screen when i would like it to only grow from the starting point. My thinking is that it should check if there is a block in the starting space and if there is it should pass and if not add a cube.

this is the code for add cube:

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

    # check what direction we are currently moving in to determine if we need to add the cube to the left, right, above or below.
    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

This is a loop inside the main function that calls the add cube function

flag = True
    # STARTING MAIN LOOP
    loop = 0
    while flag:
        #pygame.time.delay(10)  # This will delay the game so it doesn't run too quickly
        clock.tick(60)  # Will ensure our game runs at 10 FPS
        s.move()
        if loop >= 1:
            s.addCube()
        loop += 1

        for x in range(len(s.body)):
            if s.body[x].pos in list(map(lambda z: z.pos, s.body[
                                                          x + 1:])):  # This will check if any of the positions in our body list overlap
                print('Score: ', len(s.body))
                s.reset((10, 10))
                break

If you want the player to grow from the starting point, change

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)))

to just

self.body.append(cube((tail.pos[0], tail.pos[1])))

so it grows on top of the tail so when the rest of the tail moves, it stays there then moves, just like in snake

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM