call a custom event pygame code example
Example: what is pygame userevent
import pygame
from pygame import display, font, time, mouse, draw
from pygame.math import Vector2
import random
import sys
class Snake:
def __init__(self):
self.body = [Vector2(5, 10), Vector2(6, 10), Vector2(7, 10)]
self.direction = Vector2(1, 0)
def draw_snake(self):
for block in self.body:
x_pos = int(block.x * cSize)
y_pos = int(block.y * cSize)
block_rect = pygame.Rect(x_pos, y_pos, cSize, cSize)
draw.rect(screen, (183, 111, 122), block_rect)
def move_snake(self):
body_copy = self.body[:-1]
body_copy.insert(0, body_copy[0] + self.direction)
self.body = body_copy[:]
class Fruit:
def __init__(self):
self.x = random.randint(0, cNumber - 1)
self.y = random.randint(0, cNumber - 1)
self.pos = Vector2(self.x, self.y)
def draw_fruit(self):
fruit_rect = pygame.Rect(int(self.pos.x * cSize), int(self.pos.y * cSize), cSize, cSize)
draw.rect(screen, (255, 75, 30), fruit_rect)
pygame.init()
clock = time.Clock()
WIDTH = 800
HEIGHT = 600
FPS = 60
cSize = 36
cNumber = 18
screen = display.set_mode((cNumber * cSize, cNumber * cSize))
display.set_caption('Snake Game in pyGame')
fruit = Fruit()
snake = Snake()
SCREEN_UPDATE = pygame.USEREVENT
time.set_timer(SCREEN_UPDATE, 150)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.MOUSEBUTTONDOWN:
pos = mouse.get_pos()
print(pos)
if event.type == SCREEN_UPDATE:
snake.move_snake
screen.fill((200, 230, 100))
fruit.draw_fruit()
snake.draw_snake()
display.update()
clock.tick(FPS)