51
\$\begingroup\$

Write a program that creates a two-state checkbox that people can interact with using a mouse.

Specifically, your program should achieve all of the following:

  1. Have a 8×8 pixel (or larger if desired) region of the screen that is the clickable area of the checkbox. Henceforth this region is simply called the checkbox.

  2. When the mouse cursor is moved within the checkbox and the default* mouse button is pressed, the checkbox should toggle states.
    Checked becomes unchecked. Unchecked becomes checked.

  3. The checkbox should not move when it is toggled.

  4. In the checked state, the checkbox may be any colors.

  5. In the unchecked state, the checkbox may be any colors as long as at least 16 pixels are visually distinct from the checked state.

  6. In a single program instance, all checked states should be visually identical to one another and all unchecked states should be visually identical to one another.

  7. Don't end the program until it's explicitly terminated (e.g. via exit button or Alt+F4), so a user can click the checkbox as much as they want.

*You may assume the default mouse button is always left click, but it's also fine to use the default as defined by mouse software or the OS, which may not actually be left click depending on the user.

Notes

  • It does not matter what is outside of your checkbox region. It could just be the desktop. It could be a portion of a console that changes on every toggle.

  • It does not matter what state your checkbox starts in.

  • The checkbox region may have any dimensions at or above 8×8 pixels. It need not be square.

  • You may make minor allowances for settings that are out of your control such as console font size, browser zoom, monitor resolution, etc. As long your program works in a reasonable test setting it should be valid.

  • If your program opens a window, you may assume it has been dragged to an appropriate location on the screen if necessary (e.g. top left corner).

  • You may use markup languages such as HTML or other languages we usually don't consider as full-fledged programming languages.

  • Your checkbox must be be toggleable using the default mouse button. It's alright if it also toggles for other forms of input (e.g. right mouse button), with the exception of mouse motion. i.e. the state should not change if the mouse is merely moved within the checkbox.

  • Screenshots of your checkbox in action are highly encouraged!

Scoring

The shortest code in bytes wins.

Example

A canonical HTML example in 23 bytes.

<input type="checkbox">

For me in Google Chrome, this makes a 12×12 pixel checkbox and about 30 pixels clearly change between checked and unchecked states.

I make the allowance that browser zoom is at 100%.

\$\endgroup\$
  • 2
    \$\begingroup\$ Can the checkbox cover the entire screen? \$\endgroup\$ – Cows quack Feb 5 '17 at 11:19
  • \$\begingroup\$ @KritixiLithos Yes, that would be valid.Though note that you may, if desired, count a particular 8x8 region as the official checkbox, even if a larger region works. \$\endgroup\$ – Calvin's Hobbies Feb 5 '17 at 11:22
  • \$\begingroup\$ @Helka Homba - is it allowed for an app to display other controls, aside the checkbox itself ? \$\endgroup\$ – zeppelin Feb 5 '17 at 12:54
  • \$\begingroup\$ Is it OK for the checkbox to toggle on other sorts of input? (For example, is a solution correct if the checkbox toggles on any sort of user input, regardless of whether it's a mouse click, a mouse movement, or a keypress? It'd toggle on a mouse click, but it'd toggle on other stimuli too.) \$\endgroup\$ – user62131 Feb 5 '17 at 16:27
  • 1
    \$\begingroup\$ @zeppelin "It does not matter what is outside of your checkbox region. It could just be the desktop. It could be a portion of a console that changes on every toggle." So, as long as the checkbox is there, it doesn't matter what else is. \$\endgroup\$ – Calvin's Hobbies Feb 5 '17 at 20:42

53 Answers 53

3
\$\begingroup\$

Slim, 21 Bytes

input type="checkbox"

Try it here

So yeah. One of slim's major features is that < and > characters are not there. So basically, I get 2 bytes less than the creator of the question!

\$\endgroup\$
  • 1
    \$\begingroup\$ HTML still beats it though :) codegolf.stackexchange.com/a/109189/44888 \$\endgroup\$ – Jan Feb 6 '17 at 1:40
  • \$\begingroup\$ remove quotes for better points \$\endgroup\$ – dkudriavtsev Feb 7 '17 at 8:10
  • \$\begingroup\$ @wat It seems that's not allowed in Slim \$\endgroup\$ – Metoniem Feb 8 '17 at 14:27
  • \$\begingroup\$ @Metoniem That's excessively ironical. \$\endgroup\$ – Right Leg Feb 10 '17 at 4:36
3
\$\begingroup\$

Bash + zenity, 31

zenity --checklist --column a a

enter image description here

enter image description here

\$\endgroup\$
3
\$\begingroup\$

Bash (+yad), 23 bytes

Golfed

yad --form --field :chk

YAD is a program that will display GTK+ dialogs, and return (either in the return code or on standard output) the users input. This allows you to present information, and ask for information from the user, from all manner of shell scripts.

Yad is available in Debian and Ubuntu repositories (and probably others).

Demo

enter image description here

\$\endgroup\$
3
\$\begingroup\$

CSS, 46

Assumes a minimal HTML document, not unlike this CSS Hello World submission.

This one avoids the extra "X" of the old 42 char solution, making it conform with the rules.

NOTE: Seems to only work in Firefox (51.0.1)

* :after{content:'X'}*:active :after{all:unset

CSS, 42 (old solution)

:after{content:'X'}:active:after{all:unset

\$\endgroup\$
  • 1
    \$\begingroup\$ Not switching state by click, but switches to other state while muose button is pressed. \$\endgroup\$ – Qwertiy Feb 26 '17 at 21:23
  • \$\begingroup\$ @Qwertiy, which browser are you using? \$\endgroup\$ – thykka Mar 9 '17 at 7:54
  • \$\begingroup\$ Chrome 56 on Windows 7 x64. Anyway, I expect it to be in any browser as :active should work only while mouse button is down. What browser do you use with the other result? \$\endgroup\$ – Qwertiy Mar 9 '17 at 9:25
  • \$\begingroup\$ @Qwertiy, Firefox, as was clearly stated above. \$\endgroup\$ – thykka Mar 9 '17 at 9:29
  • \$\begingroup\$ Checked at my Firefox 52.0 beta 9 x32 - absolutely the same results as in Chrome. By the way, 42-byte solution has 3 states intead of 2: both Xs are visible, only the fisrst X is visible and both X are invisible. What OS are you using? \$\endgroup\$ – Qwertiy Mar 9 '17 at 9:33
3
\$\begingroup\$

Java 1.4+, 104 bytes

import java.awt.*;interface g{static void main(String[]a){new Frame(){{add(new Checkbox());show();}};}}

-13 thanks to Kevin Cruijssen.

enter image description here

Groovy, 67 bytes

import java.awt.*;{new Frame(){{add(new Checkbox())setVisible(1)}}}
\$\endgroup\$
  • \$\begingroup\$ Does !0 work instead of 1>0? It does in groovy. \$\endgroup\$ – Gurupad Mamadapur Feb 8 '17 at 11:40
  • \$\begingroup\$ The exact same thing is 68 bytes in groovy excluding main method signature and ending ;. \$\endgroup\$ – Gurupad Mamadapur Feb 8 '17 at 11:43
  • \$\begingroup\$ @GurupadMamadapur in groovy it'd just be setVisible(1). In Java 8 it works; in all versions of java though, that is not valid syntax. \$\endgroup\$ – Magic Octopus Urn Feb 8 '17 at 13:47
  • 1
    \$\begingroup\$ Ah, you're right. It was treating the .*{ as a vectorized closure on java.awt so the ; is required. \$\endgroup\$ – Magic Octopus Urn Feb 8 '17 at 14:01
  • 1
    \$\begingroup\$ That closure won't execute - Error-Ambiguous expression could be either a parameterless closure expression or an isolated open code block. Also, 1 won't evaluate to true. It raises MethodMissing exception. \$\endgroup\$ – Gurupad Mamadapur Feb 8 '17 at 14:07
2
\$\begingroup\$

Jolf, 19 bytes

"<Ξ♠ΐ♠type=Ξ\t5δbox>

Replace \t with a tab literal and with 0x06. Try it here!

"<Ξ♠ΐ♠type=Ξ\t5δbox>
"...................   string containing...
 <                     "<"
  Ξ♠ΐ♠                 compressed for "input "
      type=            "type="
           Ξ\t5δ       compressed for "CHECK"
                box    "box"
                   >

This displays a checkbox to the output element.

\$\endgroup\$
2
\$\begingroup\$

FLTK, 48 characters

Function{}{}{Fl_Window{}{}{Fl_Check_Button{}{}}}

Sample run:

bash-4.3$ fluid -c checkbox.fl 

bash-4.3$ fltk-config --compile checkbox.cxx 
g++ -I/usr/include/cairo -I/usr/include/glib-2.0 -I/usr/lib/x86_64-linux-gnu/glib-2.0/include -I/usr/include/pixman-1 -I/usr/include/freetype2 -I/usr/include/libpng16 -I/usr/include/freetype2 -I/usr/include/cairo -I/usr/include/glib-2.0 -I/usr/lib/x86_64-linux-gnu/glib-2.0/include -I/usr/include/pixman-1 -I/usr/include/freetype2 -I/usr/include/libpng16 -g -O2 -fvisibility-inlines-hidden -D_LARGEFILE_SOURCE -D_LARGEFILE64_SOURCE -D_THREAD_SAFE -D_REENTRANT -o 'checkbox' 'checkbox.cxx' -Wl,-Bsymbolic-functions -lfltk -lX11

bash-4.3$ ./checkbox

Sample output:

checkbox using FLTK

\$\endgroup\$
2
\$\begingroup\$

Racket, 98 bytes

#lang racket/gui
((λ(f)(new check-box%[parent f][label""])(send f show #t))(new frame%[label""]))

At least I have a few bytes on the Clojure answer!

\$\endgroup\$
2
\$\begingroup\$

C#, 814 bytes

Out of interest I decided to see how many bytes it would take to use a console application in C# using the mouse to change the checked state. There is no built in support so you have to use unmanaged code and it get's very long, very fast. There might be room for improvement but it's never going to be short.

Note: It does seem to change the checked state when the mouse is pressed and is moved at the same time. But seeing as this is never going to compete I decided to leave that be as a quirk.

using System;using System.Runtime.InteropServices;class P{static void Main(){int m=0,n=0,c=0;var h=GetStdHandle(-10);GetConsoleMode(h,ref m);SetConsoleMode(h,m&=~64);new System.Threading.Thread(()=>{for(;;){var r=new[]{new r()};ReadConsoleInput(h,r,1,ref n);Console.Clear();if(r[0].e==2&&r[0].m.s==1)Console.BackgroundColor=++c%2<1?0:(ConsoleColor)1;}}).Start();}[StructLayout((LayoutKind)2)] struct r{[FieldOffset(0)]public int e;[FieldOffset(4)]public m m;}struct m{int p;public int s;}[DllImport("kernel32.dll")]static extern IntPtr GetStdHandle(int h);[DllImport("kernel32.dll")]static extern bool GetConsoleMode(IntPtr h,ref int m);[DllImport("kernel32.dll")]static extern bool SetConsoleMode(IntPtr h,int m);[DllImport("kernel32.dll")]static extern bool ReadConsoleInput(IntPtr h,[Out]r[]r,int l,ref int n);}

And the formatted version:

using System;
using System.Runtime.InteropServices;

class P
{
    static void Main()
    {
        int m = 0, n = 0, c = 0;

        var h = GetStdHandle(-10);
        GetConsoleMode(h, ref m);
        SetConsoleMode(h, m &= ~64);

        new System.Threading.Thread(() =>
        {
            for (;;)
            {
                var r = new[] { new r() };
                ReadConsoleInput(h, r, 1, ref n);

                Console.Clear();
                if (r[0].e == 2 && r[0].m.s == 1)
                    Console.BackgroundColor = ++c % 2 < 1 ? 0 : (ConsoleColor)1;
            }
        }).Start();
    }

    [StructLayout((LayoutKind)2)]
    struct r
    {
        [FieldOffset(0)]
        public int e;
        [FieldOffset(4)]
        public m m;
    }

    struct m
    {
        int p;
        public int s;
    }

    [DllImport("kernel32.dll")]
    static extern IntPtr GetStdHandle(int h);

    [DllImport("kernel32.dll")]
    static extern bool GetConsoleMode(IntPtr h, ref int m);

    [DllImport("kernel32.dll")]
    static extern bool SetConsoleMode(IntPtr h, int m);

    [DllImport("kernel32.dll")]
    static extern bool ReadConsoleInput(IntPtr h, [Out]r[] r, int l, ref int n);
}
\$\endgroup\$
2
\$\begingroup\$

Vim: 13 Bytes Keystrokes

iq<Esc>:nm a g??<CR>

Press a and toggle between q and d (feels like a lever to me ...)

Explanation:

 iq<Esc>   " insert a q char
 nm a      " create a normal mapping toggled by a
 g??       " rot13 the current line, q -> d -> q ...
 <CR>      " validate the mapping
\$\endgroup\$
  • \$\begingroup\$ The checkbox has to be activated by the mouse, not the keyboard. I think you can do :nm <LeftMouse> g?? instead \$\endgroup\$ – Cows quack Feb 8 '17 at 11:01
2
\$\begingroup\$

C#, 151 139 bytes

This is a longer approach than @satibel his answer, but it's completely different and doesn't require a form. Since I couldn't comment about if I could use key presses instead of mouse clicks (not enough rep.) I'm not 100% sure this is allowed, so let me know!

EDIT: Managed to lose 12 bytes thanks to some of my own improvements, and some are thanks to @TheLethalCoder

Golfed

using c=System.Console;class p{static void Main(){for(int _=1;;_++){c.ReadKey();_%=2;c.BackgroundColor=(System.ConsoleColor)_;c.Clear();}}}

Ungolfed

using System;
class p
{
    static void Main()
    {
        int _ = 0;
        for (int _=1;;_++)
        {
            Console.ReadKey(); //Wait for user input
            _%=2; //Prevent integer from overflowing at some point
            Console.BackgroundColor = (System.ConsoleColor)_; //Set Console background color to either 0 (black) or 1 (darkblue) depending on if our integer is even
            Console.Clear(); //Clear console window to get rid of input. This also causes the whole console window to change color
        }
    }
}

I know it's kind of tricky since it works with keypresses rather than mouseclicks, so let me know if that's allowed. If it's not, I'll happily remove my answer, or write a new one instead!

\$\endgroup\$
  • 1
    \$\begingroup\$ You can do it using mouse clicks but the code get's really long \$\endgroup\$ – TheLethalCoder Feb 7 '17 at 12:30
  • 1
    \$\begingroup\$ Very very long in fact: codegolf.stackexchange.com/a/109383/38550 \$\endgroup\$ – TheLethalCoder Feb 7 '17 at 12:37
  • \$\begingroup\$ @TheLethalCoder That's an amazing answer. I knew it was possible, but I didn't even dare to try.. GG to you sir! (Can't comment on other answers than my own yet, sorry) \$\endgroup\$ – Metoniem Feb 7 '17 at 14:02
  • \$\begingroup\$ Amazing that you can do it (I did a lot of googling and then hacking on the result to get it to work and be "short"). Just not amazing with how long it is! And no worries keep posting good answers and you will get there. \$\endgroup\$ – TheLethalCoder Feb 7 '17 at 14:17
  • 1
    \$\begingroup\$ Improvement points (untested on length but should save you bytes): using c = System.Console; instead of using System; and then do c.ReadKey(); etc, the _++; and _%=2; can be combined using post increment to ++_%=2; (I think that should work although I haven't tested), < 1 instead of == 0, Might be able to assign _ on the BackgroundColor line but you'd have to experiment with it. \$\endgroup\$ – TheLethalCoder Feb 7 '17 at 14:21
2
\$\begingroup\$

P5.js 35 26 bytes

function setup(){createCheckbox()}

not really fun, but it works.

setup=s=>createCheckbox()

-9 bytes thanks to Kritixi

\$\endgroup\$
  • \$\begingroup\$ setup=s=>createCheckbox() is shorter \$\endgroup\$ – Cows quack Feb 6 '17 at 8:32
1
\$\begingroup\$

Java, 69 bytes

a->{a.removeAll();a.add(new java.awt.Checkbox());a.setVisible(1>0);};

Just a not-so-self-explanatory Consumer<Frame>. It takes a Frame, removes everything in it, puts a checkbox, and then makes sure the Frame is displayed.

\$\endgroup\$
1
\$\begingroup\$

Coding, 21 bytes

>input(checkbox)@type

Finally a perfect time to use this language!

\$\endgroup\$
1
\$\begingroup\$

VBA, 42 bytes

ActiveSheet.CheckBoxes.Add(1,1,8,8).Select

Best I could get with this!

\$\endgroup\$
1
\$\begingroup\$

 Emacs Lisp, 58

(and(widget-create'checkbox)(use-local-map widget-keymap))

enter image description here

\$\endgroup\$
1
\$\begingroup\$

Javascript, 24 23 21

for(i=0;;)alert(i=!i)

i=0;while(1)alert(i=!i)

i=0;while(1)alert(++i%2)

WARNING: Might cause you to have to force-quit your browser

This one is a neat solution because it actually is not a check box and has none of the logic of a check box, but on the surface behaves very similar to a check box (toggling change of state on button press) due to exploiting the action-based delay in javascript alerts, and meets all of the criteria of rules defined in the challenge.

Try it here (*Might cause you to have to force-quit your browser)

<script>for(i=0;;)alert(i=!i)</script>

\$\endgroup\$
  • \$\begingroup\$ Wow, this is clever. Usage of text as an image, I like it. \$\endgroup\$ – Zacharý Sep 3 '17 at 19:45
1
\$\begingroup\$

VB.NET, 67 (program) + 37 (additional switches) = 104

VB.NET Windows Forms Application, 67 chars

Class F
Inherits Form
Dim C=New CheckBox With{.Parent=Me}
End Class

Compile it with

vbc.exe *.vb /main:F /imports:System.Windows.Forms

Not using /target:winexe switch. Assume that additional console is ok.

Screenshot

PS: Question about byte count.

\$\endgroup\$
  • \$\begingroup\$ Nice. I don't think you need the Inherits Form if you specify you're using Windows Form Application. \$\endgroup\$ – Oliver Feb 26 '17 at 22:05
  • \$\begingroup\$ @obarakon, but I don't specify that. That's just a file, not the part of solution. In case of winforms solution I wouldn't write main and imports switches by myself. \$\endgroup\$ – Qwertiy Feb 26 '17 at 22:07
  • \$\begingroup\$ I get the desired form+checkbox just running Class F Dim C=New CheckBox With{.Parent=Me} End Class in an empty WFA project. \$\endgroup\$ – Oliver Feb 26 '17 at 22:10
  • \$\begingroup\$ @obarakon, let's discuss byte count: meta.codegolf.stackexchange.com/q/11650/32091. By the way, in case of winforms app you have partial class because of designer. \$\endgroup\$ – Qwertiy Feb 26 '17 at 22:20
1
\$\begingroup\$

JQuery, 50 Bytes

$("<input type=checkbox>").appendTo(document.body)
\$\endgroup\$
  • 2
    \$\begingroup\$ Welcome to PPCG! \$\endgroup\$ – Martin Ender Jun 30 '17 at 11:26
0
\$\begingroup\$

SAS, 145

proc pmenu catalog=work.c;menu m;item i dialog=d;dialog d '&1';text #1 @1 'A';checkbox #2 @1 'B';run;quit;%window w menu=work.c.m '';%display w;

This creates and displays a menu with an item that opens a dialogue box with a checkbox. It might be possible to golf it further, but I'm reluctant to try as this has already led to several crashed sessions :(

\$\endgroup\$
0
\$\begingroup\$

C# (Windows Form Application), 82 bytes

using System.Windows.Forms;class F:Form{public F(){Controls.Add(new CheckBox());}}

Saved bytes thanks to @Qwertiy

enter image description here

\$\endgroup\$
  • \$\begingroup\$ Full program, not a function. \$\endgroup\$ – Qwertiy Feb 26 '17 at 21:20
  • \$\begingroup\$ Why do you need namespace? And partial class? \$\endgroup\$ – Qwertiy Feb 26 '17 at 21:45
  • \$\begingroup\$ Let's discuss byte count: meta.codegolf.stackexchange.com/q/11650/32091. \$\endgroup\$ – Qwertiy Feb 26 '17 at 22:21
0
\$\begingroup\$

C (Win32 Console application), 143 131 bytes

#include<windows.h>
main(){MSG m;for(CreateWindow("button","",1<<28|3,0,0,8,80,0,0,0,0);GetMessage(&m,0,0,0);DispatchMessage(&m));}
\$\endgroup\$
0
\$\begingroup\$

C++ with SFML, 401 bytes

-4 bytes thanks to Zacharý

#include<SFML\Graphics.hpp>
#include<cassert>
using namespace sf;int main(){RenderWindow w(VideoMode(300,300),"");Texture a,b;assert(a.loadFromFile("a.png")&&b.loadFromFile("b.png"));Sprite p(a),q(b);bool c=0;while(w.isOpen()){Event e;while(w.pollEvent(e)){if(e.type==Event::Closed)w.close();if(e.type==Event::MouseButtonPressed)c=!c;}w.clear(Color::White);if(c)w.draw(q);else w.draw(p);w.display();}}

Screenshot of the boxes :

Checked :

Checked checkbox

And unchecked :

Unchecked checkbox

This uses the SFML library The checkbox changes state on a sf::Event::MouseButtonPressed event ( left click, right click, middle click... )

If you want to test, after the creation of the render window, you may want to set the framerate limit to 60 fps ( using the line w.setFramerateLimit(60) ), so your computer won't burn.

This requires 2 checkboxes images in the directory where the app runs ( a.png and b.png ). For the reason it uses images, i don't know if my answer is invalid ( standard loophole ? ), but since it's needed to do graphic output...

\$\endgroup\$
  • \$\begingroup\$ a.loadFromFile("a.png") && b.loadFromFile("b.png") => a.loadFromFile("a.png")&&b.loadFromFile("b.png"). if (e.type=>if(e.type. Does your code editor auto-format or something? \$\endgroup\$ – Zacharý Sep 3 '17 at 19:41
  • \$\begingroup\$ Forgot one... VideoMode(300, 300) => VideoMode(300,300) \$\endgroup\$ – Zacharý Sep 3 '17 at 19:46
  • \$\begingroup\$ @Zacharý Yes, it format every new semi colon. \$\endgroup\$ – HatsuPointerKun Sep 3 '17 at 19:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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