Take the 2-minute tour ×
Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

Your goal is simple: the program must turn the screen of your computer totally black.

After the program is started, the screen must quickly turn completely black, and remain so until the program is exited (any key, or alt+F4, mouse movement, etc.), after which things should turn back to normal. So shutting down the computer or turning the power of the monitor off is NOT allowed. Not a single non-black pixel should be visible during this time, not even a blinking cursor.

The user should not do any preparation (moving the mouse outside the screen, disconnecting cables, etc. or user input after the program started), just start the program.

You can safely assume the computer has only one monitor attached. We also assume a standard desktop or notebook computer, because doing it on a specific device without a normal monitor would be too simple.

If you use any external resources (a black image, a GUI file, etc.) their size in bytes is added to your code size.

It's OK if it only works on one OS family, or if it requires opengl etc., but requiring a very specific hardware configuration is frowned upon.

Your source code must be written in a programming language, not just a configuration file some other program (like a screen saver) will use.

share|improve this question
9  
That won't work on screens with stuck pixels... –  Ismael Miguel May 6 at 16:36
20  
@IsmaelMiguel : you can safely assume a screen in perfect working condition. Otherwise we could object other questions in the style of "what if a transistor in my ALU is burned out and my computer cannot do any floating point math?" :) –  vsz May 6 at 16:37
5  
Fun fact: on screens that use neither CRT nor dynamic contrast, this will use slightly more electricity! –  minitech May 6 at 17:11
2  
real world application: Astronomy! lists.apple.com/archives/Carbon-dev/2008/May/msg00005.html –  Not that Charles May 6 at 17:23
2  
All of the answers are automatically disqualified—one of my monitors has a pixel whose red value is always 255! –  The Guy with The Hat May 6 at 19:16

23 Answers 23

up vote 21 down vote accepted

Bash, 28 or 12

Assuming default installation of Ubuntu 12.04 LTS.

gnome-screensaver-command -a

Automatically starts the screensaver, which is a black screen by default.

Edit: As suggested by @Glenn Randers-Pehrson, here's one with 12 bytes

/*/*/gn*d -a

Note that this may not work if you have another file on your system that satisfies this name, say /tmp/1/gnd. But it's code-golf, who cares?


Check out my other bash answer if you don't use Gnome screensaver!

share|improve this answer
1  
The kind of answer that makes you think: 'Why on earth didn't I think of that?'. :) –  Alex Thornton May 6 at 18:33
1  
That's not really clearing the screen using bash. –  user973810 May 6 at 18:49
3  
"Your source code must be written in a programming language, not just a configuration file some other program (like a screen saver) will use." –  hannes karppila May 6 at 19:03
2  
@hannes karppila I did not change any configuration file that any other program will use. I only started another program, which most bash scripts do (unless written in pure bash) –  ace May 6 at 19:07
5  
@ace, Golfed: /*/*/gn*d instead of gnome-screensaver-command will save about 16 bytes (idea by mniip) –  Glenn Randers-Pehrson May 6 at 20:52

Assembly (bootloader) 131 chars / 512 bytes compiled (actually smaller, but bootsector must be 512 bytes long.)

It is a simple boot loader. When computer starts, BIOS will load it from disk (floppy). Then it enters into graphics mode and just hangs. When user presses the power button, program will end and computer will enter to mode where is was before running program.

Tested with VirtualBox.

It will compile with nasm:

nasm -f bin file.asm -o start.img

Source code:

[BITS 16]
[ORG 0x7C00]
cli
mov AX,0x0
mov SS,AX
mov SP,0x9000
sti
mov AH,0x0
mov AL,0x13
int 0x10
times 510 - ($-$$) db 0
dw 0xAA55
share|improve this answer
1  
How to run on VirtualBox: (compile using nasm), new VM, Type: Other, version: Other/Unknown, no hard drive. Next up go to the VM's settings, select Storage, right click in the list, and select "Add Floppy Controller". Mount the compiled img file to the floppy drive. Save, and then you can run it. Enjoy! –  Zeke Sonxx May 6 at 23:36
    
I wanted to do the same thing as a dos program, but you were faster. Basically the only thing I remember of assembler from waaay back :) –  Fels 3 hours ago

Java : 165

Simple Java, just creates a fullscreen black frame. To exit you have to Alt+Tab back to the console and Ctrl-C, but that seems simple enough.

import java.awt.*;class B{public static void main(String[]a){Frame f=new Frame();f.setExtendedState(6);f.setUndecorated(1>0);f.setBackground(Color.BLACK);f.show();}}

// line breaks below

import java.awt.*;
class B{
    public static void main(String[]a){
        Frame f=new Frame();
        f.setExtendedState(6);
        f.setUndecorated(1>0);
        f.setBackground(Color.BLACK);
        f.show();
    }
}
share|improve this answer

QBASIC (31)

SCREEN 7
WHILE INKEY$=""
WEND
share|improve this answer
2  
+1 for the QBasic! –  The Guy with The Hat May 6 at 19:19
12  
@TheGuywithTheHat I finally found a use for my windows 3.1 vm. –  user973810 May 6 at 21:01
2  
Wow seeing that WEND brought back memories –  Claudiu May 7 at 14:30
    
@user973810 You mean QB64. –  nyuszika7h May 19 at 18:56

Bash - 57 26

C=/s*/*/*/*/b*ess;(A=$(cat $C);echo 0;cat;echo $A)|tee $C

On a laptop this will set the screen backlight brightness to 0 via /sys/class/backlight, on a tablet or phone this will set the screen led brightness to 0 via /sys/class/leds

share|improve this answer
2  
“and remain so until the program is exited (any key, or alt+F4, mouse movement, etc.), after which things should turn back to normal” –  minitech May 6 at 17:28
1  
Fn+F6, Fn+<up arrow> and many other key combinations fall into "any key" and "etc.", and those are one of the many to put the light back as it was. –  Ismael Miguel May 6 at 17:31
1  
@minitech Oh. Well, fixed... –  mniip May 6 at 17:33
    
This doesn't work at all for me. If I do "C=/s*/*/*/*/b*ess;(A=$(cat $C);echo 0;cat;echo $A)|tee $C" from the bash prompt I get cat: /s*/*/*/*/b*ess: No such file or directory tee: /s*/*/*/*/b*ess: No such file or directory –  Lembik May 8 at 11:48
    
@Lembik I would assume that you don't have any brightness controllers or those present are lacking drivers. Mind pastebinning find /sys/class/{backlight,leds}/*/ ? –  mniip May 8 at 11:56

Applesoft ][ BASIC (17)

1 HGR2:GET X:TEXT
share|improve this answer
    
I don't think this is actually 17 bytes...I think it might be less. If I remember correctly, Applesoft tokenized its keywords, so that each keyword was actually one byte...so this one may be significantly shorter. It's +1 either way. –  Beska May 9 at 13:07

I know this is but I couldn't resist.

Just make sure you don't have any browser windows open (in this case, Chrome);

Execute this PitchBlack.bat (31 24 bytes):

chrome --kiosk file:///1

If placed in the same directory of your Chrome.exe file, this batch will execute Chrome in kiosk mode and it will open a file called /1 (49 41 34 bytes) in fullscreen:

<body bgcolor=0 style=cursor:none>

Et voilà!

Total byte count: 80 72 58
Thanks to @ace :)

To exit the program, you must go for a classic ALT+F4; You don't actually have to do any preparation after the program starts (neither before, you just have to place /1 and the batch file), so it's fine with the rules.

Please note that if you get your cursor towards the screen borders, it may become visible. The OP didn't say this was not allowed, since

After the program is started, the screen must quickly turn completely black, and remain so until the program is exited (any key, or alt+F4, mouse movement, etc.), after which things should turn back to normal.

So this should be totally ok! :P

share|improve this answer
1  
Maybe something like chrome --kiosk 'data:text/html,<style>body{background:#000;cursor:none;}</style>' can work without additional file? –  Vi. May 7 at 16:08
    
Means when using file: shceme you get no URL bar visible, but with data: scheme there is URL bar? –  Vi. May 7 at 16:17
    
On my system chromium-browser --kiosk 'data:text/html,<style>body{background:#000;cursor:none;}</style> starts almost-fullscreen Chromium with the black page without any bars. –  Vi. May 7 at 16:25
    
Tested on Ubuntu and Chromium 34.0, it works with file:///1 if the html is saved as /1, and the html file can be shortened to <body bgcolor=0 style=cursor:none> –  ace May 7 at 17:31
1  
I think you should use chrome in your answer rather than chromium –  ace May 8 at 7:01

C# - 211 202 200 196 179 bytes

using System.Windows.Forms;class A{static void Main(){Cursor.Hide();new Form{BackColor=System.Drawing.Color.Black,WindowState=(FormWindowState)2,FormBorderStyle=0}.ShowDialog();}}

Hides the cursor and shows a full-screen black window. Can be closed with Alt+F4

Un-golfed code:

using System.Windows.Forms;
class A
{
    static void Main()
    {
        Cursor.Hide();
        new Form
        {
            BackColor = System.Drawing.Color.Black,
            WindowState = (FormWindowState)2, // FormWindowState.Maximized
            FormBorderStyle = 0 // FormBorderStyle.None
        }.ShowDialog();
    }
}

I don't need to cast to FormBorderStyle, because that's not necessary if the integer is 0.

share|improve this answer
2  
You can replace System.Drawing.Color.Black, FormWindowState.Maximized, FormWindowState.Maximized and FormBorderStyle.None with their corresponding values. –  Ismael Miguel May 6 at 17:03
    
@IsmaelMiguel: Thanks, I updated the FormWindowState and the FormBorderStyle! I couldn't update the Color, because that's not an enum. –  ProgramFOX May 6 at 17:08
    
Try Color.Black. It should work right away. Or BackColor=This.ForeColor, which MIGHT work too. –  Ismael Miguel May 6 at 17:11
    
@IsmaelMiguel: The first doesn't work because I didn't add using System.Drawing;, and the second doesn't work because I set the variable values inside brackets. –  ProgramFOX May 6 at 17:14
    
Try using System; then new Windows.Forms.Form and BackColor=Drawing.Color.Black. It MIGHT work! And save a few bytes. –  Ismael Miguel May 6 at 17:17

C# 175 171 167

class P{static void Main(){SendMessage(65535,274,61808,2);}[System.Runtime.InteropServices.DllImport("user32")]static extern int SendMessage(int a,int b,int c,int d);}

A lot of the answers here don't actually make the screen black: on an LCD screen, the backlight remains on and bleeds through, leaving you with a darkish grey.

This little snippet actually tells Windows to turn off the screen, the same as what the inactivity timer does (Note: this doesn't violate the "no power off" rule because it really just causes the monitor to go into standby. Most monitors will turn back on when input is resumed. Also, that rule's intention seems to be to make sure the program can turn it back on - see below.)

Move the mouse or press a key to turn the screen back on.

Monitor power off adapted from http://stackoverflow.com/a/713519/1030702

share|improve this answer
    
"So shutting down the computer or turning the power of the monitor off is NOT allowed." –  Ismael Miguel May 7 at 21:20
1  
@IsmaelMiguel I have provided my justification. "until the program is exited (any key, or alt+F4, mouse movement, etc.), after which things should turn back to normal. So shutting..." - the rule's intention has been satisfied. This will "turn it back on". Leaving aside the intention, it also satifies the literal meaning, since, despite Microsoft's terminology, this isn't really turning it off (timeouts on projectors, etc., aside), it's placing it into standby. –  Bob May 8 at 6:03

Python / Pygame 199 127 125

from pygame import*;display.set_mode((9,9),-1<<31);mouse.set_visible(0)
while 1:
 for e in event.get():
  if e.type==2:quit()

Thanks to some tips from ace.

share|improve this answer
    
Since ALT+F4 counts, I'd take also ^C counts, so you can skip a lot of bytes at the end. –  Lohoris May 7 at 11:48
1  
For ^C to work you need to be focused on the terminal, and in the program the pygame window is always focused due to pygame.FULLSCREEN Edit: One alternative would be to leave the program with no exit, which would require spamming the keyboard till your OS notices something is wrong. –  British Colour May 7 at 12:04
    
You can save some bytes by using from pygame import* instead. Also, I don't think fill((0,0,0)) is necessary since the default color is black. Then you can remove s altogether. I don't think display.flip() is needed either. Also, use one space for indentation instead of 4 can save you more spaces. Finally, instead of FULLSCREEN and KEYDOWN, you can use their numeric values, namely -1<<31 (-2147483648) and 2 respectively. –  ace May 7 at 19:25

Amiga assembly

ASM-One - 228 219 chars, 172 bytes compiled (168 bytes optimized)

It's been 20 years since I last coded a single line in Amiga assembly, so bear with me. :-)

The Amiga was a bit more involved than the PC in terms of setting up a blank screen, so tried to get rid of as much setup and teardown as possible. There's no disabling of interrupts or multitasking; no double WaitTOF; no view replacement; etc. I wouldn't even have written this for the quickest and dirtiest demo. Which means this:

  • is bad practice
  • may not be entirely safe
  • may not always work
  • even with those disclaimers, probably has stupid mistakes owing to 20 years of neglected assembly.

... although it's been tested on emulated A500 and A1200, with or without fast memory. Compiles to a standard executable. Mouse click exits.

l=$dff080
 move.l 4,a6
 lea g,a1
 jsr -408(a6)
 move.l d0,a1
 move.l 38(a1),d4
 jsr -412(a6)
 move.l #c,l
w:btst #6,$bfe001
 bne w
 move.l d4,l
 rts
