I am a bit new to pygame, and I made this simple pixel art game. Is it possible to simplify, and is it possible to save your drawings and load them back again?
import pygame
from sys import exit
def ConvertPos(pos):
x, y = pos
return x//SQUARE_SIZE, y//SQUARE_SIZE
def DrawGrid():
for x in range(0, WIDTH, SQUARE_SIZE):
for y in range(0, HEIGHT, SQUARE_SIZE):
rect = pygame.Rect(x, y, SQUARE_SIZE, SQUARE_SIZE)
pygame.draw.rect(screen, "Black", rect, 1)
def SelectColor():
global draw_color
mouse_pressed = pygame.mouse.get_pressed()
bg = pygame.Rect(WIDTH, 0, SIDE, HEIGHT)
pygame.draw.rect(screen, "Orange", bg)
pygame.draw.rect(screen, "Purple", bg, 5)
for item, color in enumerate(colors):
select_color = pygame.Rect(0, 0, 120, 30)
select_color.center = WIDTH+SIDE//2, HEIGHT*(item+1)/len(colors)-(HEIGHT/len(colors))/2
pygame.draw.rect(screen, color, select_color)
if select_color.collidepoint(pygame.mouse.get_pos()) and mouse_pressed[0]:
draw_color = color
if draw_color == color:
pygame.draw.rect(screen, "DarkBlue", select_color, 5)
def DrawSquare():
global draw_color
mouse_pos = pygame.mouse.get_pos()
mouse_pressed = pygame.mouse.get_pressed()
grid_x, grid_y = grid_pos = ConvertPos(mouse_pos)
cursor = (grid_x*SQUARE_SIZE, grid_y*SQUARE_SIZE, SQUARE_SIZE, SQUARE_SIZE)
for (x, y), color in pressed.items():
square = pygame.Rect(x*SQUARE_SIZE, y*SQUARE_SIZE, SQUARE_SIZE, SQUARE_SIZE)
pygame.draw.rect(screen, color, square)
if 0 < mouse_pos[0] < WIDTH-1 and 0 < mouse_pos[1] < HEIGHT-1:
pygame.draw.rect(screen, draw_color, cursor, 3)
if mouse_pressed[0]:
pressed[grid_pos] = draw_color
if mouse_pressed[2] and grid_pos in pressed:
pressed.pop(grid_pos)
if mouse_pressed[1]:
pressed.clear()
pygame.init()
clock = pygame.time.Clock()
WIDTH = 800
SIDE = 200
HEIGHT = 400
MARGIN = 50
SQUARE_SIZE = 25
screen = pygame.display.set_mode((WIDTH+SIDE, HEIGHT))
pygame.display.set_caption("PXLART")
pressed = {}
colors = ["Black", "Blue", "Green", "Red", "Pink", "Yellow", "White", "DarkGreen", "Brown", "Grey", "Cyan"]
draw_color = "Black"
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
screen.fill("White")
DrawGrid()
SelectColor()
DrawSquare()
pygame.display.update()
clock.tick(60)