Campo escuro (lembrança da Hora do Planeta)

31

Seu objetivo é simples: o programa deve tornar a tela do seu computador totalmente preta .

Depois que o programa é iniciado, a tela deve rapidamente ficar completamente preta e permanecer até que o programa seja encerrado (qualquer tecla ou alt + F4, movimento do mouse etc.), após o qual as coisas devem voltar ao normal. Portanto, NÃO é permitido desligar o computador ou desligar o monitor . Nem um único pixel não preto deve estar visível durante esse período, nem mesmo um cursor piscando.

O usuário não deve fazer nenhuma preparação (mover o mouse para fora da tela, desconectar os cabos etc. ou a entrada do usuário após o início do programa), basta iniciar o programa.

Você pode assumir com segurança que o computador possui apenas um monitor conectado. Também assumimos um computador desktop ou notebook padrão, porque fazê-lo em um dispositivo específico sem um monitor normal seria muito simples.

Se você usar algum recurso externo (uma imagem em preto, um arquivo GUI etc.), o tamanho em bytes será adicionado ao tamanho do código.

Tudo bem se ele funciona apenas em uma família de sistemas operacionais, ou se requer opengl etc., mas é necessário desaprovar uma configuração de hardware muito específica.

Seu código fonte deve ser escrito em uma linguagem de programação, não apenas em um arquivo de configuração que algum outro programa (como um protetor de tela) usará.

vsz
fonte
9
Isso não vai funcionar em telas com pixels preso ...
Ismael Miguel
21
@IsmaelMiguel: você pode assumir com segurança uma tela em perfeitas condições de funcionamento. Caso contrário, poderíamos objetar outras perguntas no estilo de "e se um transistor na minha ALU estiver queimado e meu computador não puder fazer nenhuma matemática de ponto flutuante?" :)
vsz
5
Curiosidade: nas telas que não usam CRT nem contraste dinâmico, isso consumirá um pouco mais de eletricidade!
Ry-
2
real world application: Astronomy! lists.apple.com/archives/Carbon-dev/2008/May/msg00005.html
Not that Charles
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

Respostas:

22

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!

user12205
fonte
1
The kind of answer that makes you think: 'Why on earth didn't I think of that?'. :)
Alex Thornton
1
That's not really clearing the screen using bash.
Darth Egregious
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
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)
user12205
5
@ace, Golfed: /*/*/gn*d instead of gnome-screensaver-command will save about 16 bytes (idea by mniip)
Glenn Randers-Pehrson
31

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
Hannes Karppila
fonte
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!
Zach Mertes
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
Can you please explain how it works?
Mega Man
Why the cli and sti? Moves to SS automatically disable interrupts for the duration of the next instruction, and AX won't be changed if an interrupt happens before MOV SS,AX. Also, why not MOV AX, 0x13 instead of two MOVs?
Ruslan
Younger me didn't know how to write code properly. Current me probably doesn't know either.
Hannes Karppila
15

QBASIC (31)

SCREEN 7
WHILE INKEY$=""
WEND
Darth Egregious
fonte
14
@TheGuywithTheHat I finally found a use for my windows 3.1 vm.
Darth Egregious
3
Wow seeing that WEND brought back memories
Claudiu
@user973810 You mean QB64.
nyuszika7h
14

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();
    }
}
Geobits
fonte
11

