Jul-24-2020, 07:33 PM
(This post was last modified: Jul-24-2020, 07:33 PM by blacklight.)
question: I have a check if the snake.left(x coordinate) == fruit.left, the rand function should be called and the fruit spawns at a different location. It works for the first time their x coordinates are the same, but afterwords it doesn't work anymore. Can anyone help me with this problem?
import pygame import time import random # global variables game = True width, height = 500, 500 x, y = 20, 20 x2, y2 = 240, 250 # setting up screen WIN = pygame.display.set_mode((500,500)) pygame.display.set_caption("Snake by Sam") # load the background BG = pygame.image.load("snake.png") BG_resize = pygame.transform.scale(BG, (width, height)) WIN.blit(BG_resize,(0,0)) # draw square on screen snake = pygame.draw.rect(WIN, (255,0,0), (x,y,20,20)) key = None # draw fruit(circle), setup fruit = pygame.draw.rect(WIN, (255,0,0), (x2,y2,20,20)) def rand(): global x2, y2 x2 = random.randint(0, 490) y2 = random.randint(0, 490) def move(): global key global snake global x global y global fruit if key == "d": x = snake.left time.sleep(0.03) x = x + 10 WIN.blit(BG_resize,(0,0)) snake = pygame.draw.rect(WIN, (255,0,0), (x,y,20,20)) fruit = pygame.draw.rect(WIN, (255,0,0), (x2,y2,20,20)) if key == "s": y = snake.top time.sleep(0.03) y = y + 10 WIN.blit(BG_resize,(0,0)) snake = pygame.draw.rect(WIN, (255,0,0), (x,y,20,20)) fruit = pygame.draw.rect(WIN, (255,0,0), (x2,y2,20,20)) if key == "w": y = snake.top time.sleep(0.03) y = y - 10 WIN.blit(BG_resize,(0,0)) snake = pygame.draw.rect(WIN, (255,0,0), (x,y,20,20)) fruit = pygame.draw.rect(WIN, (255,0,0), (x2,y2,20,20)) if key == "a": x = snake.left time.sleep(0.03) x = x - 10 WIN.blit(BG_resize,(0,0)) snake = pygame.draw.rect(WIN, (255,0,0), (x,y,20,20)) fruit = pygame.draw.rect(WIN, (255,0,0), (x2,y2,20,20)) # mainloop while game: for event in pygame.event.get(): if event.type == pygame.QUIT: game = False if event.type == pygame.KEYDOWN: if event.key == pygame.K_d: WIN.blit(BG_resize,(0,0)) key = "d" if event.key == pygame.K_w: WIN.blit(BG_resize,(0,0)) key = "w" if event.key == pygame.K_s: WIN.blit(BG_resize,(0,0)) key = "s" if event.key == pygame.K_a: WIN.blit(BG_resize,(0,0)) key = "a" move() # border control if snake.left > 490: snake = pygame.draw.rect(WIN, (255,0,0), (250,250,20,20)) x,y = 250, 250 key = None if snake.left == 0: WIN.blit(BG_resize,(0,0)) snake = pygame.draw.rect(WIN, (255,0,0), (250,250,20,20)) x,y = 250, 250 key = None if snake.top > 490: snake = pygame.draw.rect(WIN, (255,0,0), (250,250,20,20)) x,y = 250, 250 key = None if snake.top == 0: WIN.blit(BG_resize,(0,0)) snake = pygame.draw.rect(WIN, (255,0,0), (250,250,20,20)) x,y = 250, 250 key = None # check if the snake has made contact with the fruit. if snake.left == fruit.left: WIN.blit(BG_resize,(0,0)) rand() fruit = pygame.draw.rect(WIN, (255,0,0), (x2,y2,20,20)) pygame.display.update()