[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

Re: [pygame] Odd behaviour of sprites in a list - newbie help please?



Not a direct answer to your question, but I would factor out portions of your code into separate functions. There's one school of thought in the programming world that says functions or methods shouldn't be more than 10 lines of code. People can agree or disagree, but regardless it helps to debug a problem like this when the code is organized into named functions.
 
S for example, a common convention is to have a gameloop() function which would contain your root while: statement. Then within the gameloop, you could have a handle_keys() function which handles keys, a process_input, and an update_snake() to handle the graphics. You've probably seen the basic 'game loop' flow yes? Input -> process -> output -> wait ? ? 

For me, when I'm crunching through a difficult problem it often helps to do a cleanup refactor and shake loose my thinking.

Good luck :)

On Mon, Jun 24, 2019 at 8:19 AM Adam Coombes <mac.badmoose@xxxxxxxxx> wrote:
I've created a list of sprites to try and make a basic 'snake' game. The idea is to shuffle each sprite to the position of the next, starting at the end of the tail, and then move the head. As I append new tail pieces, they should 'snake' along. However, when I move the head sprite ( Snake[0] in my list 'Snake'), they all seem to move to the same position. Even when I omit the line that moves them along by commenting out 'Snake[tail] = Snake[tail-1]' in my for loop, it still moves every sprite in the list Snake[] to the same place as Snake[0], which is inexplicable to me as I'm not even moving them then. Can anyone point out my mistake please? This is just a learner project, but it's driving me nuts.

import pygame, sys
from pygame.locals import*
import random
#colours========================================================
BLACK = (0,0,0)
WHITE = (255,255,255)
RED = (255,0,0)
GREEN = (0,255,0)
BLUE = (0,0,255)
PURPLE = (128,0,128)
GREY = (128,128,128)
YELLOW = (255,255,0)
pygame.init()
Height = 1920
Width = 1080
score = 0
basicfont = pygame.font.SysFont(None, 50)
Score = basicfont.render("Score: " + str(score), True, WHITE, GREEN)
ScoreRect = Score.get_rect()
ScoreRect.left =560
ScoreRect.bottom = 130
moveLeft = False
moveRight = False
moveUp = False
moveDown = False
PlayerSpeed = 40
def GameBoard():
    pygame.display.set_caption("Snake_Game")
    Window.fill(GREEN)
    pygame.draw.line(Window, BLACK,(560,140),(1360,140),4)
    pygame.draw.line(Window, BLACK,(560,140),(560,940),4)
    pygame.draw.line(Window, BLACK,(1360,140),(1360,940),4)
    pygame.draw.line(Window, BLACK,(560,940),(1360,940),4)
#GAME===========================================================
mainClock = pygame.time.Clock()
Window = pygame.display.set_mode((Height,Width), 0, 32)
#PLayer=========================================================                    
Snake =[]
Snake.append (pygame.Rect(940,500,40,40))
playerImage = pygame.image.load("Snake.GIF")
Window.blit(playerImage,Snake[0])
#Apple==========================================================
def PlotApple():
    global AppleX
    global AppleY
    global Apple
    AppleX = random.randint(560,1320)
    AppleY = random.randint(140,900)
    Apple = pygame.Rect(AppleX,AppleY,40,40)
PlotApple()
AppleImage = pygame.image.load("Apple.GIF") 
Window.blit(AppleImage,Apple)
pygame.display.update()
#================================================================
while True:
    for event in pygame.event.get():
        if event.type == KEYDOWN:
            if event.key == K_ESCAPE:
                pygame.quit()
        #===================================================
        if event.type == KEYDOWN:
            #===============================================
            if event.key == K_LEFT:
                moveRight = False
                moveLeft = True
                moveDown = False
                moveUp = False
            #===============================================
            if event.key == K_RIGHT:
                moveLeft = False
                moveRight = True
                moveDown = False
                moveUp = False
            #===============================================
            if event.key == K_UP:
                moveDown = False
                moveUp = True
                moveLeft = False
                moveRight = False
            #===============================================
            if event.key ==K_DOWN:
                moveUp = False
                moveDown = True
                moveLeft = False
                moveRight = False
            #KEYUP===============================================
            if event.type == KEYUP:
            #===================================================
                if event.key == K_ESCAPE:
                    pygame.quit()
                    sys.exit()
    #MovePlayer===================================================
    mainClock.tick(10)
    GameBoard()
    for tail in range (len(Snake)-1,0,-1):
        print(Snake,tail)
        Snake[tail] = Snake[tail-1]
        Window.blit(playerImage,Snake[tail])
        print(Snake,tail)
    if moveDown:
        Snake[0].top += PlayerSpeed
    if moveUp:
        Snake[0].top -= PlayerSpeed
    if moveLeft:
        Snake[0].left -= PlayerSpeed
    if moveRight:
        Snake[0].right += PlayerSpeed
    if Snake[0].bottom >=940 or Snake[0].top<+140 or Snake[0].left<=560 or Snake[0].right>=1360:
        pygame.quit()
    Score = basicfont.render("Score:" + str(score), True, WHITE, GREEN)
    Window.blit(playerImage,Snake[0])
    Window.blit(AppleImage,Apple)
    Window.blit(Score,ScoreRect)
    if Snake[0].colliderect(Apple):
        score = score +50
        Snake.append (Snake[0])
        PlotApple()
    pygame.display.update()


--
A musician must make music, an artist must paint, a poet must write, if he is to be ultimately at peace with himself.
- Abraham Maslow