g:dc.b "graphics.library",0
 SECTION d,DATA_C
c:dc 256,512,384,0,-1,-2

Less golfed:

COP1LC equ $dff080

    move.l  $4, a6          ; ExecBase
    lea     gfxname, a1
    jsr     -408(a6)        ; OpenLibrary (old, hence no need for clearing d0)
    move.l  d0, a1
    move.l  38(a1), d4      ; store copper list
    jsr     -414(a6)        ; CloseLibrary
                            ; Yeah, if I had a penny for the times I saw that left out
                            ; but I just... can't...

    move.l  #copper,COP1LC  ; write copper list

wait:
    btst    #6, $bfe001     ; Check mouse click
    bne     wait

    move.l  d4, COP1LC      ; restore copper list
    rts

gfxname:
    dc.b    "graphics.library", 0

    SECTION data, DATA_C
copper:
    dc.w $0100, $0200       ; disable bitplanes
    dc.w $0180, $0000       ; color 0 = black
    dc.w $ffff, $fffe       ; end
share|improve this answer
1  
Aaaah, the memories! Love it! –  RobIII May 8 at 20:09
    
Yeah, this was more of an excuse for a nostalgia trip than a real attempt at code golf - Amiga assembly will rarely compete with Perl or Python in terms of character count. Although I was a bit surprised it couldn't beat C# or Java. :) –  JimmiTh May 8 at 20:30

sh/X11 on Arch Linux, 26

