text:
Working Minesweeper
Similar to generating minesweeper grids, although the challenge is to make a working minesweeper grid.  This will be longer code than normal (I think).
more information on minesweeper.

Minesweeper is a logic game found on most OS's. The goal of the game is to determine where the mines are on a grid, given numbers indicating the number of mines around that spot.

Required features:
-Randomized mine generation
-8x8 field with 10 mines
-Mine and "unknown" flags
-Reveal nearby blank spaces when a blank space has been revealed.
-Input and output code: It must be playable.  (Input and output code counts in the total)

Note on scoring:
Anything that is needed to make the program work is counted.
If it can be deleted and not affect the program, get rid of it.
I will occasionally update the selected answer to shorter programs if needed.

I came across a more specific version of this problem in computer science class: make a working version with the shortest number of lines in visual basic (I got 57 lines), and I thought it will be an interesting challenge for code golf.  If there are any suggestions for improving the question, please comment.  Shortest code in bytes wins.

Do we need to allow for mine and "unknown" flags? Also, does UI code count towards the total?

Also, I assume we're counting bytes instead of lines, since several languages could make this as a one-liner.

Edited original post to clarify uncertainties.

I edited the title, cause I first thought you're looking for solutions in functional programming languages only. I renamed to 'working' instead of 'functional', while it is quiete normal, that we look for working solutions - what else?

Python 2.7 (487C)
"""
char meaning:
    '?': unknown flag
    '!': mine flag
    'x': default
how to play:
    Input 3 chars each time. The first char is the action
    and the rest form a position. For example, '013' means
    uncover grid (1,3), '110' means flag the grid (1,0).

    The top-left corner is (0, 0), bottom-left (7,0), etc.

    Player will lose after uncover a mine, the program will
    output "Bom". If the Player uncovers all grid that do
    not contain a mine, he wins and the program will output
    "Win".
"""
import random as Z
S=sum
M=map
T=range
P=[(i,j)for i in T(8)for j in T(8)]
C=dict(zip(T(-3,9),'?!x012345678'))
m={p:-1 for p in P}
h=Z.sample(P,10)
def U(p):
 if m[p]>=0:return 0
 n=filter(lambda(c,d):0<max(abs(p[0]-c),abs(p[1]-d))<2,P)
 m[p]=s=S((x in h)for x in n)
 return(1 if s else S(M(U,n))+1,-1)[p in h]
s=u=0
while(s<54)&(u>-1):
 f,i,j=M(int,raw_input(''.join((C[m[x]]+'\n '[x[1]<7])for x in P)))
 p=i,j;c=m[p]
 if f*(c<0):m[p]=-1-(-c)%3
 else:u=U(p);s+=u
print'WBionm'[s<54::2]

Full game experience:
x x x x x x x x
x x x x x x x x
x x x x x x x x
x x x x x x x x
x x x x x x x x
x x x x x x x x
x x x x x x x x
x x x x x x x x
000
0 0 1 x x x x x
0 0 2 x x x x x
0 0 2 x x x x x
0 0 1 2 x x x x
0 0 0 1 x x x x
1 1 0 2 x x x x
x 1 0 2 x x x x
x 1 0 1 x x x x
070
0 0 1 x x x x x
0 0 2 x x x x x
0 0 2 x x x x x
0 0 1 2 x x x x
0 0 0 1 x x x x
1 1 0 2 x x x x
x 1 0 2 x x x x
1 1 0 1 x x x x
123
0 0 1 x x x x x
0 0 2 x x x x x
0 0 2 ! x x x x
0 0 1 2 x x x x
0 0 0 1 x x x x
1 1 0 2 x x x x
x 1 0 2 x x x x
1 1 0 1 x x x x
113
0 0 1 x x x x x
0 0 2 ! x x x x
0 0 2 ! x x x x
0 0 1 2 x x x x
0 0 0 1 x x x x
1 1 0 2 x x x x
x 1 0 2 x x x x
1 1 0 1 x x x x
003
0 0 1 1 x x x x
0 0 2 ! x x x x
0 0 2 ! x x x x
0 0 1 2 x x x x
0 0 0 1 x x x x
1 1 0 2 x x x x
x 1 0 2 x x x x
1 1 0 1 x x x x
004
0 0 1 1 1 x x x
0 0 2 ! x x x x
0 0 2 ! x x x x
0 0 1 2 x x x x
0 0 0 1 x x x x
1 1 0 2 x x x x
x 1 0 2 x x x x
1 1 0 1 x x x x
014
0 0 1 1 1 x x x
0 0 2 ! 4 x x x
0 0 2 ! x x x x
0 0 1 2 x x x x
0 0 0 1 x x x x
1 1 0 2 x x x x
x 1 0 2 x x x x
1 1 0 1 x x x x
154
0 0 1 1 1 x x x
0 0 2 ! 4 x x x
0 0 2 ! x x x x
0 0 1 2 x x x x
0 0 0 1 x x x x
1 1 0 2 ! x x x
x 1 0 2 x x x x
1 1 0 1 x x x x
044
0 0 1 1 1 x x x
0 0 2 ! 4 x x x
0 0 2 ! x x x x
0 0 1 2 x x x x
0 0 0 1 1 x x x
1 1 0 2 ! x x x
x 1 0 2 x x x x
1 1 0 1 x x x x
034
0 0 1 1 1 x x x
0 0 2 ! 4 x x x
0 0 2 ! x x x x
0 0 1 2 3 x x x
0 0 0 1 1 x x x
1 1 0 2 ! x x x
x 1 0 2 x x x x
1 1 0 1 x x x x
035
0 0 1 1 1 x x x
0 0 2 ! 4 x x x
0 0 2 ! x x x x
0 0 1 2 3 3 x x
0 0 0 1 1 x x x
1 1 0 2 ! x x x
x 1 0 2 x x x x
1 1 0 1 x x x x
045
0 0 1 1 1 x x x
0 0 2 ! 4 x x x
0 0 2 ! x x x x
0 0 1 2 3 3 x x
0 0 0 1 1 1 x x
1 1 0 2 ! x x x
x 1 0 2 x x x x
1 1 0 1 x x x x
055
0 0 1 1 1 x x x
0 0 2 ! 4 x x x
0 0 2 ! x x x x
0 0 1 2 3 3 x x
0 0 0 1 1 1 x x
1 1 0 2 ! 2 x x
x 1 0 2 x x x x
1 1 0 1 x x x x
124
0 0 1 1 1 x x x
0 0 2 ! 4 x x x
0 0 2 ! ! x x x
0 0 1 2 3 3 x x
0 0 0 1 1 1 x x
1 1 0 2 ! 2 x x
x 1 0 2 x x x x
1 1 0 1 x x x x
164
0 0 1 1 1 x x x
0 0 2 ! 4 x x x
0 0 2 ! ! x x x
0 0 1 2 3 3 x x
0 0 0 1 1 1 x x
1 1 0 2 ! 2 x x
x 1 0 2 ! x x x
1 1 0 1 x x x x
174
0 0 1 1 1 x x x
0 0 2 ! 4 x x x
0 0 2 ! ! x x x
0 0 1 2 3 3 x x
0 0 0 1 1 1 x x
1 1 0 2 ! 2 x x
x 1 0 2 ! x x x
1 1 0 1 ! x x x
074
0 0 1 1 1 x x x
0 0 2 ! 4 x x x
0 0 2 ! ! x x x
0 0 1 2 3 3 x x
0 0 0 1 1 1 x x
1 1 0 2 ! 2 x x
x 1 0 2 ! x x x
1 1 0 1 1 x x x
125
0 0 1 1 1 x x x
0 0 2 ! 4 x x x
0 0 2 ! ! ! x x
0 0 1 2 3 3 x x
0 0 0 1 1 1 x x
1 1 0 2 ! 2 x x
x 1 0 2 ! x x x
1 1 0 1 1 x x x
005
0 0 1 1 1 1 x x
0 0 2 ! 4 x x x
0 0 2 ! ! ! x x
0 0 1 2 3 3 x x
0 0 0 1 1 1 x x
1 1 0 2 ! 2 x x
x 1 0 2 ! x x x
1 1 0 1 1 x x x
015
0 0 1 1 1 1 x x
0 0 2 ! 4 4 x x
0 0 2 ! ! ! x x
0 0 1 2 3 3 x x
0 0 0 1 1 1 x x
1 1 0 2 ! 2 x x
x 1 0 2 ! x x x
1 1 0 1 1 x x x
126
0 0 1 1 1 1 x x
0 0 2 ! 4 4 x x
0 0 2 ! ! ! ! x
0 0 1 2 3 3 x x
0 0 0 1 1 1 x x
1 1 0 2 ! 2 x x
x 1 0 2 ! x x x
1 1 0 1 1 x x x
036
0 0 1 1 1 1 x x
0 0 2 ! 4 4 x x
0 0 2 ! ! ! ! x
0 0 1 2 3 3 3 x
0 0 0 1 1 1 x x
1 1 0 2 ! 2 x x
x 1 0 2 ! x x x
1 1 0 1 1 x x x
046
0 0 1 1 1 1 x x
0 0 2 ! 4 4 x x
0 0 2 ! ! ! ! x
0 0 1 2 3 3 3 2
0 0 0 1 1 1 0 0
1 1 0 2 ! 2 0 0
x 1 0 2 ! 2 0 0
1 1 0 1 1 1 0 0
127
0 0 1 1 1 1 x x
0 0 2 ! 4 4 x x
0 0 2 ! ! ! ! !
0 0 1 2 3 3 3 2
0 0 0 1 1 1 0 0
1 1 0 2 ! 2 0 0
x 1 0 2 ! 2 0 0
1 1 0 1 1 1 0 0
007
0 0 1 1 1 1 x 1
0 0 2 ! 4 4 x x
0 0 2 ! ! ! ! !
0 0 1 2 3 3 3 2
0 0 0 1 1 1 0 0
1 1 0 2 ! 2 0 0
x 1 0 2 ! 2 0 0
1 1 0 1 1 1 0 0
017
0 0 1 1 1 1 x 1
0 0 2 ! 4 4 x 3
0 0 2 ! ! ! ! !
0 0 1 2 3 3 3 2
0 0 0 1 1 1 0 0
1 1 0 2 ! 2 0 0
x 1 0 2 ! 2 0 0
1 1 0 1 1 1 0 0
016
Win

The last step is dangerous, though.

This is definitely too old to do anything, but you can remove space in -1 for... and 1 if... to save two bytes.

(note that the score is not counting the documentation and counting the trailing newline)

Javascript, 978 bytes (824 without CSS)
http://jsbin.com/otayez/6/
Checklist:
Randomized mine generation - yes
8x8 field with 10 mines - yes
Mine flags - Yes
"unknown" flags - no
Reveal nearby blank spaces when a blank space has been revealed. - yes
Input and output code: It must be playable. - yes

JS:
(function(){
    f=Math.floor;r=Math.random;b=8,s=[-1,0,1],o='',m='*',l=0;

    for(g=[i=b];i;)g[--i]=[0,0,0,0,0,0,0,0];
    for(i=10,a=f(r()*64);i--;g[f(a/b)][a%b]=m)while(g[f(a/b)][a%b])a=f(r()*64);
    for(i=64;i--;z.id='b'+(63-i),c.appendChild(z))z=document.createElement('button');
    for(d=b;d--;)
      for(r=b;r--;)
        s.map(function(y){
          s.map(function(x){
            if(g[d][r]!=m&&g[d+y]&&g[d+y][r+x]==m)g[d][r]++;
          });
        });

    c.onclick=function(e){
        var t=e.target,
            i=t.id.slice(1),
            x=i%b,
            y=f(i/b),
            n=t.className=='b';

      if(t.innerHTML||(n&&!e.ctrlKey))return;
      if(e.ctrlKey)return t.className=(n?'':'b')

      if(q(x,y))alert('boom')
      if(l==54)alert('win')
    };
  function q(x,y){
    if(x<0||x>7||y<0||y>7)return;

    var p=y*b+x,
        v=g[y][x],
        t=document.all['b'+p];

    if(v!=m&&!t.innerHTML){
      t.innerHTML=g[y][x];
      t.className='f';
      l++;
      if(!v){t.className='z';s.map(function(d){s.map(function(r){q(x+r,y+d)})})}
    }
    return v==m
  }
})();

