This breaks the snake from getting larger but it is more of an illustration of using clock and time....not time delay more than anything else. Notice the FPS is at 60 and you can slow it down just be changing a single number. You can speed up the snake by reducing the
delay
, or slow it down by increasing the delay
import random import pygame pygame.init() screenWidth=500 screenHeight=500 mainWindow=pygame.display.set_mode((screenWidth,screenHeight)) pygame.display.set_caption("Snake") x=250 y=250 snakeSize=50 move="down" length=0 path=[] clock = pygame.time.Clock() run=True def frandxy(): global posx global posy posx=snakeSize*(random.randint(0,screenWidth/snakeSize-1)) posy=snakeSize*(random.randint(0,screenWidth/snakeSize-1)) if (posx,posy) in path or x==posx and y==posy: frandxy() def game(): global run global x global y global move global length global path global clock timer = 0.0 delay = 175 while run: #pygame.time.delay(200) for event in pygame.event.get(): if event.type==pygame.QUIT: closeGame() key=pygame.key.get_pressed() if key[pygame.K_UP] and move != "down": move="up" if key[pygame.K_DOWN] and move != "UP": move="down" if key[pygame.K_RIGHT] and move != "left": move="right" if key[pygame.K_LEFT] and move != "right": move="left" path.insert(0,(x,y)) if pygame.time.get_ticks()-timer > delay: timer = pygame.time.get_ticks() #move snake if move=="down" and y<=screenHeight-snakeSize: y+=snakeSize if move=="down" and y>=screenHeight: y=0 if move=="up" and y>=0: y-=snakeSize if move=="up" and y<0: y=screenHeight-snakeSize if move=="right" and x<=screenWidth-snakeSize: x+=snakeSize if move=="right" and x>=screenWidth: x=0 if move=="left" and x>=0: x-=snakeSize if move=="left" and x<0: x=screenWidth-snakeSize if x==posx and y==posy: length+=1 frandxy() if (x,y) in path: #loseGame() print("You lose. Your length was", length) pygame.quit() break if length>=100: print("You won! The snake filled up the whole screen!") pygame.quit() break mainWindow.fill((0,0,0)) #draw snake if length>0: for i in range(length): pygame.draw.rect(mainWindow, (0,255,0),(path[i][0],path[i][1], snakeSize,snakeSize)) pygame.draw.rect(mainWindow, (0,255,0),(x, y, snakeSize, snakeSize)) #draw food pygame.draw.rect(mainWindow, (255,0,0),(posx,posy, snakeSize, snakeSize)) if len(path)>length: path=path[:(length)] clock.tick(60) pygame.display.update() frandxy() game()I dont have much time today other than that.
Recommended Tutorials: