Created
October 26, 2015 15:43
-
-
Save hallazzang/df3fde293e875892be02 to your computer and use it in GitHub Desktop.
Pygame line drawing example using Bresenham Algorithm
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import pygame | |
from pygame.locals import * | |
WIDTH, HEIGHT = 100, 100 | |
PIXEL_SIZE = 5 # should be bigger than 1 | |
SCREEN_WIDTH, SCREEN_HEIGHT = WIDTH * PIXEL_SIZE, HEIGHT * PIXEL_SIZE | |
surf = pygame.Surface((SCREEN_WIDTH, SCREEN_HEIGHT)) | |
surf.fill((0, 0, 0)) | |
def put_pixel(x, y): | |
global surf | |
pygame.draw.rect(surf, (255, 0, 0), | |
(x * PIXEL_SIZE, y * PIXEL_SIZE, PIXEL_SIZE, PIXEL_SIZE)) | |
def put_line(x0, y0, x1, y1): | |
# referenced from http://www.poshy.net/java/graphic/linedraw4.htm | |
dx = x1 - x0 | |
dy = y1 - y0 | |
if dy < 0: | |
dy = -dy | |
stepy = -1 | |
else: | |
stepy = 1 | |
if dx < 0: | |
dx = -dx | |
stepx = -1 | |
else: | |
stepx = 1 | |
dx <<= 2 | |
dy <<= 2 | |
put_pixel(x0, y0) | |
if dx > dy: | |
fraction = dy - (dx >> 1) | |
while x0 != x1: | |
if fraction >= 0: | |
y0 += stepy | |
fraction -= dx | |
x0 += stepx | |
fraction += dy | |
put_pixel(x0, y0) | |
else: | |
fraction = dx - (dy >> 1) | |
while y0 != y1: | |
if fraction >= 0: | |
x0 += stepx | |
fraction -= dy | |
y0 += stepy | |
fraction += dx | |
put_pixel(x0, y0) | |
pygame.init() | |
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) | |
pygame.display.set_caption('Line Drawing') | |
clock = pygame.time.Clock() | |
running = True | |
while running: | |
for event in pygame.event.get(): | |
if event.type == QUIT: | |
running = False | |
elif event.type == KEYDOWN: | |
if event.key == K_ESCAPE: | |
running = False | |
elif pygame.mouse.get_pressed()[0] and event.type == MOUSEMOTION: | |
x, y = event.pos[0] / PIXEL_SIZE, event.pos[1] / PIXEL_SIZE | |
rel_x, rel_y = (int(event.rel[0] / float(PIXEL_SIZE)), | |
int(event.rel[1] / float(PIXEL_SIZE))) | |
put_line(x - rel_x, y - rel_y, x, y) | |
if running: | |
clock.tick(60) | |
screen.blit(surf, (0, 0)) | |
pygame.display.update() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment