Python program question snake game, box making using, random fun

Viewed 28

I am new to python. I tried to make a python snake game and I got a problem with making a small rectangle on the screen which should appear on screen every time I run the program. But the rectangle is moving very fast I don't know why. just tell me how to code so that the rectangle stays in one place and changes position every time I run the program

import pygame,sys
from pygame.math import Vector2
import  random
pygame.init()

class fruit:
    def __init__(self):
        self.x=random.randint(0,size_y-1)
        self.y=random.randint(0,size_y-1)
        self.pos=Vector2(self.x,self.y)


    def draw_fruit(self):
        fruit_draw=pygame.Rect(self.pos.x*size_x,self.pos.y*size_x,size_x,size_x)
        pygame.draw.rect(screen,(200,150,160),fruit_draw)

size_x=30
size_y=25
screen=pygame.display.set_mode((size_y*size_x,size_y*size_x))

while True:
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
                quit()
    screen.fill(pygame.Color("dark green"))
    fruit().draw_fruit()
    pygame.display.flip()
1 Answers

You are creating new fruit object every time loop does iteration. You need to initialize it outside that loop. Also class names should be uppercase.

import pygame,sys
from pygame.math import Vector2
import  random
pygame.init()

class Fruit:
    def __init__(self):
        self.x=random.randint(0,size_y-1)
        self.y=random.randint(0,size_y-1)
        self.pos=Vector2(self.x,self.y)


    def draw_fruit(self):
        fruit_draw=pygame.Rect(self.pos.x*size_x,self.pos.y*size_x,size_x,size_x)
        pygame.draw.rect(screen,(200,150,160),fruit_draw)

size_x=30
size_y=25
screen=pygame.display.set_mode((size_y*size_x,size_y*size_x))

fruit = Fruit()  # fruit is now object,
while True:
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
                quit()
    screen.fill(pygame.Color("dark green"))
    fruit.draw_fruit()  # drawing existing object.
    pygame.display.update()
Related