MiniJS 812 bytes:
f=Math.floor;r=Math.random;b=8,s=[-1,0,1],o='',m='*',l=0,h='b';for(g=[i=b];i;)g[--i]=[0,0,0,0,0,0,0,0];for(i=10,a=f(r()*64);i--;g[f(a/b)][a%b]=m)while(g[f(a/b)][a%b])a=f(r()*64);for(i=64;i--;z.id=h+(63-i),c.appendChild(z))z=document.createElement('button');for(d=b;d--;)for(r=b;r--;)s.map(function(y){s.map(function(x){if(g[d][r]!=m&&g[d+y]&&g[d+y][r+x]==m)g[d][r]++})});c.onclick=function(e){var t=e.target,i=t.id.slice(1),n=t.className==h;if(t.innerHTML||(n&&!e.ctrlKey))return;if(e.ctrlKey)return t.className=(n?'':h);if(q(i%b,f(i/b)))alert('boom');if(l==54)alert('win')};function q(x,y){if(x<0||x>7||y<0||y>7)return;var p=y*b+x,v=g[y][x],t=document.all[h+p];if(v!=m&&!t.innerHTML){t.innerHTML=g[y][x];t.className='f';l++;if(!v){t.className='z';s.map(function(d){s.map(function(r){q(x+r,y+d)})})}}return v==m}

HTML 12 bytes
<div id="c">

