Introduction

One day, you were showing your kid how to draw on a computer. You type mspaint.exe in the run bar. To your horror, it says "No items match your search". You must create a simple version of paint so your kid can draw!

Challenge

You must create a simple drawing program. To do this, open a white display window (larger than 99x99 pixels). Anytime the mouse is pressed down, change the pixel that the mouse is on to black.

This is , so shortest answer in bytes wins!

  • 8
    Does it need to be pixels? or can it be 99x99 squares? – fəˈnɛtɪk Apr 20 '17 at 21:24
  • 2
    How long does it need to run for? – Picard Apr 20 '17 at 21:34
  • 2
    When TI-Basic's Pen does exactly this :o – Timtech Apr 20 '17 at 22:56
  • 1
    @Riker it should run for at least 10 seconds, preferably forever – pydude Apr 21 '17 at 20:24
  • 1
    Is larger than 99×99 just so we have to use three digits in decimal notation for each dimension? Would 99×100 or 100×99 be valid? – Xufox Apr 22 '17 at 21:03

25 Answers 25

up vote 87 down vote accepted

8086 machine code, 32 31 28 26 bytes

00000000  b8 0f 00 cd 10 b8 02 10  ba 18 01 cd 10 b8 03 00  |................|
00000010  cd 33 4b b8 01 0c eb f3  3f 00                    |.3K.....?.|
0000001a

Assumes the presence of a VGA graphics card, and any Microsoft-compatible mouse driver.

-2 bytes thanks to @berendi!

screenshot

How it works:

            |   org 0x100
            |   use16
b8 0f 00    |       mov ax, 0x000f      ; set screen mode: 640x350 monochrome
cd 10       |       int 0x10            ; call video bios
b8 02 10    |       mov ax, 0x1002      ; set palette
ba 18 01    |       mov dx, palette     ; pointer to palette data
cd 10       |   @@: int 0x10            ; call video bios
b8 03 00    |       mov ax, 0x0003      ; get mouse position in (CX, DX) and button status in BL
cd 33       |       int 0x33            ; call mouse driver
4b          |       dec bx              ; if no buttons pressed, --BX = 0xFFFF (invalid page)
b8 01 0c    |       mov ax, 0x0c01      ; plot pixel with color AL at (CX, DX) in page BH
eb f3       |       jmp @b              ; repeat
3f 00       |   palette db 0x3f, 0x00   ; palette in 2:2:2 rgb. color 0 = white, 1 = black.
            |                           ; this should be a 17-byte struct, but we only care about the first two colors here

That's all there is to it. No magic involved, just a few function calls.

  • 1
    Clean, clear, and clever code. Very nicely done! I don't see anywhere this can be further optimized for size. For some reason, when I tried this using the CuteMouse driver, this draws without the mouse button having to be held down, but that may just be an issue with CuteMouse not being 100% Microsoft-compatible. Which driver did you use for testing? – Cody Gray Apr 22 '17 at 6:26
  • 2
    Hmm. After running the code with a debugger (good old DEBUG.COM, of course!), it appears it's not a problem with the CuteMouse driver. Without a button held down, INT 33h is returning 0 in BX, and this gets decremented to FFFFh as expected, but a line is still being drawn. Perhaps this is because mode 11h only has one video page, and the invalid page number is automatically being fixed up? I'm testing on VM VirtualBox, so maybe that's something its BIOS implementation is doing. – Cody Gray Apr 22 '17 at 6:37
  • 2
    Looks like VirtualBox is to blame here, it simply ignores the page number altogether: virtualbox.org/browser/vbox/trunk/src/VBox/Devices/Graphics/… – user5434231 Apr 22 '17 at 17:27
  • 2
    Bill Atkinson himself would be proud of this. Splendid work. – Wossname Apr 23 '17 at 21:35
  • 4
    -2 bytes remove the last int 0x10, jmp back to the second int 0x10 instead. Offset in jmp remains the same, adjust address in mov dx – berendi Apr 24 '17 at 8:47

Scratch, 10 Scratch bytes

Scratch was practically designed for things like this.

Try it online!

  • Does this actually do pixels? Also, if you click the mouse fast vs holding it for a bit, it produces different results (without moving it of course). I think that invalidates this. – Picard Apr 21 '17 at 0:46
  • 19
    This is not 10 Scratch bytes, according to the scoring we currently use. – Okx Apr 21 '17 at 9:53
  • 2
    You should probably use the scratchblocks app to convert to text, or the SB2 file size. – lol Apr 21 '17 at 14:30
  • 2
    I'm using the scoring that I used with earlier Scratch answers. Can someone please link me to the current scoring? @Okx – Mendeleev Apr 21 '17 at 15:19
  • 8
    @Mendeleev I'm not certain, but he's probably referring to this Scratch scoring system. – FreeAsInBeer Apr 21 '17 at 15:34

HTML + JavaScript (ES6), 66 64 62 bytes

HTML

<canvas id=c>

JavaScript

onclick=e=>c.getContext`2d`.fillRect(e.x,e.y,1,1)

Saved 2 bytes thanks to Gustavo Rodrigues and 2 bytes from Shaggy.

onclick=e=>c.getContext`2d`.fillRect(e.x,e.y,1,1)
/* This css isn't needed for the program to work. */
*{margin: 0}
#c{border:1px solid black}
<canvas id=c>

  • How about <canvas id=c>? – Gustavo Rodrigues Apr 21 '17 at 18:36
  • 2
    This actually puts the dot not where my cursor goes, but to the bottom right of the arrow. Is this intentional? – Anoplexian Apr 21 '17 at 20:33
  • Save 2 bytes by dropping the c. from the start of your JS. @Anoplexian, that's the default body margin throwing things off by a few pixels. – Shaggy Apr 21 '17 at 23:15
  • 4
    How do I make this work? I'm clicking in the result area and it's not doing anything. – numbermaniac Apr 22 '17 at 1:48
  • 1
    @Anoplexian That's a known issue; there's no reliable way to get the relative position of the mouse cursor on an element (short of large, browser-specific functions that fail when a new type of CSS padding is introduced). – wizzwizz4 Apr 23 '17 at 8:06

C + Win32, 209 200 195 bytes

Thanks, Cody and Quentin! I was hoping to get rid of the #include <windows.h> but this leads to all sort of errors. At least it is working correctly with multiple monitors...

#include<windows.h> 
struct{int h,m,w,x:16,y:16;}m;h;main(){for(h=CreateWindow("EDIT","",1<<28,0,0,199,199,0,0,0,0);GetMessage(&m,h,0,0);m.m^513?DispatchMessage(&m):SetPixel(GetDC(h),m.x,m.y,0));}

Previous code:

#include<windows.h> 
main(){MSG m;HWND h;for(h=CreateWindow("EDIT","",1<<28,0,0,199,199,0,0,0,0);GetMessage(&m,h,0,0);m.message^513?DispatchMessage(&m):SetPixel(GetDC(h),LOWORD(m.lParam),HIWORD(m.lParam),0));}

enter image description here

  • 2
    I can't test right now, bu I think you can merge the declaration of h into the for initializer to save two bytes :) – Quentin Apr 21 '17 at 16:00
  • I realize this is code golf and it may be desirable here, but LOWORD and HIWORD are not the correct way to extract cursor coordinates from a packed LPARAM. You should be using GET_X_LPARAM and GET_Y_LPARAM, otherwise you will get wrong results with multiple monitors. – Cody Gray Apr 22 '17 at 6:07
  • @Quentin, that will work in c++ but not in c. I could have used c++ but then I would have written int main which would have added 4 more bytes. – Johan du Toit Apr 22 '17 at 6:48
  • @Cody, Fair comment. I don't have a multi monitor system to test but do you think using (short)LOWORD() and (short)HIWORD() would solve the issue? – Johan du Toit Apr 22 '17 at 6:49
  • What Quentin suggested works fine in any modern version of C, including C99. Of course, you are using Microsoft's C compiler, which is stuck back in C89/90, with its demented variable scoping rules. C89 is also why you're allowed to omit the main function's return type (because of the implicit-int rule). Only problem is, omitting the return 0; causes undefined behavior in C89 and MSVC. In C99 and C++, you need a return type for main, but the return 0; is implicit and thus unnecessary. Well, the language wasn't made for code golfing. :-) – Cody Gray Apr 22 '17 at 8:43

Processing, 98 79 bytes

19 bytes saved thanks to @dzaima

void setup(){background(-1);}void draw(){if(mousePressed)point(mouseX,mouseY);}

Explanation (outdated)

void setup() {
  size(100,100);            // size of the sketch
  background(-1);           // set the background to white
                            // 1 byte shorter than background(255);
}

void draw(){}               // required for mousePressed to work

void mousePressed() {       // function that is called whenever the mouse is pressed
  point(mouseX, mouseY);    // draw a point at the mouse's coordinates
                            // the colour is set to black as default
}

clicketty click

  • @dzaima I did not know the size(100,100); does not have to be mentioned, thanks! (also I don't know why I did not see the if(mousePressed) bit) – Cows quack Apr 22 '17 at 11:02

JavaScript ES6, 126 bytes

Tested in chrome.

onclick=e=>document.body.outerHTML+=`<a style=position:fixed;top:${e.y}px;left:${e.x}px;width:1px;height:1px;background:#000>`

Try it online!

onclick=e=>document.body.outerHTML+=`<a style=position:fixed;top:${e.y}px;left:${e.x}px;width:1px;height:1px;background:#000>`

Haskell, 189 184 170 169 bytes

import Graphics.Gloss.Interface.Pure.Game
main=play FullScreen white 9[]Pictures(#)(\_->id)
EventKey(MouseButton LeftButton)Down _(x,y)#l=Translate x y(Circle 1):l
_#l=l

This uses the Gloss library (v1.11). It opens a full screen window and paints black pixels (in fact circles with radius 1) by pressing the left mouse button. Press ESC to exit.

How it works:

play                 -- handles the whole event handling, screen update, etc. process
    FullScreen       -- use a full screen window
    white            -- use a white background
    9                -- 9 simulation steps per second (see simulation handler below)
    []               -- the initial world state, an emtpy list of circles
    Pictures         -- a function to turn the world state into a picture.
                     -- The world state is a list of translated circles and
                     -- "Pictures" turns this list into a single picture
    (#)              -- event handler, see below
    (\_->id)         -- simulation step handler. Ignore time tick and return the
                     -- world state unchanged. More readable: "\tick world -> world"

EventKey ... # l=... -- if the left mouse button is pressed, add a circle with
                     -- radius 1 translated to the current position of the mouse
                     -- to the world state
_#l=l                -- on all other events do nothing

Edit: @ceased to turn counterclockwis told me about the newst version of gloss which saves 5 bytes when using full screen windows. Thanks!

  • FullScreen is nullary in gloss>=1.11, reducing the score by 5. (I'm getting an error unknown GLUT entry glutInit though, but probably my glut setup just doesn't work; never used it on this machine.) – ceased to turn counterclockwis Apr 21 '17 at 18:39
  • @ceasedtoturncounterclockwis: ah, thanks for the hint. I had 1.10.2.3 on my system and now updated to the latest version. – nimi Apr 21 '17 at 18:57

SmileBASIC 2, 52 51 bytes

This one runs in SmileBASIC's daddy, Petit Computer (and is one two byte shorter.)

PNLTYPE"OFF
GPAGE 1GCLS 15@A
GPSET TCHX,TCHY
GOTO@A

Explanation:

PNLTYPE"OFF       'turn off keyboard
GPAGE 1           'set graphics to lower screen
GCLS 15           'clear with color 15 (white)
@A                'loop begin
GPSET TCHX,TCHY   'set black pixel at draw location
GOTO@A            'loop
  • You can save 1 byte by doing GPSET TCHX,TCHY:GOTO@A since the default color is 0 (transparent). – 12Me21 Apr 21 '17 at 14:10

Javascript + jQuery 138 bytes

d=$(document.body).click((e)=>d.append("<div style='background:black;width:5;height:5;position:fixed;top:"+e.pageY+";left:"+e.pageX+"'>"))

Check it out online!

Adding click and drag support would be simple, you'd set a variable, however, per the instructions and to shorten code, it is not supported, "Anytime the mouse is pressed down, change the pixel that the mouse is on to black". I interpretted the instruction as a click event.

  • 3
    Hiya! Next time, you should undelete your old answer instead of making a new answer. Also, I'm afraid that this must work in a specified environment--if this is vanilla javascript, you'll have to include the byte count of jQuery with your submission. You could call this submission "JavaScript + jQuery", and that would be fine: there you could assume jQuery is installed. As this answer currently stands, its more of a "HTML" answer,n ot a javascript one. – Conor O'Brien Apr 20 '17 at 21:52
  • 1
    @ConorO'Brien I'll make sure to do that next time. I updated the answer using your suggestions. – Neil Apr 20 '17 at 21:54

SpecBAS - 61 59 bytes

1 CLS 15 
2 IF MOUSEBTN=1 THEN PLOT MOUSEx,MOUSEy
3 GO TO 2

Black is already the default pen colour, but the background is usually a nasty shade of grey, so CLS 15 sets it to bright white.

enter image description here

  • Most Basic variants don't require a space between the command number and the code on that line. – Pavel Apr 21 '17 at 17:07
  • SpecBAS adds all the spaces after you hit return (including GOTO becoming GO TO) – Brian Apr 23 '17 at 11:08
  • 1
    But can you remove the spaces, and still have it run fine? If so, you don't count them. – Pavel Apr 23 '17 at 20:22
  • If the user doesn't mind only painting with black, why would he mind a grey background? – Cees Timmerman Apr 24 '17 at 6:52

SmileBASIC, 70 58 53 Bytes

XSCREEN 4GCLS-1@L
TOUCH OUT,X,Y
GPSET X,Y+240,0GOTO@L

Explained:

XSCREEN 4 'display one graphics page on both screens
GCLS -1 'fill screen with white
@L 'loop
TOUCH OUT,X,Y 'get touch location
GPSET X,Y+240,0 'draw black pixel at touch position, offset by the height of the top screen.
GOTO @L 'loop

Clojure, 91 71 bytes

-20 bytes thanks to @cfrick for pointing out that I can use use to shrink my importing.

(use 'quil.core)(defsketch P :mouse-dragged #(point(mouse-x)(mouse-y)))

Uses the Quil library. Draws a dot whenever the mouse is dragged.

Basically the Processing answer, since Quil is a Processing wrapper for Clojure.

(q/defsketch P ; Start a new drawing

             :mouse-dragged ; Attach a mouse drag listener
             ; that draws a point at the current mouse location
             #(q/point (q/mouse-x) (q/mouse-y))) 

enter image description here

  • 71: (use 'quil.core)(defsketch P :mouse-dragged #(point(mouse-x)(mouse-y))) – cfrick Apr 24 '17 at 13:15
  • @cfrick LOL, I always forget about use because it's "not proper". Thank you. – Carcigenicate Apr 24 '17 at 13:16

Tcl/Tk, 45 46 51 57

gri [can .c]
bind . <1> {.c cr o %x %y %x %y}

pentagram

  • That is one fugly pentogram 😁 – Johan du Toit Apr 24 '17 at 18:45
  • @JohanduToit: Don't you like stars? – sergiol Apr 26 '17 at 0:20

Java 7, 353 bytes

import java.awt.*;import java.awt.event.*;class M{static int x,y;public static void main(String[]a){Frame f=new Frame(){public void paint(Graphics g){g.drawLine(x,y,x,y);}};f.addMouseListener(new MouseAdapter(){public void mousePressed(MouseEvent e){x=e.getX();y=e.getY();f.repaint(x,y,1,1);}});f.setBackground(Color.WHITE);f.resize(500,500);f.show();}}

Ungolfed:

import java.awt.*;
import java.awt.event.*;

class M {
    //store the last point
    static int x, y;
    public static void main(String[] a) {
        Frame f = new Frame() {
            @Override
            public void paint(Graphics g) {
                g.drawLine(x, y, x, y);
            }
        }
        f.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                x = e.getX();
                y = e.getY();
                //repaint only the "new pixel"
                f.repaint(x, y, 1, 1);
            }
        });
        //default background is grey
        f.setBackground(Color.WHITE);
        f.resize(500, 500);
        f.show();
    }
}

Python2 and Python3, 82 bytes (or 77?)

from turtle import *;up();onscreenclick(lambda x,y: goto(x,y)or dot(1));mainloop()

Using the Turtle module, this isn't too bad :)

Ungolfed:

import turtle
turtle.up()

def fun(x, y):
    turtle.goto(x,y)
    turtle.dot(1)

turtle.onscreenclick(fun)
turtle.mainloop()

If it's OK to have lines between the dots, you can actually save 5 bytes:

from turtle import *;onscreenclick(lambda x,y: goto(x,y)or dot(1));mainloop()
  • from turtle import *;up();onclick(lambda *x:goto(*x)or dot(1));done() – innisfree Apr 24 '17 at 13:56
  • That's 70 bytes – innisfree Apr 24 '17 at 13:58

Excel VBA, 62 Bytes

Anonymous VBE immediate window function that allows the user to draw on the any sheet by simply selecting it

Cells.RowHeight=48:Do:DoEvents:Selection.Interior.Color=0:Loop

Sample Output

enter image description here

HTML + Javascript, 152 148 bytes

<body onclick="document.body.innerHTML+='<x style=position:fixed;width:1;height:1;left:'+event.clientX+';top:'+event.clientY+';background:#000;>'"/>

Turing, 77 bytes

var x,y,b:int loop mousewhere(x,y,b)if b=1then drawdot(x,y,1)end if end loop

Ungolfed:

var x,y,b : int      
loop
  mousewhere(x,y,b)  % Set (x,y) to mouse co-ords, and b to 1 or 0 indicating if the button is pressed
  if b=1 then
    drawdot(x,y,1)  % Draw a black pixel at (x,y)
  end if
end loop

HTML + CSS + JavaScript (ES6), 8 + 31 + 64 = 103 bytes

Fun with CSS box-shadow!

s='0 0 0',onclick=e=>p.style.boxShadow=s+=`,${e.x}px ${e.y}px 0`
*{margin:0;width:1px;height:1px
<p id=p>

HTML + CSS + JavaScript (ES6), 8 + 22 + 69 = 99 bytes

This one attempts to offset the default margin of the <body> element, but it may be different across browsers and user agent stylesheets. Tested successfully in Chrome.

s='0 0 0',onclick=e=>p.style.boxShadow=s+=`,${e.x-8}px ${e.y-16}px 0`
*{width:1px;height:1px
<p id=p>

HTML + CSS + JavaScript (ES6), 8 + 18 + 69 = 95 bytes

Pixels in this one may appear bigger as they are drawn at half-pixel coordinates.

s='0 0 0',onclick=e=>p.style.boxShadow=s+=`,${e.x}px ${e.y}px 0 .5px`
*{margin:0;width:0
<p id=p>

TI-Basic, 1 byte

Pt-Change(

I'm sure that most of you with TI calcs thought of the Pen command, but it turns out that it's not tokenized so it would make most sense to count that as 3 bytes. You can read about the interactive version of Pt-Change( at http://tibasicdev.wikidot.com/pt-change

  • This does not answer the challenge: TI calcs can’t handle mouse input, as far as I know. – Grimy Apr 24 '17 at 11:44
  • 2
    @Grimy If you insist you can always use the usb8x library to get USB mouse input instead. But I'm sure that the default cursor navigation will suffice. – Timtech Apr 24 '17 at 12:28

Lua (love2d Framework), 180 bytes

golfed version

l=love v,g,m,p=255,l.graphics,l.mouse,{}d=m.isDown function l.draw()g.setBackgroundColor(v,v,v)if d(1)or d(2)then p[#p+1],p[#p+2]=m.getPosition()end g.setColor(0,0,0)g.points(p)end

ungolfed

l=love 
v,g,m,p=255,l.graphics,l.mouse,{}
d=m.isDown 
function l.draw()
  g.setBackgroundColor(v,v,v)
  if d(1)or d(2)then 
    p[#p+1],p[#p+2]=m.getPosition()
  end 
  g.setColor(0,0,0)
  g.points(p)
end

quite easy how it works. First a few initialisations to make things shorter. After it it will check the mous is clicked and saves the points to the array. After that it draws the points.Also it sets the color to white& black cause default is the other way around :)
And here comes the picture:

enter image description here

  • 1
    Believe it or not, I came here to post an answer using Love2d as I only recently found out about it and love it, so +1 for the nice effort! Anyway, I think you can shorten it down a bit more as like this: l=love v,g,m,p=255,l.graphics,l.mouse,{}function l.draw()g.setBackgroundColor(v,v,v)if m.isDown(1)then p[#p+1],p[#p+2]=m.getPosition()end g.setColor(0,0,0)g.points(p)end which results into 169 bytes! – DimP Apr 26 '17 at 19:01
  • 1
    I came here kind of the same reason, nice to see that there are other people out here who know it :D Thank you :) – Lycea Apr 27 '17 at 15:14

Processing, 65 bytes

void draw(){if(mousePressed)line(mouseX,mouseY,pmouseX,pmouseY);}

minimal draw

glslsandbox 232 bytes

Old post but found this interesting.
Since processing already been done I decided to do something different.

This draws whether the mouse is pressed or not, so not what pydude asked for but almost.

#ifdef GL_ES
precision lowp float;
#endif
uniform float time;uniform vec2 mouse,resolution;uniform sampler2D t;void main(){vec2 f=gl_FragCoord.xy,r=resolution;gl_FragColor=vec4(time<2.||length(f-mouse*r)>2.&&texture2D(t,f/r).x>.1);}

Try it on glslsandbox

Processing, 93 bytes, 91 bytes if spaces don't count

void setup(){size(100,100);background(-1);}void draw(){if(mousePressed) point(mouseX,mouseY);}
  • 1
    In PPCG, if not mentioned in the challenge, spaces and everything count as normal (as bytes in the encoding of choice, by default UTF-8). So your score would be 92 bytes as the 1st space can't be removed without breaking the program, but the second space can be safely removed. – dzaima Apr 22 '17 at 11:14

UCBlogo with wxWidgets, 65 bytes

setbg 7
setpc 0
ht
pu
make "buttonact[setpos clickpos pd fd 1 pu]

Explanation (the code assigned to the variable buttonact is executed on each button click):

SetBackground 7 ; white
SetPenColor 0 ; black
HideTurtle
PenUp
make "buttonact [
  SetPos ClickPos
  PenDown
  Forward 1
  PenUp
]

At least, I think this works. It should according to the documentation, but apparently the buttonact variable only works in a wxWidgets build and I'm struggling to build UCBLogo with wxWidgets on a modern Linux (waddyamean you can't cast a pointer to int and back?).

UCBlogo without wxWidgets, 73 bytes

To see the intended effect, you can run this longer version with an infinite loop.

setbg 7 setpc 0 ht pu
while[1=1][setpos mousepos if[button?][pd] fd 1 pu]

But this crashes ucblogo on my machine... Looks like a race condition.

UCBlogo, actually working on my machine, 80 bytes

setbg 7 setpc 0 ht pu
while[1=1][setpos mousepos if[button?][pd] fd 1 pu wait 1]

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.