Skip to main content
 首页 » 编程设计

python之用 Pygame 画抛物线

2025年05月04日10telwanggs

我想在pygame中画一条抛物线。我制作了一个 pixelarray 对象并循环遍历它以确定像素是否在抛物线上。我似乎得到了一个点之间有间隙的图像。如何使它成为一条连续的线?

import pygame 
import sys 
from pygame.locals import * 
import math 
 
WIDTH = 640 
HEIGHT = 480 
 
pygame.init() 
screen = pygame.display.set_mode((WIDTH, HEIGHT), 0, 32) 
 
pxarray = pygame.PixelArray(screen) 
 
while True: 
    for event in pygame.event.get(): 
        if event.type == QUIT: 
            pygame.quit() 
            sys.exit() 
 
    screen.fill((0,0,0)) 
 
    for y, py in enumerate(pxarray): 
        for x, px in enumerate(py): 
            if int(x) == (int(y)*int(y)) - 30*int(y) + 450: 
                pxarray[y][x] = 0xFFFFFF 
 
    pygame.display.update() 

请您参考如下方法:

color = 255, 0, 0 
first = True 
prev_x, prev_y = 0, 0 
while True: 
    for event in pygame.event.get(): 
        if event.type == QUIT: 
            pygame.quit() 
            sys.exit() 
 
    screen.fill((0,0,0)) 
 
    for y, py in enumerate(pxarray): 
        for x, px in enumerate(py): 
            if int(x) == (int(y)*int(y)) - 30*int(y) + 450: 
                pxarray[y][x] = 0xFFFFFF 
 
                if first: 
                    first = False 
                    prev_x, prev_y = x, y 
                    continue 
 
                pygame.draw.line(screen, color, (prev_y, prev_x), (y, x)) 
                prev_x, prev_y = x, y 
 
    first = True 
    pygame.display.flip()