Applesoft ][ BASIC (17)

1 HGR2:GET X:TEXT
Geoff Reedy
fonte
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
11

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

mniip
fonte
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”
Ry-
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
1
@minitech Oh. Well, fixed...
mniip
This doesn't work at all for me. If I do "C=/s*/*/*/*/bess;(A=$(cat $C);echo 0;cat;echo $A)|tee $C" from the bash prompt I get cat: /s*/*/*/*/bess: No such file or directory tee: /s*/*/*/*/b*ess: No such file or directory
@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
8

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

Vereos
fonte
1
Maybe something like chrome --kiosk 'data:text/html,<style>body{background:#000;cursor:none;}</style>' can work without additional file?
Vi.
Means when using file: shceme you get no URL bar visible, but with data: scheme there is URL bar?
Vi.
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.
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>
user12205
1
I think you should use chrome in your answer rather than chromium
user12205
7

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.

ProgramFOX
fonte
2
You can replace System.Drawing.Color.Black, FormWindowState.Maximized, FormWindowState.Maximized and FormBorderStyle.None with their corresponding values.
Ismael Miguel
@IsmaelMiguel: Thanks, I updated the FormWindowState and the FormBorderStyle! I couldn't update the Color, because that's not an enum.
ProgramFOX
Try Color.Black. It should work right away. Or BackColor=This.ForeColor, which MIGHT work too.
Ismael Miguel
@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
Try using System; then new Windows.Forms.Form and BackColor=Drawing.Color.Black. It MIGHT work! And save a few bytes.
Ismael Miguel
5

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 https://stackoverflow.com/a/713519/1030702

Bob
fonte
"So shutting down the computer or turning the power of the monitor off is NOT allowed."
Ismael Miguel
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
4

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
JimmiTh
fonte
1
Aaaah, the memories! Love it!
RobIII
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
4

Python / Pygame 199 127 125 92

from pygame import*;display.set_mode((9,9),-1<<31);mouse.set_visible(0)
while 1:event.pump()

Thanks to some tips from ace.

Harry Beadle
fonte
Since ALT+F4 counts, I'd take also ^C counts, so you can skip a lot of bytes at the end.
o0'.
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.
Harry Beadle
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.
user12205
4

TI-BASIC, 7 6

Shade(Ymin,Ymax

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

Timtech
fonte
Can be one byte smaller (and work even if the graph screen window is changed) as Shade(Ymin,Ymax.
lirtosiast
@ThomasKwa You're right, thanks for the tip!
Timtech
3

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.

the eels have eyes
fonte
3

sh/X11 on Arch Linux, 26

b=/b*/*ht;$b =0;read;$b =7
Ry-
fonte
you can probably shave a few chars with an alias and maybe using -set for both
ardnew
1
Use xbacklight = 0 and xbacklight + 7.
bb010g
1
29 bytes: x=xbacklight;$x +0;read;$x +7
nyuszika7h
@nyuszika7h: Thanks! (Got it to 28, too!)
Ry-
3

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.


fonte
Screen gets completely white in my system.
Vi.
@Vi. that means your XTerm background colour is white.
You can abbreviate "-fullscreen" to "-fu", and use "-bg black" to force black background color regardless of user preferences.
semi-extrinsic
You can remove the spaces around & to save 2 bytes.
nyuszika7h
3

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.

user12205
fonte
1
For the second case: x='setterm -foreground';$x black;clear;read;$x white (52 bytes).
nyuszika7h
2

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.

segfaultd
fonte
2

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.

kitcar2000
fonte
2

Lua + LÖVE (50)

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

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

Seeker14491
fonte
2

QBasic, 9 bytes

CLS:SLEEP

CLS clears the screen, SLEEP without any arguments holds execution until a key is pressed.

steenbergh
fonte
2

SmileBASIC, 15 bytes

XSCREEN 4
EXEC.

Pressing START or SELECT will end the program.

XSCREEN 4 sets the display mode to show a 320*480 image spanning both screens. This should clear everything, so an ACLS is not required. EXEC. makes the code repeat by constantly running the program in slot 0. I wasn't able to do XSCREEN 4EXEC. because you can't have a number directly before E

12Me21
fonte
1

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.

Brian
fonte
Does this return the screen to normal after finishing?
kitcar2000
@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
I think that it is only 10 bytes (12 with :NEW) as the commands are single bytes rather than a collection of characters.
kitcar2000
1

SmileBASIC, 23 bytes

Runs forever until the program is force-killed with START or SELECT. This makes both screens completely black, going so far to disable 3D (thus turning off the 3D LED on o3DS.)

ACLS:XSCREEN 3@L GOTO@L
snail_
fonte
1

Most POSIX compatible shells (at least bash and zsh), 21

Needs to be run on a tty

tput civis;clear;read

First command hides the cursor, second command clears the screen (duh) and third command reads a line of text

therealfarfetchd
fonte
0

BASH - 14 chars

pmset sleepnow does the job!

(typed into my Mac's Terminal)

Max Chuquimia
fonte
You should specify the OS and/or other prerequisites in your answer.
user12205
@ace answer edited :)
Max Chuquimia
Doesn't sleep shut the monitor down?
o0'.
0

Bash: 48 characters

eval xrandr\ --output\ DP1\ --{off,auto}\;read\;

CW because not clear whether it qualifies due to the way it works:

  • The produced black screen is real power saving: it cuts off information sending to display 1.
  • Many computer displays when detect signal loss, will temporarily or periodically show their own notice.

(Note that DP1 is the first connected display. If you have a laptop, its embedded display is eDP1.)

manatwork
fonte
0

HTML Application (.hta), 102 bytes

<HTA:APPLICATION CAPTION=no innerborder=0 border=dialog scroll=0 windowstate=maximize><body bgcolor=0>
user2428118
fonte
0

TI-80 BASIC, 5 bytes

ZOOM OUT
ZOOM OUT
GRIDON
12Me21
fonte
0

Chip-8, 0 bytes

[T]he original Chip-8 interpreter began execution from 0x01FC. The interpreter includes two permanent Chip-8 instructions at this location that are always executed at the start of every programme. The first of these, 0x00E0, clears the display RAM by setting all the bits to zero. The second, 0x004B, calls a machine language routine within the interpreter that switches the VIP’s display on.

Source: http://laurencescotford.co.uk/?p=75

12Me21
fonte