The CSS isn't necessary from a functionality standpoint, but is from a usability standpoint:
#c{
  width:300px;
  height:300px;
}
button{
  width:12.5%;
  height:12.5%;
  line-height:30px;
}
.f,.z{
  background:#fff;
  border:solid 1px #fff;
}
.z{
  color:#fff;
}
.b{background:#f00}

Mini CSS 154 bytes:
#c{width:300px;height:300px}button{width:12.5%;height:12.5%;line-height:30px}.f,.z{background:#fff;border:solid 1px #fff}.z{color:#fff}.b{background:#f00}

with "unknown" flags: http://jsbin.com/otayez/10

C, 568, 557, 537
Checklist:
  Randomized mine generation - yes
  8x8 field with 10 mines - yes
  Mine and "unknown" flags - yes
  Reveal nearby blank spaces when a blank space has been revealed. - yes
  Input and output code: It must be playable. - yes

Further to playable:
  Win detection (found all mines, or revealed all empties)
  Bang detection (hit a mine)
  Game terminates.

Output format:
  # - unrevealed
  ! - a flagged mine
  * - a mine
  (number) - number of neighbouring mines
  ? - unknown flag

Input format:
  x y f
  - where x is 0..7, y is 0..7 (origin upper-left)
  - f is 0 to open up, 1 to flag a mine, and 2 to flag a unknown

example game:
./a.out
5 5 0
# 1 0 0 0 2 # #
# 1 0 0 0 2 # #
# 1 0 0 0 1 1 1
# 1 0 0 0 0 0 0
# # 1 0 0 0 1 1
# # 1 0 0 0 1 #
# # # 1 2 1 # #
# # # # # # # #
6 1 1
# 1 0 0 0 2 # #
# 1 0 0 0 2 ! #
# 1 0 0 0 1 1 1
# 1 0 0 0 0 0 0
# # 1 0 0 0 1 1
# # 1 0 0 0 1 #
# # # 1 2 1 # #
# # # # # # # #
7 5 0
# 1 0 0 0 2 # #
# 1 0 0 0 2 ! #
# 1 0 0 0 1 1 1
# 1 0 0 0 0 0 0
# # 1 0 0 0 1 1
# # 1 0 0 0 1 *
# # # 1 2 1 # 1
# # # # # # # #
bang!

code:
// 8x8 grid but with padding before first row, after last row, and after last column, i.e. its 9x10
m[99]; // 0=empty,1=mine
u[99]; // 0=revealed,1=unrevealed,2=flag,3=unknown

// count neighbouring mines (8way)
c(i){return m[i-8]+m[i-9]+m[i-10]+m[i+8]+m[i+9]+m[i+10]+m[i-1]+m[i+1];}

// reveal (4way)
r(i){
    if(u[i]){
        u[i]=0;
        if(!c(i))r(i-9),r(i+9),r(i+1),r(i-1);
    }
}

i,x,y,f,e;
main(){
    // place 10 mines
    for(srand(time(0));i<10;){
        x=rand()%64;
        x+=9+x/8;
        if(!m[x]){
            m[x]=1;
            i++;
        }
    }
    for(;y<64;y++)u[y+9+y/8]=1; // mark visible grid as being unrevealed

    while(!e){
        // read input 0..7 0..7 0..2
        scanf("%d%d%d",&x,&y,&f);
        i=x+9+y*9;
        if(f)u[i]=f==1?2:u[i]==3?1:3;else r(i); // flag, toggle unknown/unrevealed, open

        // show grid and calc score
        for(y=f=x=0;x<64;x++){
            i=x+9+x/8;
            putchar(u[i]?" #!?"[u[i]]:m[i]?42:48+c(i)); // 42='*', 48='0'
            putchar(x%8==7?10:32);
            if(!u[i])y+=m[i]?-99:1;   // y = number of correctly open
            if(u[i]==2)f+=m[i]?1:-99; // f = number of correct mines
        }
        if(y<0||y==54||f==10)e=puts(y<0?"bang!":"win!"); // 54 = 64-10
    }
}

I tried to add the grid padding, but it made my program longer :P Good job.

does for(x=64;x--;)... work for c?

Mathematica 566 548 1056
Edit: This is a complete rewrite. I gave up trying to obtain the shortest code and decided instead to build in the features that made most sense.
r indicates the number of rows in the grid. c indicates the number of columns in the grid.
m: number of mines.
The game is played by mouse-clicking on the buttons. If the player clicks on a mine, the cell turns black and the program prints "You Lose!"
The checkbox "u" allows the player to peek at the complete solution at any time.
The flags, "?" and "!" can be placed in any cell as desired.
DynamicModule[{s, x, f, l},
Manipulate[
Column[{
Grid[s],
If[u, Grid@f, Null]
}],
Grid[{{Control@{{r, 8}, 4, 16, 1, PopupMenu},
 Control@{{c, 8}, 4, 16, 1, PopupMenu},
 Control@{{m, 10}, 1, 50, 1, PopupMenu}},
{Button["New", i],
 Control@{{e, 0}, {0 -> "play", 1 -> "?", 2 -> "!"}, SetterBar},
 Control@{{u, False}, {True, False}}}}],
 Deployed -> True,

 Initialization :>
 (p = ReplacePart;
  q = ConstantArray;
  z = Yellow;
  w = White;
  b := Array[Button["  ", v[{#, #2}], Background -> z] &, {r, c}];
  a := RandomSample[l = Flatten[Array[List, {r, c}], 1], m];
  d[m1_] :=
   p[ListConvolve[BoxMatrix@1, p[q[0, {r, c}], (# -> 1) & /@ m1], 2,
    0], (# -> "*") & /@ (x)];
  n[y_] := Complement[Select[l, ChessboardDistance[y, #] == 1 &], x];
  d[m1_] :=
  p[ListConvolve[BoxMatrix@1, p[q[0, {r, c}], (# -> 1) & /@ m1], 2,
    0], (# -> "*") & /@ (x)];

  v[{r_, c_}] :=
   Switch[e,
    1, If[s[[r, c, 3, 2]] == z,
     s = p[s, {{r, c, 1} -> If[s[[r, c, 1]] == "?", "  ", "?"]}],
     Null],

    2, If[s[[r, c, 3, 2]] == z,
    s = p[s, {{r, c, 1} -> If[s[[r, c, 1]] == "!", "  ", "!"]}],
    Null],
    3, Null,

    0, Switch[f[[r, c]],
     "*", (Print["You lose!"]; (s = p[s, {r, c, 3, 2} -> Black])),
     0, (s = p[s, {{r, c, 1} -> "  ", {r, c, 3, 2} -> w}];
      f = p[f, {{r, c} -> ""}]; v /@ n[{r, c}]),
     "  ", Null,
     _, (s = p[s, {{r, c, 1} -> f[[r, c]], {r, c, 3, 2} -> w}])]];

   i :=
   (x = a;s = b;f = d[x]);i) ] ]

Initial State

At a later point...

The 'new' button is probably costing you a bunch of characters.

And it doesn't look like you have flagging implemented yet.

I'm not sure what you mean by flagging. Do you mean an option to allow the player to place a question mark on a cell? BTW, the "New button costs about 25 chars".

The player should be able to place a "flag" on a square they think is a mine, or a "?" on a square they are uncertain about.

@Shmiddty  Flags are now implemented (along with a few other things).

Python (502 566)
Checklist:
Randomized mine generation - yes
8x8 field with 10 mines - yes
Mine and "unknown" flags - yes
Reveal nearby blank spaces when a blank space has been revealed. - yes
Input and output code: It must be playable. - yes

It has a win detector as well.
Input is given while the game is running, with (f, x, y). (x, y) is the coordinates of the grid selection, f is whether you want to flag or not. (0, 0, 0) would open up (0, 0), and (1, 2, 3) would flag (2, 3). Flagging works in a cycle: flagging a square twice gives a question mark.
(number) - number of mines
(space) - unexplored
. - 0 mines
! - flag
" - question
import random
A=[-1,0,1]
R=lambda x:[x+i for i in[-9,-8,-7,-1,1,7,8,9]if(0<x+i<64)&([i,x%8]not in([7,0],[-7,7],[-1,0],[1,7]))]
M=lambda p:sum(G[i]=='*'for i in R(p))
def V(p):
 m=M(p);G[p]=`m`if m else'.'
 if m>0:return
 for c in R(p):
  if' '!=G[c]:continue
  m=M(c);G[c]=`m`
  if m==0:G[c]='.';V(c)
G=[' ']*54+['*']*10
random.shuffle(G)
while' 'in`G`:
 for i in range(8):print[j.replace('*',' ')[0]for j in G[8*i:8*i+8]]
 i=input()[::-1];a=i[0]*8+i[1];b=G[a]
 if i[2]:G[a]=(chr(ord(b[0])+1)if'"'!=b[0]else' ')+b[1:];continue
 if'*'==b:print'L';break
 if'!'!=b:V(a)

Needs to be improved: function R [get all squares around item p] (101 chars), printing (69 chars), flagging (72 chars)

Dyalog APL, 113 bytes
{⎕←1 0⍕c+○○h⋄10=+/,h:1⋄m⌷⍨i←⎕:0⋄∇{~⍵⌷h:0⋄(⍵⌷h)←0⋄0=⍵⌷c:∇¨(,⍳⍴m)∩⍵∘+¨,2-⍳3 3⋄0}i}h←=⍨c←{⍉3+/0,⍵,0}⍣2⊢m←8 8⍴10≥?⍨64
non-competing: no "mine" and "unknown" flags
prints * for unopened cells and digits for opened (including 0)
repeatedly asks the user for the 1-based coordinates of a cell to open
ultimately outputs 0 on failure (mine opened) or 1 on success (only 10 unopened left)
looks like this:
********
********
********
********
********
********
********
********
⎕:
      1 1
00000000
11012321
*112****
********
********
********
********
********
⎕:
      3 8
00000000
11012321
*112***1
********
********
********
********
********
⎕:
      4 7
00000000
11012321
*112***1
******3*
********
********
********
********
⎕:

...


text:
(simple) variable and scope simulator
Based on this closed question on stack overflow, what is the shortest way to stimulate scope for variables in an input.  For simplicity, print is replaced with >.
copying critical information from the linked source:

[ and ] start and end a new scope.

Within scopes any changes to a variable outside of that scope is not permanent and is reverted when the scope has left, but the outer values are used to determine if a variable is undefined and its starting value.

Input will always start with [ and will end with matching ]
If its not defined then value should be 0
All input that is not a variable is a number with no decimal points. as in 10 or 582
> a means print the contents of a
a 10 assigns 10 to a
a b assigns the contents of b to a
Variables should be considered strings: one 1 is valid syntax
It is not required for the input to contain the print command >

Note on scoring:
You may chose how to input and output the "code", but it should be explained in the answer.

I answered this on the linked page in java, but I did not go for shortest code.
Comment any suggestions or questions, so I can improve my future posts.  Shortest code by character wins.  Good luck.

What is meant by "All input that is not a variable is an integer"? And why mention Java, which is actually quite different?

The interesting thing is, > is a special variable that outputs its value when assigned to!

Python 2, 165
def f(v):
 while 1:
    s=raw_input().split()
    if'['in s:f(dict(v))
    elif']'in s:break
    elif'>'in s:print v.get(s[1],0)
    else:v[s[0]]=v.get(s[1],s[1])
raw_input()
f({})

Character count assumes tabs are used for the second level of indentation.

Nice solution. c=b in v and v[b]or 0 can be replaced with c=v.get(b,0).

Thanks. Great suggestion; using .get helps a lot.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Cropping an image succintly
I am constantly frustrated by how complicated it is to write graphical programs that would have been only a few lines of code 20+ years ago.  Since the invention of the mouse this has become even worse it seems.  I was hoping someone could put me out of my misery and show the shortest code to do the following really basic "modern" operations.
The code will read in an image in any sensible format of your choosing (png, jpg, etc.), display it on the screen, allow you to choose a rectangular region with your mouse and then just save the selected region as an image file.
You are free to use any programming language and any library which hasn't been written especially for this competition.  Both should be freely (in both senses) online.  The code should be runnable in linux.
To start things off.... here is a very lightly golfed solution in python modified from code to Andrew Cox from https://stackoverflow.com/questions/601874/digital-image-cropping-in-python which takes 1294 1101 characters.
import pygame, sys
from PIL import Image
pygame.init()

def displayImage( s, px, t):
    s.blit(px, px.get_rect())
    if t:
        pygame.draw.rect( s, (128,128,128), pygame.Rect(t[0], t[1], pygame.mouse.get_pos()[0] - t[0], pygame.mouse.get_pos()[1] - t[1]))
    pygame.display.flip()

def setup(path):
    px = pygame.image.load(path)
    s = pygame.display.set_mode( px.get_rect()[2:] )
    s.blit(px, px.get_rect())
    pygame.display.flip()
    return s, px

def mainLoop(s, px):
    t = None
    b = None
    runProgram = True
    while runProgram:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                runProgram = False
            elif event.type == pygame.MOUSEBUTTONUP:
                if not t:
                    t = event.pos
                else:
                    b = event.pos
                    runProgram = False
        displayImage(s, px, t)
    return ( t + b )

s, px = setup(sys.argv[1])
left, upper, right, lower = mainLoop(s, px)
im = Image.open(sys.argv[1])
im = im.crop(( left, upper, right, lower))
im.save(sys.argv[2])

I believe it is traditional to give a time limit, so I will accept the best answer in exactly one week's time.
Current count

Octave - 44 + 15 = 59 characters
R - 305 characters
Python - 343 characters
Java - 560 characters

You should golf your program a little bit more :) Use one letter variables and as little whitespace as possible. Also, you don't need the if __name__ == "__main__": if you're just writing a program.

@beary605 Thanks.  I don't want to obfuscate it too much as I was hoping that it might inspire someone to make a great alternative solution.  I suspect but don't know that the key may be to find a language+library pair that does almost the work for you.

I don't like "You are free to use any (..) libraries you like as long as they are available freely (..) online." This means I can write a library that does all the work, make it available online, and then publish a one-line program in an answer here that does nothing but call the library!

@MrLister Thanks you are right. I need to fix that. Is the new version better?

@felipa good enough.

in bash, I just type gimp

@boothby :)  I am not sure that is in the spirit of the game.

@felipa Octave should be 44+15!

Octave - 59 chars
pkg load image;imwrite(imcrop(imread(input(''))),input(''))

MATLAB - 44 chars (not free, out of the contest)
imwrite(imcrop(imread(input(''))),input(''))

MATLAB seemed spot-on for this. Requires the Image Processing Toolbox (or package image 2.0.0 from Octave Forge). Usage:

Write at prompt 'input-filename' (single quotes included)
MATLAB: Drag from top-left to bottom-right corner and double click the rectangle.
Octave: Click top-left and bottom-right corner
Write 'output-filename' (between single quotes too)

This code doesn't work for me in octave. I am not sure which mouse buttons I am meant to select with but I always get "subscript indices must be either positive integers or logicals" in any case.

It works in MATLAB, but apparently not in Octave. My bad for not testing it. I'll fix it ASAP.

@felipa I fixed it and shaved some chars. Works fine with Octave + package image 2.0.0. Am I allowed to assume in/out filenames are in a var instead of the ugly input('')s?

@koaD I got it to work in the end. You might have to add "pkg load image" strictly speaking.

@koaD You can assume the filenames are given on the command line but the code you give should be self contained and runnable as is.

@felipa in MATLAB package imports are not needed, but since the rules require free software I guess I have to stick to Octave. Edited. (btw, I'm kaoD, not koaD! :P)

Are you supposed to count blank spaces? I am not clear on the golfing rules. tr -d '[[:blank:]]' which is used below removes them I think.

@felipa as far as I know, spaces are counted usually (I did count spaces). You make the rules tho, so it's up to you.

Java (580 560 559)
import java.awt.*;import javax.imageio.*;public class R extends
Frame{static java.awt.image.BufferedImage i;int
x,y,w,h;{setSize(i.getWidth(),i.getHeight());setUndecorated(0<1);show();}public static void
main(String[]a)throws Exception{i=ImageIO.read(System.in);new R();}public boolean handleEvent(Event
e){if(e.id==501){x=e.x;y=e.y;}if(e.id==502){w=e.x-x;if(w<0)x-=w=-w;h=e.y-y;if(h<0)y-=h=-h;try{ImageIO.write(i.getSubimage(x,y,w,h),"png",System.out);System.exit(0);}catch(Exception
E){}}return 0<1;}
public void paint(Graphics g){g.drawImage(i,0,0,this);}}

Takes input image from stdin and writes cropped image to stdout. You can drag in whichever direction you choose and it will automatically flip the coordinates as required. Input in GIF, PNG, JPEG, TIFF, probably one or two others; output in PNG.
With whitespace and a couple of comments:
import java.awt.*;
import javax.imageio.*;

// Extending Frame is the simplest and ugliest way of showing a GUI.
public class R extends Frame {

    // static so that we can read it in main() and save a try/catch block
    static java.awt.image.BufferedImage i;
    int x,y,w,h;

    // Instance initialiser ~= constructor without the signature
    {
        setSize(i.getWidth(),i.getHeight());
        // Don't show frames. This saves handling inset dimensions everywhere
        setUndecorated(0<1);
        show();
    }

    public static void main(String[]a) throws Exception
    {
        i=ImageIO.read(System.in);
        new R();
    }

    // This is deprecated, but it's the shortest way of handling events.
    // I learnt this trick from the Java4k Game Competition
    public boolean handleEvent(Event e) {
        if (e.id == 501) { // MOUSE_DOWN
            x=e.x;
            y=e.y;
        }
        if (e.id == 502) { // MOUSE_UP
            w = e.x - x;
            // If the second click was to the left of the first one, flip them.
            if (w < 0) x -= w = -w;
            h = e.y - y;
            // Similarly.
            if (h < 0) y -= h = -h;

            try {
                ImageIO.write(i.getSubimage(x,y,w,h), "png", System.out);
                System.exit(0);
            } catch(Exception E){
            }
        }
        return 0<1;
    }

    public void paint(Graphics g) {
        g.drawImage(i,0,0,this);
    }
}

Would you mind putting a nicely formatted version too so we can appreciate the golfing tricks you have done?

R - 325 305 characters
f=scan(,"");l=locator;r=round;i=as.raster(png::readPNG(f));n=nrow(i);m=ncol(i);x11(h=7,w=7*m/n);p=function(X){par(mar=rep(0,4));m=ncol(X);n=nrow(X);plot(c(1,m),c(1,n),xaxs="i",yaxs="i");rasterImage(X,1,1,m,n)};p(i);a=l(1);b=l(1);j=i[r(n-a$y):r(n-b$y),r(a$x):r(b$x)];png(w=ncol(j),h=nrow(j));p(j);dev.off()

Or fully developed:
f=scan(,"")
l=locator
r=round
i=as.raster(png::readPNG(f))
n=nrow(i)
m=ncol(i)
x11(h=7,w=7*m/n)
p=function(X){
par(mar=rep(0,4))
m=ncol(X)
n=nrow(X)
plot(c(1,m),c(1,n),xaxs="i",yaxs="i")
rasterImage(X,1,1,m,n)
}
p(i)
a=l(1)
b=l(1)
j=i[r(n-a$y):r(n-b$y),r(a$x):r(b$x)]
png(w=ncol(j),h=nrow(j))
p(j)
dev.off()

Tested on a Mac, untested on Linux but should work.
Package png needs to be installed.
At prompt, should be provided with path to png file to crop. Then when the picture appears, click twice: once for the left upper corner of selection rectangle and a second time for the right lower corner.
Create a cropped png file in working directory with default name ("Rplot001.png").

How are you counting the chars? It seems to be 306 to me using tr -d '[[:blank:]]' < temp.R |wc.

So I'm guessing you're counting the line-break then. It's my first week code-golfing I might have overlook that. The issue is that not all line-break are meaningful in R so I might need to edit accordingly.

So the actual number is 305 (the line-break after the opening braces and the one before the closing braces being meaningless).

Java (Applet), 706 698 590
By no means is Java ever considered terse, and it certainly doesn't have the most elegant handling of image display or mouse interaction, but this really isn't that bad. I'm wondering if a solution using Swing or some other library might be shorter.
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.imageio.*;

public class R extends java.applet.Applet{
    Scanner s=new java.util.Scanner(System.in);
    java.awt.image.BufferedImage i;
    int x,y;
    {
        try{
            i=ImageIO.read(new File(s.nextLine()));
        }catch(Exception e){}
        addMouseListener(new MouseAdapter(){
            public void mousePressed(MouseEvent e){
                x=e.getX();y=e.getY();
            }
            public void mouseReleased(MouseEvent e){
                try{
                    ImageIO.write(i.getSubimage(x,y,e.getX()-x,e.getY()-y),"png",new File(s.nextLine()));
                }catch(Exception z){}
            }
        });
    }
    public void paint(java.awt.Graphics g){
        g.drawImage(i,0,0,this);
    }
}

I see you are counting characters using tr -d '[[:blank:]]' < file.java |wc . If you take the view that you don't need to include the imports you are down to 590 chars.

@felipa If part of the solution is to match the best code with the best library, then perhaps counting the include is a good idea?

You can almost certainly golf this more by not using listeners. Just override an event handling method of Applet (handleEvent or processEvent). I think you'll also find that BufferedImage.getSubimage is shorter than copying the data manually.

@Gaffi Sure. It's just not what the Octave solution did . I  think you are right though.

@felipa I'm counting the minimum number of characters to make a working program. That includes whitespace in some cases, and definitely includes imports.

@PeterTaylor thanks for the tips. getSubimage definitely helps, but I don't think processEvent will. Too much added to ensure that the event is a mouse down or mouse up, and not something like a window resize or a focus or whatever.

Seems to work ok for me...

@JoeK That makes sense. How exactly are you doing the counting? By hand?

@felipa Yep, pretty much deleting every newline and tab character and then just putting the cursor at the end of the program and looking at the column number.

Python/PyGame (343C)
Usage:
python this.py image.png result.png

which read from image.png and write to result.png.
import pygame as P
import sys
D=P.display
I=P.image
D.init()
f,g=sys.argv[1:3]
m=I.load(f)
s=D.set_mode(m.get_size())
r=k=0
c=1
while c:
 for e in P.event.get():
  t=e.type
  if t==5:x,y=e.pos;k=1
  if t==4 and k:i,j=e.pos;r=(x,y,i-x,j-y)
  if t==6:c=0
 s.blit(m,(0,0))
 if r and c:P.draw.rect(s,0,r,1)
 D.flip()
q=s.subsurface(r)
I.save(q,g)

I know the time limit is up, but here's how to do it in 34 characters using Bash:
display $1&K=$!;import $2;kill $K

Call it like this: 'script.sh input.png output.png'.
This  uses the ImageMagick tools/library to first display the image. Then it lets you select an area to take a screenshot of using the mouse. This screenshot is effectively a crop of the image. Finally, the display is closed.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Breakout in half an hour
When I was a young teen I had a very boastful friend who claimed he could code up breakout in half an hour. Half an hour later he had done a great job but it didn't quite work. This challenge is to see in 2013 how short it is possible to code this classic game. For the purposes of the competition there need only be one level and no score keeping is needed. The game should be controlled from the keyboard (right and left is all that is needed) but the bricks need to be destroyed correctly and the ball has to bounce in the usual way.
You can choose any programming language you like as well as any free (in both sense) libraries. The code should run in linux.
To inspire you, here is a bare bones and completely ungolfed version of the game in python by  Leonel Machava from http://codentronix.com/2011/04/14/game-programming-with-python-and-pygame-making-breakout/ .
"""
 bricka (a breakout clone)
 Developed by Leonel Machava <leonelmachava@gmail.com>

 http://codeNtronix.com
"""
import sys
import pygame

SCREEN_SIZE   = 640,480

# Object dimensions
BRICK_WIDTH   = 60
BRICK_HEIGHT  = 15
PADDLE_WIDTH  = 60
PADDLE_HEIGHT = 12
BALL_DIAMETER = 16
BALL_RADIUS   = BALL_DIAMETER / 2

MAX_PADDLE_X = SCREEN_SIZE[0] - PADDLE_WIDTH
MAX_BALL_X   = SCREEN_SIZE[0] - BALL_DIAMETER
MAX_BALL_Y   = SCREEN_SIZE[1] - BALL_DIAMETER

# Paddle Y coordinate
PADDLE_Y = SCREEN_SIZE[1] - PADDLE_HEIGHT - 10

# Color constants
BLACK = (0,0,0)
WHITE = (255,255,255)
BLUE  = (0,0,255)
BRICK_COLOR = (200,200,0)

# State constants
STATE_BALL_IN_PADDLE = 0
STATE_PLAYING = 1
STATE_WON = 2
STATE_GAME_OVER = 3

class Bricka:

    def __init__(self):
        pygame.init()

        self.screen = pygame.display.set_mode(SCREEN_SIZE)
        pygame.display.set_caption("bricka (a breakout clone by codeNtronix.com)")

        self.clock = pygame.time.Clock()

        if pygame.font:
            self.font = pygame.font.Font(None,30)
        else:
            self.font = None

        self.init_game()

    def init_game(self):
        self.lives = 3
        self.score = 0
        self.state = STATE_BALL_IN_PADDLE

        self.paddle   = pygame.Rect(300,PADDLE_Y,PADDLE_WIDTH,PADDLE_HEIGHT)
        self.ball     = pygame.Rect(300,PADDLE_Y - BALL_DIAMETER,BALL_DIAMETER,BALL_DIAMETER)

        self.ball_vel = [5,-5]

        self.create_bricks()

    def create_bricks(self):
        y_ofs = 35
        self.bricks = []
        for i in range(7):
            x_ofs = 35
            for j in range(8):
                self.bricks.append(pygame.Rect(x_ofs,y_ofs,BRICK_WIDTH,BRICK_HEIGHT))
                x_ofs += BRICK_WIDTH + 10
            y_ofs += BRICK_HEIGHT + 5

    def draw_bricks(self):
        for brick in self.bricks:
            pygame.draw.rect(self.screen, BRICK_COLOR, brick)

    def check_input(self):
        keys = pygame.key.get_pressed()

        if keys[pygame.K_LEFT]:
            self.paddle.left -= 5
            if self.paddle.left < 0:
                self.paddle.left = 0

        if keys[pygame.K_RIGHT]:
            self.paddle.left += 5
            if self.paddle.left > MAX_PADDLE_X:
                self.paddle.left = MAX_PADDLE_X

        if keys[pygame.K_SPACE] and self.state == STATE_BALL_IN_PADDLE:
            self.ball_vel = [5,-5]
            self.state = STATE_PLAYING
        elif keys[pygame.K_RETURN] and (self.state == STATE_GAME_OVER or self.state == STATE_WON):
            self.init_game()

    def move_ball(self):
        self.ball.left += self.ball_vel[0]
        self.ball.top  += self.ball_vel[1]

        if self.ball.left <= 0:
            self.ball.left = 0
            self.ball_vel[0] = -self.ball_vel[0]
        elif self.ball.left >= MAX_BALL_X:
            self.ball.left = MAX_BALL_X
            self.ball_vel[0] = -self.ball_vel[0]

        if self.ball.top < 0:
            self.ball.top = 0
            self.ball_vel[1] = -self.ball_vel[1]
        elif self.ball.top >= MAX_BALL_Y:
            self.ball.top = MAX_BALL_Y
            self.ball_vel[1] = -self.ball_vel[1]

    def handle_collisions(self):
        for brick in self.bricks:
            if self.ball.colliderect(brick):
                self.score += 3
                self.ball_vel[1] = -self.ball_vel[1]
                self.bricks.remove(brick)
                break

        if len(self.bricks) == 0:
            self.state = STATE_WON

        if self.ball.colliderect(self.paddle):
            self.ball.top = PADDLE_Y - BALL_DIAMETER
            self.ball_vel[1] = -self.ball_vel[1]
        elif self.ball.top > self.paddle.top:
            self.lives -= 1
            if self.lives > 0:
                self.state = STATE_BALL_IN_PADDLE
            else:
                self.state = STATE_GAME_OVER

    def show_stats(self):
        if self.font:
            font_surface = self.font.render("SCORE: " + str(self.score) + " LIVES: " + str(self.lives), False, WHITE)
            self.screen.blit(font_surface, (205,5))

    def show_message(self,message):
        if self.font:
            size = self.font.size(message)
            font_surface = self.font.render(message,False, WHITE)
            x = (SCREEN_SIZE[0] - size[0]) / 2
            y = (SCREEN_SIZE[1] - size[1]) / 2
            self.screen.blit(font_surface, (x,y))

    def run(self):
        while 1:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    sys.exit

            self.clock.tick(50)
            self.screen.fill(BLACK)
            self.check_input()

            if self.state == STATE_PLAYING:
                self.move_ball()
                self.handle_collisions()
            elif self.state == STATE_BALL_IN_PADDLE:
                self.ball.left = self.paddle.left + self.paddle.width / 2
                self.ball.top  = self.paddle.top - self.ball.height
                self.show_message("PRESS SPACE TO LAUNCH THE BALL")
            elif self.state == STATE_GAME_OVER:
                self.show_message("GAME OVER. PRESS ENTER TO PLAY AGAIN")
            elif self.state == STATE_WON:
                self.show_message("YOU WON! PRESS ENTER TO PLAY AGAIN")

            self.draw_bricks()

            # Draw paddle
            pygame.draw.rect(self.screen, BLUE, self.paddle)

            # Draw ball
            pygame.draw.circle(self.screen, WHITE, (self.ball.left + BALL_RADIUS, self.ball.top + BALL_RADIUS), BALL_RADIUS)

            self.show_stats()

            pygame.display.flip()

if __name__ == "__main__":
    Bricka().run()

I will accept the answer with the highest number of votes in exactly one week. Extra extra points if anyone can make a version in half an hour :)
Update The answer are great but... surely there are more people who want to show off their favourite language to play breakout! Come on python/perl/Haskell/crazy language experts :)
Winners  And the winner is.. Ray.  However, extra extra points go to... Schmiddty for completing the task in under 30 minutes!  I would still love to see implementations in other languages however.

What exactly needs to be implemented? Do all bricks break after being hit once? Indestructible bricks? Win/lose logic? Brick Colors?

@Shmiddty A brick breaks when it is hit once.  No indestructible bricks needed nor win/lose logic. The bouncing rules have to be correct however. Colors are up to you but I hope you can include some.

Could you clarify The bouncing rules have to be correct? In your python example implementation, the absolute value of the ball's velocity will always be [5, 5]. Is this acceptable?

@Shmiddty Constant speed is fine. I should say the example I gave is a little fast for me... :)

@felipa I am glad to see my python code referenced here. Thank you.

A friend of mine coded Pong in about an hour, but he was constantly stopping explaining what he was doing, as this was a presentation being made to new programmers. I'd bet he could take a challenge like this.

I think this is still vague. There should be specifics about how many bricks are necessary at minimum, dimensions, and a description about what Breakout is. Answers should be self-contained.

Python 3 with Pygame and PIL / many hours
After playing other answers, that has simple level config, an idea came to me: The level can be initialized be an image.
So I make this one. To play it, you draw an image that contains many convex polygons, like this:
 image example http://imgbin.org/images/11634.png
The black color will be parsed as walls and the lowest block will be the player.
Save it as break-windows.png and then run with command:
python3 brcki.py break-windows.png

Another feature is that the collision detection is very precise. I use binary-search to do it. When two objects collide, time goes back until nothing collide so that the
exact collide time and point will be detected. With this tecnique, the ball can go very fast while
the bounce effect is still realistic.
Here is brcki.py. I know it's a bit too long to be a golf. But isn't that insteresting playing on your own image?
import pygame as pg
import itertools
import Image
from random import randint
from math import pi,sin,cos,atan2

norm = lambda c:c/abs(c)
times = lambda c,d:(c*d.conjugate()).real
cross = lambda c,d:(c*d.conjugate()).imag

class Poly:
    def __init__(self, ps, c, color=0):
        assert isinstance(c, complex)
        for p in ps:
            assert isinstance(p, complex)
        self.c = c
        self.ps = ps
        self.boundR = max(abs(p) for p in ps)
        self.ns = [norm(ps[i]-ps[i-1])*1j for i in range(len(ps))]
        self.color = color

class Ball(Poly):
    def __init__(self, r, c, v):
        n = int(1.5*r)
        d = 2*pi/n
        ps = [r * (cos(i*d)+sin(i*d)*1j) for i in range(n)]
        super().__init__(ps, c)
        self.v = v
        self.r = r
        self.color = ColorBall

class Player(Poly):
    def __init__(self, ps, c, color=0):
        super().__init__(ps, c, color)
        self.v = 0+0j

pg.display.init()
W, H = 600, 700
ColorBG = pg.Color(0xffffffff)
ColorBall = pg.Color(0x615ea6ff)
ColorBrick = pg.Color(0x555566ff)
FPS = 40
BallR, BallV = 15, 120+640j
PlayerV = 300

Bc, Bi, Bj = W/2+H*1j, 1+0j, -1j

def phy2scr(p):
    p = Bc + p.real * Bi + p.imag * Bj
    return round(p.real), round(p.imag)

def hittest(dt, b, plr, Ps)->'(dt, P) or None':
    t0, t1, t2 = 0, dt, dt
    moveon(dt, b, plr)
    if not existhit(b, Ps): return None
    while t1 - t0 > 1e-2:
        t3 = (t0 + t1)/2
        moveon(t3 - t2, b, plr)
        if existhit(b, Ps): t1 = t3
        else: t0 = t3
        t2 = t3
    moveon(t1 - t2, b, plr)
    P = next(P for P in Ps if collide(b, P))
    moveon(t0 - t1, b, plr)
    assert not existhit(b, Ps)
    return (t1, P)

def existhit(b, Ps)->'bool':
    return any(collide(b, P) for P in Ps)

def inside(p, P)->'bool':
    return all(times(p-q-P.c, n)>=0 for q,n in zip(P.ps,P.ns))

def collide(P1, P2)->'bool':
    if abs(P1.c - P2.c) > P1.boundR + P2.boundR + 1:
        return False
    return any(inside(P1.c + p, P2) for p in P1.ps) \
            or any(inside(P2.c + p, P1) for p in P2.ps)

def moveon(dt, *ps):
    for p in ps:
        p.c += p.v * dt

def hithandle(b, P):
    hp, n = hitwhere(b, P)
    b.v -= 2 * n * times(b.v, n)

def hitwhere(b, P)->'(hitpoint, norm)':
    c = P.c
    for p in P.ps:
        if abs(b.c - p - c) < b.r + 1e-1:
            return (p+c, norm(b.c - p - c))
    minD = 100
    for p, n in zip(P.ps, P.ns):
        d = abs(times(b.c - p - c, -n) - b.r)
        if d < minD:
            minD, minN = d, n
    n = minN
    return (b.c + n * b.r, -n)

def draw(sur, P):
    pg.draw.polygon(sur, P.color, [phy2scr(p + P.c) for p in P.ps])

def flood_fill(img, bgcolor):
    dat = img.load()
    w, h = img.size
    mark = set()
    blocks = []
    for x0 in range(w):
        for y0 in range(h):
            if (x0, y0) in mark: continue
            color = dat[x0, y0]
            if color == bgcolor: continue
            mark.add((x0, y0))
            stk = [(x0, y0)]
            block = []
            while stk:
                x, y = stk.pop()
                for p1 in ((x-1,y),(x,y-1),(x+1,y), (x,y+1)):
                    x1, y1 = p1
                    if x1 < 0 or x1 >= w or y1 < 0 or y1 >= h: continue
                    if dat[p1] == color and p1 not in mark:
                        mark.add(p1)
                        block.append(p1)
                        stk.append(p1)
            block1 = []
            vis = set(block)
            for x, y in block:
                neig = sum(1 for p1 in ((x-1,y),(x,y-1),(x+1,y), (x,y+1)) if p1 in vis)
                if neig < 4: block1.append((x, y))
            if len(block1) >= 4: blocks.append((dat[x0, y0], block1))
    return blocks

def place_ball(b, plr):
    c = plr.c
    hl, hr = 0+0j, 0+300j
    # assume:
    # when b.c = c + hl, the ball overlaps player
    # when b.c = c + hr, the ball do not overlaps player
    while abs(hr - hl) > 1:
        hm = (hl + hr) / 2
        b.c = c + hm
        if collide(b, plr): hl = hm
        else: hr = hm
    b.c = c + hr

def pixels2convex(pixels):
    """
    convert a list of pixels into a convex polygon using Gramham Scan.
    """
    c = pixels[0]
    for p in pixels:
        if c[1] > p[1]:
            c = p
    ts = [(atan2(p[1]-c[1], p[0]-c[0]), p) for p in pixels]
    ts.sort()
    stk = []
    for x, y in ts:
        while len(stk) >= 2:
            y2, y1 = complex(*stk[-1]), complex(*stk[-2])
            if cross(y1 - y2, complex(*y) - y1) > 0:
                break
            stk.pop()
        stk.append(y)
    if len(stk) < 3: return None
    stk.reverse()
    return stk

def img2data(path) -> "(ball, player, brckis, walls)":
    """
    Extract polygons from the image in path.
    The lowest(with largest y value in image) polygon will be
    the player. All polygon will be converted into convex.
    """
    ColorWall = (0, 0, 0)
    ColorBG = (255, 255, 255)
    print('Start parsing image...')
    img = Image.open(path)
    w, h = img.size

    blocks = flood_fill(img, ColorBG)
    brckis = []
    walls = []
    player = None
    def convert(x, y):
        return x * W / float(w) - W/2 + (H - y * H / float(h))*1j

    for color, block in blocks:
        conv = []
        conv = pixels2convex(block)
        if conv is None: continue
        conv = [convert(x, y) for x, y in conv]
        center = sum(conv) / len(conv)
        p = Poly([c-center for c in conv], center, color)
        if color == ColorWall:
            walls.append(p)
        else:
            brckis.append(p)
            if player is None or player.c.imag > center.imag:
                player = p
    ball = Ball(BallR, player.c, BallV)
    print('Parsed image:\n  {0} polygons,\n  {1} vertices.'.format(
        len(walls) + len(brckis),
        sum(len(P.ps) for P in itertools.chain(brckis, walls))))
    print('Ball: {0} vertices, radius={1}'.format(len(ball.ps), ball.r))
    brckis.remove(player)
    player = Player(player.ps, player.c, player.color)
    place_ball(ball, player)
    return ball, player, brckis, walls

def play(config):
    scr = pg.display.set_mode((W, H), 0, 32)
    quit = False
    tm = pg.time.Clock()
    ball, player, brckis, walls = config
    polys = walls + brckis + [player]
    inputD = None
    while not quit:
        dt = 1. / FPS
        for e in pg.event.get():
            if e.type == pg.KEYDOWN:
                inputD = {pg.K_LEFT:-1, pg.K_RIGHT:1}.get(e.key, inputD)
            elif e.type == pg.KEYUP:
                inputD = 0
            elif e.type == pg.QUIT:
                quit = True
        if inputD is not None:
            player.v = PlayerV * inputD + 0j

        while dt > 0:
            r = hittest(dt, ball, player, polys)
            if not r: break
            ddt, P = r
            dt -= ddt
            hithandle(ball, P)
            if P in brckis:
                polys.remove(P)
                brckis.remove(P)
        if ball.c.imag < 0: print('game over');quit = True
        if not brckis: print('you win');quit = True
        scr.fill(ColorBG)
        for p in itertools.chain(walls, brckis, [player, ball]):
            draw(scr, p)
        pg.display.flip()
        tm.tick(FPS)

if __name__ == '__main__':
    import sys
    play(img2data(sys.argv[1]))

Javascript/KineticJS
Here's a "working" version in 28 minutes, but it's not exactly playable (the collision logic is too slow). http://jsfiddle.net/ukva5/5/
(function (con, wid, hei, brk) {
    var stage = new Kinetic.Stage({
        container: con,
        width: wid,
        height: hei
    }),
        bricks = new Kinetic.Layer(),
        brks = brk.bricks,
        bX = wid / 2 - brk.width * brks[0].length / 2,
        bY = brk.height,
        mov = new Kinetic.Layer(),
        ball = new Kinetic.Circle({
            x: wid / 4,
            y: hei / 2,
            radius: 10,
            fill: 'black'
        }),
        paddle = new Kinetic.Rect({
            x:wid/2-30,
            y:hei*9/10,
            width:60,
            height:10,
            fill:'black'
        }),
        left = false,
        right = false;

    mov.add(ball);
    mov.add(paddle);
    stage.add(mov);

    paddle.velocity = 5;

    ball.angle = Math.PI/4;
    ball.velocity = 3;
    ball.bottom = function(){
        var x = ball.getX();
        var y = ball.getY();
        return {x:x, y:y+ball.getRadius()};
    };
    ball.top = function(){
        var x = ball.getX();
        var y = ball.getY();
        return {x:x, y:y-ball.getRadius()};
    };
    ball.left = function(){
        var x = ball.getX();
        var y = ball.getY();
        return {x:x-ball.getRadius(), y:y};
    };
    ball.right = function(){
        var x = ball.getX();
        var y = ball.getY();
        return {x:x+ball.getRadius(), y:y};
    };
    ball.update = function(){
        ball.setX(ball.getX() + Math.cos(ball.angle)*ball.velocity);
        ball.setY(ball.getY() + Math.sin(ball.angle)*ball.velocity);
    };
    paddle.update = function(){
        var x = paddle.getX();
        if (left) x-=paddle.velocity;
        if (right) x+= paddle.velocity;

        paddle.setX(x);
    };

    for (var i = 0; i < brks.length; i++) {
        for (var j = 0; j < brks[i].length; j++) {
            if (brks[i][j]) {
                bricks.add(new Kinetic.Rect({
                    x: bX + j * brk.width + .5,
                    y: bY + i * brk.height + .5,
                    width: brk.width,
                    height: brk.height,
                    stroke: 'black',
                    strokeWidth: 1,
                    fill: 'gold'
                }));
            }
        }
    }
    stage.add(bricks);

    $(window).keydown(function(e){
        switch(e.keyCode){
            case 37:
                left = true;
                break;
            case 39:
                right = true;
                break;
        }
    }).keyup(function(e){
        switch(e.keyCode){
            case 37:
                left = false;
                break;
            case 39:
                right = false;
                break;
        }
    });

    (function loop(){
        ball.update();
        paddle.update();

        if (paddle.intersects(ball.bottom())){
            ball.setY(paddle.getY()-ball.getRadius());
            ball.angle = -ball.angle;
        }
        if (ball.right().x > wid){
            ball.setX(wid - ball.getRadius());
            ball.angle = Math.PI - ball.angle;
        }
        if (ball.left().x < 0){
            ball.setX(ball.getRadius());
            ball.angle = Math.PI - ball.angle;
        }
        if (ball.top().y < 0){
            ball.setY(ball.getRadius());
            ball.angle = -ball.angle;
        }

        for(var i = bricks.children.length; i--;){
            var b = bricks.children[i];
            if (b.intersects(ball.top()) || b.intersects(ball.bottom())){
                ball.angle = -ball.angle;
                b.destroy();
            }
            else if (b.intersects(ball.left()) || b.intersects(ball.right())){
                ball.angle = Math.PI-ball.angle;
                b.destroy();
            }
        }

        stage.draw();

        webkitRequestAnimationFrame(loop);
    })()

})('b', 640, 480, {
    width: 80,
    height: 20,
    bricks: [
        [1, 1, 1, 1, 1, 1],
        [1, 1, 0, 0, 1, 1],
        [1, 1, 1, 1, 1, 1]
    ]
});

I'll work on making the game snappier now. :)
Note: Works only in webkit browsers right now. I'll add a shim so it will work in any HTML5 ready browser eventually.
Updates:

http://jsfiddle.net/ukva5/6/ more playable
http://jsfiddle.net/ukva5/7/ random bricks, faster ball
http://jsfiddle.net/ukva5/8/ random brick health
http://jsfiddle.net/ukva5/12/show/light/ stopping point for the day.

I feel sure this is a dumb question but... How would you run this in a browser without making an HTML page to put it in?

@felipa You would need the HTML page.

28 minutes is amazing!  I am not clear on the rules of golfing. Is javascript allowed without the associated HTML?

@felipa 28 minutes was only possible because you said we could use libraries. :) I am using both jQuery and KineticJS, which simplify a great many things for me.

Also, I'm not sure if there is a definite answer on that. My gut says that HTML/JS answers would include any HTML inside of the body tag towards their character count, but nothing outside of it, or the body tag itself. IE, for my solution, I would simply include <div id='b'></div> or <div id='b'> if I were golfing it.

Processing, 400 characters
Didn't manage to do it in 30min, but here's a surf'd version. The ball is square and if you press any other key than left/right it jumps fully right, but it was shorter and the spec didn't say anything against it ;).
int x,y=999,u,v,p=300,q=580,i,l,t;long g;void setup(){size(720,600);}void draw(){background(0);if(keyPressed)p=min(max(p+8*(keyCode&2)-8,0),630);rect(p,q,90,20);for(i=0;i<64;i++)if((g>>i&1)<1){l=i%8*90;t=i/8*20+40;if(x+20>l&&x<l+90&&y+20>t&&y<t+20){v=-v;g|=1l<<i;}rect(l,t,90,20);}if(x+20>p&&x<p+90&&y+20>q)v=-abs(v);if(y<0)v=-v;if(x<0||x>700)u=-u;if(y>600){x=y=400;u=v=3;}x+=u;y+=v;rect(x,y,20,20);}

With proper names & some whitespace for clarity, that's:
int ballX, ballY=999, speedX, speedY, paddleX=300, paddleY=580;
long bricks;

void setup() {
  size(720, 600);
}

void draw() {
  background(0);
  if(keyPressed) paddleX = min(max(paddleX+8*(keyCode^37)-8,0),630);
  rect(paddleX, paddleY, 90, 20);
  for(int i=0; i<64; i++) {
    if((bricks>>i&1)<1) {
      int brickX=i%8*90, brickY=i/8*20+40;
      if(ballX+20>brickX && ballX<brickX+90 && ballY+20>brickY && ballY<brickY+20) {
        speedY = -speedY;
        bricks |= 1l<<i;
      }
      rect(brickX, brickY, 90, 20);
    }
  }
  if(ballX+20>paddleX && ballX<paddleX+90 && ballY+20>paddleY) speedY = -abs(speedY);
  if(ballY<0) speedY = -speedY;
  if(ballX<0 || ballX>700) speedX = -speedX;
  if(ballY>600) {
    ballX = ballY = 400;
    speedX = speedY = 3;
  }
  ballX += speedX; ballY += speedY;
  rect(ballX, ballY, 20, 20);
}

I had a feeling processing would be used here...

Elm, 1 hour 44 minutes
I tried to do it in half an hour, but overshot a little.  To try to save time, I used circles for everything (paddle, ball, bricks).  This avoided the many cases needed to implement circle/rectangle collision, but required some vector math to compute the resulting direction.
To run, go to http://elm-lang.org/edit/, paste the code into the editor, and click the "In Tab" button at the bottom.
import Keyboard

brickR = 30
ballR = 10
paddleY = 450
paddleR = 50

-- Initial (center) position of each brick
brickLayout = [(150,50), (250, 50), (350, 50), (450, 50),
            (100,100), (200,100), (300,100), (400,100), (500,100)]

brickForm = filled blue . circle brickR

-- Return True if the brick coordinate collides with the ball coordinate
brickVsBall brickPos ballPos =
    distance brickPos ballPos <= brickR + ballR

addVec (ax,ay) (bx,by) = (ax+bx, ay+by)
subVec (ax,ay) (bx,by) = (ax-bx, ay-by)
dot (ax,ay) (bx,by) = ax*bx + ay*by
magsq (x,y) = x*x + y*y
scaleVec s (x,y) = (x*s, y*s)
proj n v = scaleVec (dot v n / magsq n) n
flipV n v = v `subVec` scaleVec 2 (proj n v)
distance a b = sqrt $ magsq $ a `subVec` b

-- Only flip the velocity if headed "toward" the target, where n is a vector
-- pointing from the ball to the target.
bounceV n v =
    if v `dot` n > 0
       then v `subVec` scaleVec 2 (proj n v)
       else v

checkBricks ballPos ballV bricks =
    let (smashed, kept) = updateBricks ballPos [] [] bricks
     in (updateBallV ballPos ballV smashed, kept)

updateBricks ballPos smashed kept bricks = case bricks of
    [] -> (reverse smashed, reverse kept)
    (x:xs) ->
        if brickVsBall x ballPos
           then updateBricks ballPos (x:smashed) kept xs
           else updateBricks ballPos smashed (x:kept) xs

updateBallV ballPos ballV smashed = case smashed of
    []     -> ballV
    (x:xs) -> updateBallV ballPos (bounceV (x `subVec` ballPos) ballV) xs

checkPaddle paddleX ballPos ballV =
    let paddlePos = (paddleX,paddleY) in
    if distance ballPos paddlePos <= ballR + paddleR
       then bounceV (paddlePos `subVec` ballPos) ballV
       else ballV

checkWalls r (x,y) =
    let checkLeft  (vx,vy) = if x-r <= 0   && vx<0 then (0-vx,vy) else (vx,vy)
        checkRight (vx,vy) = if x+r >= 600 && vx>0 then (0-vx,vy) else (vx,vy)
        checkTop   (vx,vy) = if y-r <= 0   && vy<0 then (vx,0-vy) else (vx,vy)
     in checkLeft . checkRight . checkTop

-- type Scene = ([BrickPos], BallPos, BallV, PaddleX)
-- BallV is in pixels per frame

initScene = (brickLayout, (300,385), (0, 0-3), 300)

renderScene (bricks, ballPos, ballV, paddleX) =
    collage 600 500 $
    map brickForm bricks ++
    [ filled red $ circle ballR ballPos
    , filled black $ circle paddleR (paddleX,paddleY)
    ]

updateScene (bricks, ballPos, ballV, paddleX) arrows =
    let paddleX' = paddleX + arrows.x * 4
        (ballV1, bricks') = checkBricks ballPos ballV bricks
        ballV2 = checkPaddle paddleX' ballPos ballV1
        ballV' = checkWalls ballR ballPos ballV2
     in (bricks', ballPos `addVec` ballV', ballV', paddleX')

main =
    lift renderScene $
    foldp (\(t, arrows) scene -> updateScene scene arrows) initScene $
    lift2 (,) (every (second/60)) arrows

That is very cool. Two small problems. One is that I think the ball bouncing logic is slightly broken. If the ball comes from above a "brick" it seems to go straight through it rather than bounce off. Second, it's not golfed at all :)

Also, in case anyone else is struggling with circle rectangle collsion, here is a very nice and simple way to do it http://stackoverflow.com/questions/401847/circle-rectangle-collision-detection-intersection . Of course it could be fun to golf that too :)


text:
Drawing 3d nets - Archimedean solids
I have a weakness for 3d nets which when cut out and folded allow you to make 3d shapes out of paper or card.  The task is simple, written the shortest program you can that draws nets for the 13 Archimedean solids. The output should be an image file in any sensible format (png, jpg).
All thirteen shapes are described at http://en.wikipedia.org/wiki/Archimedean_solid and in the following table taken from there.

Input: An integer from 1 to 13.  Assume the shapes are numbered exactly as in the table above so that the "truncated tetrahedron" is number 1 and the "snub dodecahedron" is number 13.
Output: An image file containing the net for that shape. Just the outline including the internal lines is OK. There is no need to fill it in with colors
You can use any programming language you like as well as any library that was not made especially for this competition. Both should be available freely however (in both senses) online.
I will accept the answer with the smallest number of characters in exactly one week's time.  Answers will be accepted whenever they come.
(No) Winner yet.  Sadly no valid entrants. Maybe it is too hard?

Maybe do away with the time-limit altogether? What if somebody finds this a year from now. Do you want them not to try?...Might've been better to do the Platonic first, wait, then the hard one. You may have divided the interest. For me personally (all of this is extrapolation), when I saw two similar ones, I kind of withdrew from it, feeling I didn't have the time to really look at both and plan out how to solve both. And I wouldn't want to do it any other way....On the other hand, others here have had difficulty with Part-2 challenges. See the Minsky Register Machine ones. Maybe it's not you.

@luserdroog Thanks. Question edited.  I should maybe add that I have emailed the answer to the related question around lots of people who love it! FWIW.

I don't think it's hard to do, but to golf it requires several hours of thinking and experimenting because there are many possible nets for each polyhedron and they won't compress equally well.

Java, 1552
import java.awt.*;import java.awt.image.*;import java.io.*;import javax.imageio.*;class
A{public static void main(String[]x)throws
Exception{String[]a={"33623368356:356;66","33413341334535463547354735473444","33823382338:3586338>358>358>358?88","66456:466:466845684668466766","334144453546354635474746464646464647354634463446344744","88456:466:466:4668458<468<468<468:456846684668466788","33343535353231333535313133353447353434353534313133353447353545343535313133353447353545343444","33513351335233593554335433593554335935543359355433593559355835593559355935593455","33:233:233:433:B35:833:833:B35:833:B35:833:B35:833:B35:B35:833:B35:B35:B35:B35:C::","66566:576:57696869576969586969586:586969576969586857685868586766","334155453546354635463547594658465846584658473546354634463546344635463446354634463547584657465746574657473546344634463446344755","::456:466:466:466:466845:@46:@46:@46:@46:>4568466:4668466:4668466:4668466:4668466845:>46:>46:>46:>46:<45684668466846684667::","333531333434343132333434353531313335343434323232323334343435353231333133343556343434313233323335345935353532313331313132333233353535343557343133343556343434355934353535593432333234355935323335345935323335345935323335345935343459313334353455"};BufferedImage
m=new BufferedImage(1300,1300,1);Graphics2D g=m.createGraphics();g.translate(500,500);String
s=a[Integer.valueOf(x[0])-1];int f=1,i=0,n,t;while(i<s.length()){n=s.charAt(i++)-48;t=s.charAt(i++);while(t-->48){g.drawLine(0,0,20,0);g.translate(20,0);g.rotate(f*Math.PI*2/n);}f=-f;}ImageIO.write(m,"png",new File("o.png"));}}

Ungolfed:
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;

import javax.imageio.ImageIO;

public class A {
    static int f = 1;
    static Graphics2D g;

    static void fixtrans() {
        double[] m = new double[6];
        g.getTransform().getMatrix(m);
        for (int i = 0; i < 6; ++i) {
            if (Math.abs(m[i] - Math.round(m[i])) < 1e-5) {
                m[i] = Math.round(m[i]);
            }
        }
        g.setTransform(new AffineTransform(m));
    }

    static void d(String s) {
        for (int i = 0; i < s.length();) {
            int n = s.charAt(i++) - '0';
            int t = s.charAt(i++) - '0';
            for (int j = 0; j < t; ++j) {
                g.drawLine(0, 0, 20, 0);
                g.translate(20, 0);
                g.rotate(f * Math.PI * 2 / n);
                fixtrans(); // optional, straightens some lines
            }
            f = -f;
        }
    }

    public static void main(String[] args) throws Exception {
        String[] a = {
                "33623368356:356;66",
                "33413341334535463547354735473444",
                "33823382338:3586338>358>358>358?88",
                "66456:466:466845684668466766",
                "334144453546354635474746464646464647354634463446344744",
                "88456:466:466:4668458<468<468<468:456846684668466788",
                "33343535353231333535313133353447353434353534313133353447353545343535313133353447353545343444",
                "33513351335233593554335433593554335935543359355433593559355835593559355935593455",
                "33:233:233:433:B35:833:833:B35:833:B35:833:B35:833:B35:B35:833:B35:B35:B35:B35:C::",
                "66566:576:57696869576969586969586:586969576969586857685868586766",
                "334155453546354635463547594658465846584658473546354634463546344635463446354634463547584657465746574657473546344634463446344755",
                "::456:466:466:466:466845:@46:@46:@46:@46:>4568466:4668466:4668466:4668466:4668466845:>46:>46:>46:>46:<45684668466846684667::",
// bad          "333531333434343132333434353531313335343434323232323334343435353231333133343556343434313233323335345935353532313331313132333233353535343557343133343556343434355934353531333459343434355935323335345935323335345935323335345935323335345935353455"
                "333531333434343132333434353531313335343434323232323334343435353231333133343556343434313233323335345935353532313331313132333233353535343557343133343556343434355934353535593432333234355935323335345935323335345935323335345935343459313334353455"};

        BufferedImage img = new BufferedImage(1300, 1300, BufferedImage.TYPE_INT_RGB);
        g = img.createGraphics();
        g.translate(500, 500);
        d(a[Integer.parseInt(args[0]) - 1]);
        String f = args[0] + ".png";
        ImageIO.write(img, "png", new File(f));
    }
}

Results (trimmed, negated, joined and scaled):

The shapes are quite unusual :) but correct as far as I can tell (let me know if you find any errors). They were generated (in a separate program) by constructing the face graph and cutting cycles in a DFS.
I'm sure this can be golfed quite a lot more using e.g. python and turtle.
Edit: oops, the last case was self-intersecting a bit. I fixed the code (by hand), here's the updated image:

Does the fix by hand mean the code still outputs a self intersection? Is that the only thing separating this from being a valid answer?

@githubphagocyte If it still outputted a self-intersection, it wouldn't be a fix. This is a valid answer.

This has been flagged because it violates one of the rules in our help center: All solutions to challenges should [...] be a serious contender for the winning criteria in use. For example, an entry to a code golf contest needs to be golfed.

@Dennis better now, mr. policeman? :p

Much better.

Mathematica
Out of competition, not a free language
f[n_] := PolyhedronData[Sort[PolyhedronData["Archimedean",
                                             {"FaceCount", "StandardName"}]][[n, 2]],  "NetImage"]

Usage:
f /@ Range@13


text:
Drawing 3d nets - Platonic solids
This is a basic version of the rather more difficult Drawing 3d nets - Archimedean solids .
I have a weakness for 3d nets which when cut out and folded allow you to make 3d shapes out of paper or card.  The task is simple, write the shortest program you can that draws nets for the 5 Platonic solids. The output should be an image file in any sensible format of your choosing (png, jpg, etc.).
All five shapes are described at http://en.wikipedia.org/wiki/Platonic_solid . Their nets looks like this (taken from http://www.newscientist.com/gallery/unfolding-the-earth/2 ).

Input: An integer from 1 to 5.  Assume the shapes are numbered in order of the number of sides they have. So, 1 would be a tetrahedron and 5 the icosahedron.
Output: An image file containing the net for that shape. Just the outline including the internal lines is OK. There is no need to fill it in with colors
You can use any programming language you like as well as any library that was not made especially for this competition. Both should be available freely however (in both senses) online.
I will accept the answer with the smallest number of characters in exactly one week's time.
Winner. Only one entrant but it was wonderful. The winner is ... Raufio for what is my favourite piece of code golf ever.

Python, 456 429 381
import turtle as t
L="fl"
R="fr"
d=L*3+R*3
b=(d+R)*3
a=[b,120,L*3+"fflflffflflfrflflfffl"+R*4+"flf",90,b+"ffrfrflffrffrfrfrflflf",120,(R*5+L*5+R+L)*5+"rrfr"+L*5+R*2+L*2+R*4+"f",72,(d+"f")*5+"rfl"+((d+"b")*5)[:-1],120]
l=t.lt
f=t.fd
b=t.bk
r=t.rt
p=input()*2-2
t.setup(.9,.9)
t.goto(-200,150)
t.clear()
for c in a[p]:exec c+"(a[p+1])"
t.getscreen().getcanvas().postscript(file="o")

I implemented a primitive interpreter with l r f b as operators that move the turtle cursor around at the angle of the shapes. At one time, it turns only one angle. I compressed the strings by reusing strings (kind of like psuedo-subroutines), other than that, I didn't check to see if I was using the best path. It outputs to a postscript file.
A little explanation of un-golfed code:
import turtle as t
Left="fl"
Right="fr"
diamond= Left*3 + Right*3
tetrahedron=(d+R)*3 #used to be b

Imports the built-in turtle module and defines the macros that shorten the strings. The turtle module uses commands to move a 'turtle' around the screen (ie forward(100), left(90))
netList=[
   #tetrahedron
   tetrahedron,120,
   #cube
   Left*3+"fflflffflflfrflflfffl"+Right*4+"flf",90,
   #octohedron, builds off the tetrahedron
   tetrahedron+"ffrfrflffrffrfrfrflflf",120,
   #dodecahedron
   (Right*5 + Left*5 + Right + Left)*5
    +"rrfr"+
    Left*5 + Right*2 + Left*2 + Right*4 + "f",72,
   #icosahedron
   (diamond+"f")*5 +"rfl"+((diamond+"b")*5)[:-1],120
]

This list holds the angles and movement sequences. The tetrahedron was saved to reuse with the octohedren.
l=t.left
f=t.forward
b=t.back
r=t.right

This is the part that i like, it makes single character local functions so the calls can be shortened and automated through pre-defined strings.
input=int(raw_input())*2-2
t.setup(.9,.9)
t.goto(-200,150)
t.clear()

This starts by taking the input (between 1 and 5), and converting that to an index that points to the shape string in the netList. These setup turtle to show the whole net. These could be left out if the task was just to draw them, but since we need a picture output they are needed.
for command in netList[input]:
    exec command+"(netList[input+1])"
t.getscreen().getcanvas().postscript(file="o")

The for loop takes the commands in the command sequence string and executes them, so for a string like "fl", this executes "forward(angle);left(angle);" by calling the newly created local functions. the last line outputs a file called 'o' that is in postscript format format using turtle function.
To run:
Copy it into a file and run it from there. When you run it, it will wait for a number input between 1 and 5 (i just changed it so that it asks before setting up turtle). When you input a number, a window pops up and draws the net. if you want it to go faster you can add t.speed(200) before setup.
You can copy-paste it into the interpreter, but when raw_input() is called it consumes the next string you input "t.setup(.9,.9)" instead of a number. So if you do this, copy up until raw_input(), input a number, than copy paste the rest. It is intended to be run as a whole. Or you could copy it into a function and call it.
Here are it's outputs (converted from postscript):
Note: the position of these in the window has changed, but their overall shape is the same.

It's a little brute force for code golf, but I got tired of trying to find a consistent pattern between the shapes.

Very close. The dodecahedron is definitely more tricky.

@Raufio It's very nice. Is it not possible to define a triangle (or square or pentagon) and then just rotate/move it about? Or is that effectively what you have done?

Effectively, yes that is what I did, but with larger shapes. For instance, the icosahedron is drawn by drawing two triangles, one on top of the other, and moving forward 5 times, then resetting at a new location, drawing the diamond again moving back then repeating 5 times. d is the string that does the two triangles, so it is (d+'f')*5+setupPosition+(d+'b')*5

@Raufio The golfed code doesn't work for me. It opens a window that is mostly blank. If I then press return I get  p=(ord(raw_input())-49)*2
TypeError: ord() expected a character, but string of length 0 found

@Raufio I tried it line by line in ipython and I don't really get it. I mean what is t.setup(.9,.9)
t.goto(-200,150)
t.clear() for? And then what is p=(ord(raw_input())-49)*2 meant to do?

@felipa setup makes the turtle window to be big enough to hold the net. Same thing with goto, it moves the 'turtle' to -200, 150. clear clears the line made by goto. Their just commands for setting up drawing. p=(ord(raw_input())-49)*2 takes a number, 1 through 5, corresponding to what shape you want.

@Raufio Oh I take it back. It's beautiful :)

Mathematica
Out of competition, not a free language (unless a free trial counts as free)
f[n_] := PolyhedronData[ Sort[PolyhedronData["Platonic", {"FaceCount","StandardName"}]][[n,2]],
                                                                                "NetImage"]

Usage:
f /@ Range@5

Mathematica is definitely not free in either sense.  Very nice answer however.

@felipa it's free as in beer on the Raspberry Pi.

you know, on that free computer, the raspberry pi

Python 2 (with cairo) - 239
from cairo import*
s=PSSurface(None,99,99)
g=Context(s)
g.move_to(30,20)
a=str([34,456,3455,568788,3454445555][input()-1])
f=6.28
for c in a+a[::-1]:exec'g.rel_line_to(8,0);g.rotate(f/int(a[0]));'*int(c);f=-f
g.stroke()
s.write_to_png('o')

Results:

Logo, 199 bytes
TO p:d:n:s
rt :n*45 for[i 1 :n/8][pu setxy :d*:i 0 pd repeat 2[for[k 1 :s*2+2][fd 40 rt (360-720*(:k>:s))/:s] rt 720/:s]]END
TO q:j
apply "p item :j [[70 9 3][56 23 4][70 16 3][105 26 5][40 42 3]]END

Reading this back I see my original version did not comply with the spec as written (take a numerical argument and draw one shape) but rather as interpreted by some of the other answers (draw all shapes.) The new version fixes this. It expects to be called as for example q 5. cs should be done before to clear the screen and point the turtle north.
q calls the main function p with 3 arguments. The syntax for this is pretty bloated, so to beat my previous score I had to shave off bytes elsewhere.
the new version of p takes 3 arguments. There is no need for x and y because we only plot one net, but d the pitch between subunits remains. s
is still the number of sides per polygon, and n now encodes for two different things> n/8 is the number of subunits to be plotted, and n*45 is an angle through which the turtle must be turned before starting (taking advantage of the natural mod 360 for rotations.)
Improved looping accomplishes drawing s lines with  righthand rotation and s+2 lines with lefthand rotation in a single loop.
the calormen interpreter seems to be less tolerant of missing whitespace now than at the time of my first post, but the code runs fine on http://turtleacademy.com/playground/en
Logo, 200 bytes
TO p:x:y:d:n:s
for[i 1:n][pu setxy:x:y-:d*:i if:i<>6[pd]repeat 2[repeat:s[fd 40 rt 360/:s]repeat:s+2[fd 40 lt 360/:s]rt 720/:s]]END
p 0 200 40 7 3
p 70 0 80 2 3
p -200 200 105 3 5
rt 45
p 90 90 56 2 4

Interpreter at http://www.calormen.com/jslogo/# It is assumed the turtle is pointing North before the program is run. Use the cs command to clear the screen, point the turtle north, and place it at the origin in the centre of the screen.

The basic unit of all the above nets is a pair of back to back polygons. These are arranged in 2 staggered rows, making a subunit of 4 polygons which can be translated vertically to make all the nets (except the octahedron, which hitches a ride on the drawing of the icosahedron and tetrahedron). The subunit forms 1 tetrahedron net, 1/5 of the icosahedron net, 1/3 of the dodecahedron net and 2/3 of the cube net (two subunits are drawn, with the middle two squares overlapping.)
Ungolfed code
TO p :x :y :d :n :s                 ;x,y=starting point d=negative vertical offset for each iteration n=#of iterations s=# of sides on polygon
  for[i 1 :n][                      ;iterate n times
    pu                              ;pen up
    setxy :x :y- :d* :i             ;move pen to start of iteration
    if :i<>6[pd]                    ;pen down (supressed for i=6 to enable part of octahedron to be drawn with icosahedron)
    repeat 2[                       ;draw lower row of 2 polygons, then upper row of 2 polygons
      repeat :s[fd 40 rt 360/ :s]   ;starting at lower left of polygon facing up, draw righthand polygon
      repeat :s+2[fd 40 lt 360/ :s] ;starting at lower right of polygon facing up, draw lefthand polygon, duplicating last two sides
      rt 720/ :s                    ;return turtle to upwards facing in order to draw second row
    ]
  ]
END
cs
p 0 200 40 7 3                      ;draw icosahedron and left side of octahedron (6th iteration is suppressed)
p 70 0 80 2 3                       ;draw right side of octahedron, and tetrahedron
p -200 200 105 3 5                  ;draw dodecahedron
rt 45                               ;turn turtle in preparation for drawing cube
p 90 90 56 2 4                      ;draw cube

@phase haha, thanks, I actually considered doing a ht to hide it for the image. I'm glad I didn't!


text:
Implement String.prototype.toLowerCase()
Implement String.prototype.toLowerCase()
Description
The toLowerCase method returns the value of the string converted to lowercase. toLowerCase does not affect the value of the string itself.
Conditions
Let count chars inside function and ignore all bootstrap code:
String.prototype.toLowerCase = function(){
  // code that count here
}

Other languages are welcome but JavaScript implemantation is target of this question. Let's just focus on ASCII charachters .
Example input and output:
"sOmeText".toLowerCase(); => "sometext"

Example implementation:
String.prototype.toLowerCase = function(){
  return this.split('').map(function(c){
     var cc = c.charCodeAt(0);
     if (cc > 64 && cc < 91) {
        return String.fromCharCode(cc + 32);
     }
     return c;
  }).join('');
}

Winning condition? I saw String.prototype.toLowerCase.apply(new Date()); on StackOverflow with a quick search; what is the input going to be?

@beary605 I've updated the question. I hope it's clear now.

The example answer is buggy. It doesn't even handle the whole of Latin 1.

It might want to be specified that the answer only has to work on ASCII characters.  Otherwise, things may get out of hand quickly.

updated again. JavaScript supports unicode chars and involving that can be confusing. How would you lowercase Ú?

ú, obviously. That's what String.prototype.toLowerCase() does.

Javascript 70 68
Building from @grc's answer:
for(s=i='';c=this[i++];s+=(parseInt(c,36)||c).toString(36));return s

Convert character to integer then back (works since Number.toString(36) will always be lowercase)
Test case: http://jsfiddle.net/Vh2TW/2/
input:
console.log('ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890~`-=_+{}[]:;\\\'\"<>,.?/!@#$%^&*()abcdefghijklmnopqrstuvwxyz'.toLowerCase())

output:
abcdefghijklmnopqrstuvwxyz1234567890~`-=_+{}[]:;\'"<>,.?/!@#$%^&*()abcdefghijklmnopqrstuvwxyz

Update: -2 characters, thanks @copy

Save 2 characters: for(s=i=""

@copy didn't realize ''++ becomes 0 interesting.

Bash, 10
Doesn't interface with javascript very well, but it works for everyday purposes.
tr A-Z a-z

Also, it's shorter than golfscript.  (Booyah!)

Example Input:
echo "Hello World, asDFghJkL0123" | tr A-Z a-z

Output:
hello world, asdfghjkl0123

Kindly show an example of input and output.

shorter than golfscript. This is a first. Is this a first?

Golfscript, 17
{..64>\91<*32*|}%

J, 25
toLowerCase =: u:@(+32*91&>*64&<)@(3&u:)

Converting to numbers (3&u:) and back u: is quite uneasy.

Javascript, 86
String.prototype.toLowerCase = function () {
    s="";for(i=0;c=this.charCodeAt(i++);s+=String.fromCharCode(c>64&c<91?c+32:c));return s
};

Python (45)
l=lambda x:''.join(chr(ord(i)+('@'<i<'[')*32)for i in x)
Pseudocode:
l=func(x) {
  return toString( iterate(i in x) { chr(ord(i) + IsUppercase(i) * 32) } )
}

Explanation:
('@'<i<'[')*32): IsUppercase. '@' - 64, 'A' - 65, 'Z' - 90, '[' - 91: If 64<ord(i)<91, then return True and multiply it by 32 (to get 32).

VBA - 77 82
Function l(s)
'Counting only the stuff between Function and End
For x=1 To Len(s):m=Mid(s,x,1):l=l & IIf(m Like"[A-Z]",Chr(Asc(m)+32),m):Next
End Function

Ruby: 32 characters
s.gsub(/[A-Z]/){($&.ord+32).chr}

Sample run:
(In 35 characters it can be made a method of String class, to work just as the JavaScript sample.)
irb(main):001:0> class String
irb(main):002:1>   def toLowerCase
irb(main):003:2>     self.gsub(/[A-Z]/){($&.ord+32).chr}
irb(main):004:2>   end
irb(main):005:1> end
=> nil
irb(main):006:0> "sOmeText".toLowerCase
=> "sometext"

javascript 76 chars:
replace(/[A-Z]/g,function(b){return String.fromCharCode(b.charCodeAt()+32)})

Here's the full function:
String.prototype.toLowerCase = function () {
    return this.replace(/[A-Z]/g, function(b){
        return String.fromCharCode(b.charCodeAt()+32)
    });
}

Julia, 49 chars
L(s)=ascii([s[i]+32(64<s[i]<91)for i=1:endof(s)])

for all chars s[i] if 64 < s[i] < 91 is true, add 32 to the ASCII character point (32*true=32). If it’s false, then (32*false=0), and nothing is changed.
example:
julia> str
"ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#abcdefghijklmnopqrstuvwxyz~"

julia> L(str)
"abcdefghijklmnopqrstuvwxyz1234567890!@#abcdefghijklmnopqrstuvwxyz~"

The default method in Julia is lowercase(str)
julia> lowercase(str)
"abcdefghijklmnopqrstuvwxyz1234567890!@#abcdefghijklmnopqrstuvwxyz~"

the difference in timing and memory allocation:
julia> @time L(str)
elapsed time: 1.0263e-5 seconds (792 bytes allocated)

julia> @time lowercase(str)
elapsed time: 6.693e-6 seconds (224 bytes allocated)


text:
Build an RSA encoder
Your task is to build a function in any language that takes a message m, an encryption e, and a modulus k (all positive integers), and takes m to the power of e modulo k. Your solution must not be a theoretical one, but one that would work on a reasonable computer such as your own, for RSA keys of currently used sizes such as 2048 bits.
Shortest code wins.

How are you measuring memory usage? Does this implicitly forbid using big integer libraries unless they come with documented guarantees about their memory usage?

(And if you're going to post a challenge about RSA, why not make it interesting by asking for an implementation of real RSA as opposed to academic useless-for-protecting-secrets RSA?)

@PeterTaylor: Big-integer libraries are fine. The main point of the limit is to prevent people from trying to store the entire exponentiated number and then evaluating it modulo m.

@PeterTaylor: Also, you can pose the question that includes PKCS #1 if you want.

Python – 5
Python 3 built-in function pow have third parameter. So Python 3 already have built-in RSA encoder
r=pow

Looks like we have a winner. I didn't know that. :\

In fact, the solution has a length of 0. Just use function pow for RSA encoding/decoding

Nope, it's still length 3 because you need to describe it. :P

Imho, this solution has a char count of 5. By just providing pow, the criteria 'build a function' is not satisfied.

Yeah, I suppose that's true.

Here's my first attempt at actually golfing something here:
Python – 69 61 55
r=lambda m,e,k:1 if e==0 else m**(e%2)*r(m*m%k,e/2,k)%k

This is a simple exponentiation by squaring algorithm.

02/15 13:17 – 61: Used lambda notation.
02/22 15:44 – 55: Removed some brackets as per grc's suggestions.

I believe the question specifies that the function should be named RSA

Sorry, that was unclear on my part.

You can save a few chars by removing unnecessary spaces and brackets: r=lambda m,e,k:1if e==0 else m**(e%2)*r(m*m%k,e/2,k)%k. And you might also be able to do this, but I haven't tested it: r=lambda m,e,k:e<1or m**(e%2)*r(m*m%k,e/2,k)%k. It uses e<1 instead of e==0 and or instead of if ... else.

Doesn't % have precedence over *?

In most C-derived languages, */% have equal precedence and are evaluated left-to-right.

Huh. I seem to have forgotten that. I generally use brackets where it might be ambiguous anyway, as I've been burned too many times by strict left-to-right evaluation to forget.

@grc: I'm pretty sure e<1 will return True, not 1.

@Joe Zeng: Yes, but True behaves as 1 when it is used with arithmetic operators.

Well, I learned something new. Will "or" also default to bitwise or when working with numbers?

java (83 chars)
if input is of BigInteger type:
public BigInteger r(BigInteger m,BigInteger e,BigInteger k){return m.modPow(e,k);}

Husk, 7 bytes
!¡o%⁰*³

Try it online!
Function that takes arguments: arg1=m (message), arg2=k (key/modulus), arg3=e (exponent/encryption).
Encoding takes about 10 seconds on [Try it online!] with a message of 12345678910, a 2048-bit key/modulus of 17335246217810680499565282364130282347913694411139706552337646969996795185310539972695213589521948877888710148108314183322475193115466538523720272848165926667358225384343389288464059692412384746831929390686202279817642231618920311152771862965772849228722380926373552800043250590230507345247504584516585217552163181827225685419709962073929610117852078754818132187957128758451536498778247147713136878727238232838512570562685513074673965992921930197584545660069134797478016576085619884280636191861425890311213983668804147423192923778212236303196414996652277121672303217925415867248268691221399027188630076689585126618899, and exponent/encryption of 65537.
Decoding is significantly longer when (as is usual) the decryption exponent d is much larger than the encryption exponent e.  But we can check that it works using small values: m=123, k=257 and e=7 (for which the decryption exponent d=55):
Try encoding
Try decoding

Nibbles, 4 bytes (8 nibbles)
=_`.@%*_

=_`.@%*_        # full program
=_`.@%*_$@      # with implicit args added
  `.            # repeatedly apply (while results are unique)
    @           # starting with arg2:
      *_$       #   multiply arg2 by result-so-far
     %   @      #   and modulo by arg1
=_              # finally, return result at index given by arg3

Full program that takes arguments: arg1=k (key/modulus), arg2=m (message), arg3=e (exponent/encryption).
Encoding is fast (screenshot below shows a message of 12345678910, a 2048-bit key/modulus, and exponent/encryption of 65537).

Decoding is significantly longer when (as is usual) the decryption exponent d is much larger than the encryption exponent e. But we can check that it works using small values: m=123, k=257 and e=7 (for which the decryption exponent d=55).

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Build a polyglot for Hello World
Produce a text file that prints "Hello World!" in as many programming languages as possible when compiled/interpreted, while also being as short as possible.
The score for your submission is calculated as C / 2 ^ ((L - 1) / 4), where "C" is the length of the text file in characters and "L" is the number of languages that the program is valid in. Lowest score wins, of course.

This question is similar to this other one, but in this case, you can share "Hello World" among some languages if you wish.

Does it have to be a whole program or just a valid command?

print("Hello World!")

Works in at least  Julia, Perl, PHP, Python2, Python3, Qbasic, R, Ruby ...

It also works in R and Julia (and surely in many other languages).

works in PHP too

This print() syntax is also valid in Transact-SQL. http://pastebin.com/is2mqRJC

@jdstankosky, that exact code not works in PHP. http://pastebin.com/9x6HactK

Kind of forcing the limits, but we can say it works in JavaScript too, as some command line interpreters provide print() function for outputting. http://pastebin.com/6fXtgFER

@manatwork Well, <?php print("Hello World!") ?> since you want to get specific, but I'm not counting the <?php ?> tags.

Works in TI-Basic too.

works in lua too

@gnibbler, doesn't work in PHP without the opening tags.

Works in Perl 6 too

Works in all derivatives of H9+ except for FISHQ9+ too

Assuming it is valid in the 8 languages listed, the score is at most(as in numerically) 21/2^((8-1)/4)=6.2433373537642856

It will print something out in browser JS, but not quite the intended text ;)

Works in JavaScript (V8)

JavaScript ES6, Oration, Vitsy, Minkolang score = 71.94703045766462
121 / 2^(3/4). Fun fact? I'm not trying to win, just to add as many languages as possible.
222 //X>"!dlroW olleH"Z
shush=0
alert("Hello World!")
sorry=`
listen
capture Hello World!`
$$$
=` >###      .O$r"!"rXr<`

What Vitsy sees
"Well, I'm a 1D language, so... for now, only the first line counts."
222 //X>"!dlroW ,olleH"Z
222                      push three twos
    //                   divide twice
      X>                 drop the result and carry on
        "!dlroW ,olleH"Z standard Hello, World! program

Thanks for the cookie, Vitsy :3
What JavaScript ES6 sees
222 //X>"!dlroW ,olleH"Z

"Let's see... You put the number 222 and then put something in a comment. Alright, sure, I'll roll with that."
shush=0

"You made a variable. Noted."
alert("Hello, World!")

"Ah, I see where you're going with this. I'll display that."
sorry=`
listen
capture Hello, World!`

"Oo! A multiline string! Now we're talking, ES6 rulez, ES5 drools!"
(EOF)

"Well, I'm done. Peace out."
What Oration sees
222 //X>"!dlroW ,olleH"Z

"This wasn't on my notes...! Best not do anything."
shush=0
alert("Hello, World!")
sorry=`

"Oh, here's some extra notes."
listen

"Listen..."
capture Hello, World!`

"...Hello, World!"
(EOF)

"thinks Nothing more! Great, I'm done here. breathes deeply"
Minkolang explanation
(Too lazy to create narrative. Might do later, the code took a while.) Irrelevant code replaced with # or omitted. Also, added comments C ... C.
222 ###>"!dlroW olleH"#
$$$  C this separates layers C
###>### #####.O$r"!"rXr<`

Layer 1, pt 1
222 ###>"!dlroW olleH"#
222                      C push three 2s C
   _                     C space; fall to the next layer C

Layer 2, pt 1
###>### #####.O$r"!"rXr<`
   >                       C go this way C
       _                   C fall to the next (first) layer C

Layer 1, pt 2
222 ###>"!dlroW olleH"#
       >"!dlroW olleH"   C go right and push those characters in that order C
                       _ C fall to the next layer C

Layer 2, pt 2
###>### #####.O$r"!"rXr<`
                       <  C starts here, going left C
                      r   C reverse stack C
                     X    C pop n (n = 2), and pop top n items on stack (2, 2) C
                    r     C reverse stack C
                 "!"      C push exclamation mark (for some reason, it's chopped off C
                r         C reverse stack C
              $O          C output stack as characters C
             .            C terminate program C

My child is proud of your submission. Here. Have a cookie. +1

'Hello World!'

Runs in several scripting languages, including PHP, GolfScript, APL, ...

Also AppleScript and Javascript :)

Won't Javascript include the quotes?

This works in PowerShell too.

Works in all derivatives of H9+ except for FISHQ9+ too

Probably the best answer, If you run in python shells would work too

Score of 0.84
H

Works in H9+ and HQ9+.
1 / 2 ^ ((2 - 1) / 4) = 0.84

You forgot: HQ9++, HI9+, FISHQ9+, CHIQRSX9+.

@user75200 I'm guessing those weren't as popular back in 2013

CoffeeScript and CJam, 46/2^((2-1)/4)=38.68
e###
"Hello, World!"
e###alert "Hello, World!"

ES8, Japt, TeaScript, C#, C++, C, ESMin, score: ~8.8
main=_=>"Hello World!"();

ES8, TeaScript and Japt see "Hello World!".

It won't work in Hello due to extra characters.

I'm pretty sure a lot of these (HQ9, Hello, and variants) don't count because they're not "real" programming languages.

Yes they're. They're real languages. But they may or mayn't work. And Hello++ discards non-h characters. Hello++++ discards all not part of "Hello world!"

According to PPCG standards, they're not.

And there's no HQ9.

Madbrain and [insert most BF derivatives here], 272 227 bytes
Just posting for fun, not to win c:
956658555658
852224222254
************
c4993c839941
1****1**+**+
01cc70776ccc
g+11+g++*11
 c003 c3c00
 1gg* 1*1gg
 0  c 0c0
 g  1 g1g
    0  0
    g  g[-]+[-->-[>>+>-----<<]<--<---]>-.>>>+.>>..+++.>>.>.<<<.+++.------.<<-.>>>>+.

NOTE: There is no TIO for Madbrain, so you'll have to trust me on this one. I did, however, write an (admittedly not really well-written (but hey, at least it works!)) interpreter for Madbrain, which is on the esolangs wiki.
Explanation
Madbrain sees: (I wrote this code c:)
956658555658
852224222254
************
c4993c839941
1****1**+**+
01cc70776ccc
g+11+g++*11
 c003 c3c00
 1gg* 1*1gg
 0  c 0c0
 g  1 g1g
    0  0
    g  g

I admit, Madbrain reaches the BF code, but it doesn't do anything, so I didn't include it here.
Brainfuck (and a lot of BF derivatives) sees:
++++++[-]+[-->-[>>+>-----<<]<--<---]>-.>>>+.>>..+++.>>.>.<<<.+++.------.<<-.>>>>+.

BF ignores everything that isn't ><+-.,[], so it ignores most of the Madbrain code. However, there are some +s in the Madbrain code (that's what the ++++++ is), so you need to add [-] after that which sets the current cell to 0.
The code after ++++++[-] is the code for printing Hello World!.

TI-BASIC and Pyth, 13/2^((2-1)/4)=10.93
"Hello World!

Also works in ESMin, Japt, Teascript, O, etc.

Feel free to write in any language you desire, it matters not when it was made.

puts "Hello world!"

Works in Ruby and Tcl