I have been trying to figure out how to create a rect that is constantly moving in Pygame, using the game loop.
I've tried doing something that works in Godot, similar to a __process function__ in the main game-loop, but it doesn't seem to work the same way in python.
Here is some code i put together, using a snake game as an example:
import pygame as py
from pygame import Vector2
import sys
py.init()
clock = py.time.Clock()
#COLOURS
WHITE = (255, 255, 255)
GREEN = (50, 250, 60)
RED = (255, 0, 50)
BLACK = (0, 0, 0)
#GRID
square_size = 50
square_amount = 10
grid_square_one_side = square_size * square_amount
grid_square = grid_square_one_side, grid_square_one_side
#SNAKE
speed = 1
snake_pos = Vector2(5, 5)
#Class
class Snake:
def __init__(self): #you only put all variables in the brackets if there is more than one of the objects in this class
pass
def draw(self):
self.position: Vector2 = Vector2(snake_pos.x*square_size, snake_pos.y*square_size)
#x axis on grid #y axis on grid
self.size : list = 50, 50
#
py.Rect(self.position, (self.size))
py.draw.rect(window, GREEN, (self.position, self.size))
#create a variable for the snake
snake = Snake
#create a direction variable
global current_dir
current_dir = Vector2(0, 0)
#create an instance for the class
MySnake = Snake()
#SCREEN
window = py.display.set_mode((grid_square))
#LOOP
running = True
while running:
for event in py.event.get():
if event.type == py.QUIT:
running = False
#INPUT
if event.type == py.KEYDOWN:
if event.key == py.K_RIGHT:
current_dir.x = 1
if event.key == py.K_LEFT:
current_dir.x = -1
if event.key == py.K_UP:
current_dir.y = -1
if event.key == py.K_DOWN:
current_dir.y = 1
#draw the snake
counter = 0
counter += 1
snake_pos.x += current_dir.x
snake_pos.y += current_dir.y
if current_dir.x > 2:
current_dir.x = 1
elif current_dir.x < -2:
current_dir.x = -1
if current_dir.y == 1 or -1:
current_dir.x = 0
if current_dir.x == 1 or -1:
current_dir.y = 0
if current_dir.y > 2:
current_dir.y = 1
elif current_dir.y < -2:
current_dir.y = -1
MySnake.draw()
py.display.update()
window.fill(BLACK)
#Frame-rate
clock.tick(120)
print(current_dir)
py.quit()
sys.exit()
This code creates a block that moves around the screen - but not continuously as I had hoped.
Do loops act similarly to processes in Godot?
Please could someone explain my errors and explain how loops work?
Help would be much appreciated.