b=/b*/*ht;$b =0;read;$b =7
share|improve this answer
    
you can probably shave a few chars with an alias and maybe using -set for both –  ardnew May 6 at 19:49
1  
Use xbacklight = 0 and xbacklight + 7. –  bb010g May 8 at 7:13
1  
29 bytes: x=xbacklight;$x +0;read;$x +7 –  nyuszika7h May 19 at 19:05
    
@nyuszika7h: Thanks! (Got it to 28, too!) –  minitech May 19 at 19:09

Bash, 37

Uses unclutter to hide the mouse pointer and a fullscreen session of xterm to black the screen. The cursor will reappear for a moment if you move it, but if you leave it alone the screen will be black until you press Ctrl+C.

It will take a few seconds for the mouse cursor to disappear (as long as you don't move it). If this isn't fast enough, add the -grab option to unclutter for an additional 6 chars.

unclutter&xterm -fu -bg black -e yes ''

WARNING: this will leave a process of unclutter running even after you press Ctrl+C, use killall unclutter to stop it.

Explanation

unclutter & launches unclutter. The & is there so we can get on with the next command instead of waiting for this one to terminate.

xterm -fullscreen launches XTerm, whose background is black by default.

The -e yes '' option causes XTerm to run yes '', thereby printing the empty string forever. This serves to hide the terminal cursor, and also provides the Ctrl+C functionality.

share|improve this answer
    
Screen gets completely white in my system. –  Vi. May 7 at 16:05
    
@Vi. that means your XTerm background colour is white. –  professorfish May 7 at 16:31
    
You can abbreviate "-fullscreen" to "-fu", and use "-bg black" to force black background color regardless of user preferences. –  semi-extrinsic May 14 at 12:17
    
You can remove the spaces around & to save 2 bytes. –  nyuszika7h May 19 at 19:01

Bash, 31 (or 52)

On a TTY, use the following script (assuming your default TTY background is black, which is true at least for Ubuntu 12.04 LTS):

setterm -foreground black
clear

Your TTY would still be fully functional even after using this script :)

If this isn't allowed, use the following (52 bytes):

x='setterm -foreground'
$x black
clear
read
$x white

And press Enter to terminate the script.

Special thanks to @nyuszika7h.

share|improve this answer
1  
For the second case: x='setterm -foreground';$x black;clear;read;$x white (52 bytes). –  nyuszika7h May 19 at 19:08

Lua + LÖVE (50)

love.mouse.setVisible()love.window.setFullscreen""

Both functions are supposed to take a boolean argument, yet this works.

share|improve this answer

BASH - 14 chars

pmset sleepnow does the job!

(typed into my Mac's Terminal)

share|improve this answer
    
You should specify the OS and/or other prerequisites in your answer. –  ace May 7 at 7:36
    
@ace answer edited :) –  Jugale May 7 at 11:48
    
Doesn't sleep shut the monitor down? –  Lohoris May 7 at 12:03

Sinclair BASIC - 28 chars

BORDER 0:PAPER 0:CLS:PAUSE 0

The thing about Sinclair BASIC was each keyword had it's own character code (taking up one byte), so this would actually take up 13 bytes including spaces.

share|improve this answer
    
Does this return the screen to normal after finishing? –  kitcar2000 May 9 at 16:02
    
@kitcar2000 - Thinking about it, no. I'd probably add ":NEW" at the end as a quick and dirty reset, taking it up to 32 chars/15 bytes –  Brian May 10 at 17:04
    
I think that it is only 10 bytes (12 with :NEW) as the commands are single bytes rather than a collection of characters. –  kitcar2000 May 10 at 17:19

Processing, 113

void setup(){noCursor();size(displayWidth, displayHeight);background(0);}boolean sketchFullScreen(){return true;}

I tried putting the code above onto draw() to save some bytes, but it didn't work. Press Alt-F4 to quit.

share|improve this answer

ZX Spectrum Basic (29 bytes)

1 FOR x=0 TO 255
2 FOR y=0 TO 175
3 PLOT x,y
4 NEXT y
5 NEXT x

Iterates over the screen, plotting black pixels which are automatically cleared when the program finishes.

The ZX Spectrum's edition of basic uses single bytes as commands and no newlines, if counting displayed characters you get 61 chars.

share|improve this answer

TI-BASIC

Shade(-10,10

Works both in the terminal (home screen) or as a program. Pressing ON or most other buttons returns to the terminal/home screen.

share|improve this answer

Commodore 64 (16 bytes)

ROL $A903
BRK
STA $D020
STA $D011
JSR $FF8A
JMP ($032C)

It has been more than 20 years since I used Turbo Assembler, so I can only provide source for use in VICE's monitor. Assemble this at $032C and save[1] through $033B. Reset and LOAD"PITCHDARK",8,1. Hit good ol' Runstop+Restore[2] to get back to normal.

How does it work?

Here's the true source:

032C 2E 03      .BY 2E 03
032E A9 00      LDA #$00
0330 8D 20 D0   STA $D020   ; set border color  
0333 8D 11 D0   STA $D011   ; set VIC blanking mode
0336 20 15 FD   JSR $FF8A   ; reset the vectors we trampled
0339 6C 2C 03   JMP ($032C) ; call the real CLALL

$032C is the kernal CLALL or "Close All Channels And Files" vector. As part of its cleanup, the BASIC LOAD command does a CLR which in turn calls CLALL. We replace the CLALL vector with a pointer to our own routine immediately after the vector. We set the border to black and cover the screen with the border, and then call RESTOR at $FF8A. The last vector replaced by RESTOR is SAVE at $0332-0333 which means the last 8 bytes are undisturbed. We then exit via the restored CLALL vector to continue LOAD's execution.

Thanks for this, it was fun trip down memory lane, relearning how to do an autorun program :)

[1] use save and not bsave so that load with ,1 works correctly
[2] Escape + PageUp in x64, probably.

share|improve this answer

Linux Shell Scripting (15)

In the true spirit of Earth Hour, this solution also activates a special power-saving mode on the computer itself in addition to blanking the screen, saving even more energy:

shutdown -P now

Users can exit this program by pressing the power key found on either their desktop keyboard or more commonly on a separate keyboard typically mounted to the front of the computer chassis, or sometimes integrated into the bezel.

Conveniently, most setups have the power key set as a hotkey for this action out-of-the-box.

share|improve this answer
5  
"So shutting down the computer or turning the power of the monitor off is not allowed" –  Ismael Miguel May 6 at 17:05
    
@IsmaelMiguel And a bootloader is any better? That is just a particular sort of config file, after all. –  AJMansfield May 6 at 17:07
2  
It was written in Assembly and compiled. If it was compiled, it is a program. And if a bootloader wasn't a program, how could it be ran? How could a system boot? –  Ismael Miguel May 6 at 17:15
    
@Ismael Miguel I think his point is that if it is a bootloader then you actually need to reboot your computer to run it, so it does not satisfy "after which things should turn back to normal." –  ace May 6 at 17:48
1  
@ace it turns back to normal if you run it without the floppy drive. –  Ismael Miguel May 6 at 19:54

Linux Shell Script (37)

As a famous meerkat says... "Simples, squeek"

#! /bin/sh
xset dpms force off
exit 0

Tested on Ubuntu 14.04 LTS. I've not done a code golf, and am unsure if my scoring is correct.

Alternatively, just type xset dpms force off into your linux console for 20.

share|improve this answer
2  
turning the power of the monitor off is not allowed –  Lohoris May 7 at 12:06
1  
This answer isn't valid, but on the bright side, your scoring is correct. :P (Also, you can save the space between #! and /bin/sh) –  undergroundmonorail May 8 at 14:45

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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