返回

python——有没有办法简化这个pygame代码?

发布时间:2022-03-09 21:40:38 428
# node.js

我对pygame有点陌生,我不知道是否有办法简化这个过程,如果你能在画画时改变颜色也会很好。我已经尝试过实现这一点,但我找不到让它工作的方法。它基本上是一款简单的像素艺术游戏:

import pygame
from sys import exit


def MousePos():
    mouse_pos = pygame.mouse.get_pos()
    return mouse_pos[0] // grid_size, mouse_pos[1] // grid_size


def DrawGrid():
    for x in range(0, WIDTH, grid_size):
        for y in range(0, HEIGHT, grid_size):
            rect = pygame.Rect(x, y, grid_size, grid_size)
            pygame.draw.rect(screen, "Black", rect, 1)


def DrawSquare():
    mouse_buttons = pygame.mouse.get_pressed()
    if mouse_buttons[0] and MousePos() not in pressed:
        pressed.append(MousePos())
    if mouse_buttons[1] and MousePos() not in pressed:
        pressed.clear()
    if mouse_buttons[2] and MousePos() in pressed:
        pressed.remove(MousePos())
    for coordinates in pressed:
        rectangle = pygame.Rect(coordinates[0]*grid_size, coordinates[1]*grid_size, grid_size, grid_size)
        pygame.draw.rect(screen, "Black", rectangle)
    cursor = pygame.Rect(MousePos()[0]*grid_size, MousePos()[1]*grid_size, grid_size, grid_size)
    pygame.draw.rect(screen, "Grey", cursor)


pygame.init()
clock = pygame.time.Clock()

WIDTH = 800
HEIGHT = 400
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("PixelArt!")

grid_size = 25
pressed = []
pygame.mouse.set_visible(False)

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            exit()

    screen.fill("White")

    MousePos()
    DrawGrid()
    DrawSquare()

    pygame.display.flip()
    clock.tick(60)
特别声明:以上内容(图片及文字)均为互联网收集或者用户上传发布,本站仅提供信息存储服务!如有侵权或有涉及法律问题请联系我们。
举报
评论区(0)
按点赞数排序
用户头像