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

The challenge is simple. Give the shortest code possible to reproduce the classic 2-player game of pong http://en.wikipedia.org/wiki/Pong . The level of graphics and functionality should be as close as possible to this javascript demonstration http://codeincomplete.com/posts/2011/5/14/javascript_pong/demo.html (but without the extra options you can click on on the left or the frame, fps etc. information in the bottom right).

As always the code must be written in a free language (in both senses) and should be runnable on linux. Any libraries used must also be free, easily available and not be written for the purposes of this competition (and also not already contain a working version of Pong!).

Current lead: To be determined

share|improve this question
    
Honestly, this question is a little too difficult for code golf. The ball physics for Pong is pretty complicated. –  beary605 Mar 8 '13 at 2:18
    
@beary605, I don't think the ball physics are too complicated. My solution is 'as close as possible' to the javascript demonstration, and the physics are quite simple. –  boothby Mar 8 '13 at 21:21
    
Just for reference there are some other [code-golf]s that run to pretty long. Build an engine for a maze game, Noughts and Crosses (aka Tic-Tac-Toe) (both could use additional entries, who likes to "win" by default?), Write a small HTTP server, Self-Interpreting Interpreter, Self-compiling compiler, Compile Regexes ... –  dmckee Mar 8 '13 at 23:28
    
@felipa, Can you formalize 'as close as possible'? I don't know why my sed solution isn't in the lead. –  boothby Mar 12 '13 at 19:28
    
@boothby My mistake. I didn't have time to actually run the python code and made a wrong assumption. –  felipa Mar 13 '13 at 8:00

6 Answers 6

up vote 18 down vote accepted
+25

Javascript, 883 (+ 70 HTML)

c=document.getElementById('c').getContext('2d')
c.fillStyle="#FFF"
c.font="60px monospace"
w=s=1
p=q=a=b=0
m=n=190
x=300;y=235
u=-5;v=3
setInterval(function(){if(w&&!s)return;s=0
c.clearRect(0,0,640,480)
for(i=5;i<480;i+=20)c.fillRect(318,i,4,10)
m+=p;n+=q
m=m<0?0:m;m=m>380?380:m
n=n<0?0:n;n=n>380?380:n
x+=u;y+=v
if(y<=0){y=0;v=-v}
if(y>=470){y=470;v=-v}
if(x<=40&&x>=20&&y<m+110&&y>m-10){u=-u+0.2;v+=(y-m-45)/20}
if(x<=610&&x>=590&&y<n+110&&y>n-10){u=-u-0.2;v+=(y-n-45)/20}
if(x<-10){b++;x=360;y=235;u=5;w=1}
if(x>640){a++;x=280;y=235;u=-5;w=1}
c.fillText(a+" "+b,266,60)
c.fillRect(20,m,20,100)
c.fillRect(600,n,20,100)
c.fillRect(x,y,10,10)},30)
document.onkeydown=function(e){k=(e||window.event).keyCode;w=w?0:k=='27'?1:0;p=k=='65'?5:k=='81'?-5:p;q=k=='40'?5:k=='38'?-5:q;}
document.onkeyup=function(e){k=(e||window.event).keyCode;p=k=='65'||k=='81'?0:p;q=k=='38'||k=='40'?0:q}


/* Variable index:
a -> left player score
b -> right player score
c -> context
e -> event
i -> counter for dashed line
k -> keycode
m -> left paddle y
n -> right paddle y
p -> left paddle y velocity
q -> right paddle y velocity
s -> is start of game
u -> ball x velocity
v -> ball y velocity
w -> game is waiting (paused)
x -> ball x
y -> ball y
*/

The script can be placed at the end of <body> or called onLoad. It needs the following canvas element:

<canvas id="c"width="640"height="480"style="background:#000"></canvas>

Player 1 uses the q and a keys, and player 2 uses the p and l keys. Press the esc key to pause and any key to start/continue.

You can play it in your browser here.

I wasn't sure of the physics to use, so I started off with a simple reflection method and then added some variety and experimented with it a bit. The ball's velocity in the y direction is affected by where on the paddle you hit the ball, so you have some control over where the ball goes. The ball's velocity in the x direction slowly increases with each hit in the rally.

I suspect that it will be beaten quite easily by solutions using libraries, but I had fun making it in plain javascript.

share|improve this answer
    
That's a really nice implementation. –  felipa Mar 12 '13 at 14:15

sed, 35

Raising the bar a bit with a postage-stamp sed meditation.

s/> / >/
s/ </< /
s/0</0>/
s/>1/<1/

The meditation is enjoyed on sdin/stdout on two computers, not necessarily connected by a network. The meditation begins in the state

0         <       1

with guru zero on the left and one on the right. The angle bracket moves left and right, and if a guru maneuvers their number to contact the cursor as it comes to their side, their score is increased by one, and they become elated with joy.

The meditation is initiated by typing the above state into sed -f medi.sed, and the computer responds with the next state. The dutiful guru types that state into the meditation, reading aloud the next key they will press, with both gurus pressing the holy key to enter the future at the same time. The dutiful computer replies with the next state. This, in turn, is read aloud while typed in unison as with the last. Continue advancing into the future until infinite bliss is achieved.

Gurus desiring a challenge may play 'turbo' mode, wherein the gurus attempt to collaboratively predict the computer's next state, and typing it into the prompt instead of the current state. Gurus will have the wisdom to verify agreement between their predictions before entering the future.

share|improve this answer
11  
Dude... what did I just read? –  MrZander Mar 8 '13 at 23:43
2  
@MrZander Only through extensive contemplation may the wisdom of the meditation be revealed. This contemplation is best aided through execution of the program. –  boothby Mar 9 '13 at 18:00

Python (with pygame) 650 bytes

Features

  • 1 and 2 player modes - When the game begins, press 1 for 1 player, or 2 for 2 players. The game will not begin until one of these keys is pressed.
  • Increasing ball speed - Each volley, the ball speed is increased so that after 10 volleys it has increased by approximately 50%, after 20 it will be 50% faster than that, etc.
  • Variable ball deflection - Ball deflection is based on two factors: what portion of the paddle it strikes, and whether or not the paddle is moving upon impact. If the ball strikes the paddle near one of the ends, it will be deflected more strongly than if it strikes near the middle (almost as if it were a curved surface). Additionally, if the paddle is in motion, the motion of the paddle is added to the deflection. In order to obtain the strongest deflection, the ball must strike near the end of the paddle, and the paddle must be in motion towards that same end. This is very similar to the original Pong for Atari 2600.
  • Pause - The game may be paused at any time by pressing the Space bar. Play will resume upon pressing the space bar a second time.
  • Controls - As with the example, player 1 moves with the Q and A keys, and player 2 moves with P and L.

As a final note, I would like to request that this solution not be selected as the accepted answer, for various reasons.

from pygame import*
init();d=display;s=d.set_mode((640,480))
g=p=16;j=q=80;x=y=200;o=t=h=v=1;z=m=n=0;w=[255]*3
while s.fill(time.wait(3)):
 event.get();k=key.get_pressed();t^=o*k[32];o=1-k[32];z=z or-k[49]-k[50]*2;e=k[113]-k[97];f=[k[112]-k[108],(h>0)*cmp(y,q-32)][z];a=p<g;b=q-[y,x][a]
 if p%608<g:m,n,p,h,v=[m+1-a,m,n+a,n,g+a*592,p,1-a*2,h/-.96,1,b/32.+~[f,e][a]][-g<b<j::2]
 for r in[(0,x,g,j),(624,y,g,j),(p,q,g,g)]+[(316,i*31,8,15)for i in range(g)]:draw.rect(s,w,r)
 if z*t:v*=(0<q<464)*2-1;x-=(0<x-e<400)*e/.6;y-=(0<y-f<400)*f/.6;p+=h;q+=v
 c=font.SysFont('monospace',j,1).render('%3d %%-3d'%m%n,1,w);s.blit(c,(320-c.get_width()/2,0));d.flip()

Sample screen capture:

Note: the font used for the score may vary from system to system.

share|improve this answer
    
The score shows in the left half for me, and I think the deflection is too strong, but it's pretty cool anyway :) –  aditsu Mar 14 '13 at 8:28
    
@aditsu are you operating under linux? I'll see if I can find an alternative that works regardless of the selected font face. The idea behind the deflection is that it would be possible to deflect the ball at a faster speed (maximum 2.5 on my scale) than the paddle can move (1.67). This is only possible if you give it some 'spin'. If the paddle isn't moving when the ball strikes, the maximum is velocity will be 1.5. –  primo Mar 14 '13 at 8:38
    
Yes I'm using Linux. I find it strange that the ball can actually go "back" (up or down) after hitting the paddle, instead of continuing in the same direction (perhaps at a different angle). But maybe the Atari version did that, I don't know. –  aditsu Mar 14 '13 at 9:07
    
@aditsu It cost a few bytes, but I believe the score should be centered regardless of the font chosen (so long as it is monospace). Let me know if it works for you. And yes, the deflection is very similar (although a smoother distribution) to the Atari version I was familiar with. If you imagine the paddle as a (convexly) curved surface (like an air hockey paddle), I think it should be more intuitive. –  primo Mar 14 '13 at 11:22
    
Yes it's centered now –  aditsu Mar 14 '13 at 16:53

HTML & JavaScript (take 2) - 525

Since the OP didn't seem to care much about the "as close as possible" part, here's an alternative solution that I mercilessly simplified, stripped and golfed. Q/A and P/L to play, but every other key also has an effect. Again, the code is fully self-contained and I tested it in Chromium 25 on Linux. I can golf it even further if you can accept small bugs or greater degradation of graphics quality/gameplay.

<canvas id=c><script>C=c.getContext('2d');f=C.fillRect.bind(C)
S=[-1,I=J=0];A=B=210;X=Y=1
function g(n){++S[n];N=Math.random(M=n*613+9)*471}D=document
D.onkeydown=D.onkeyup=function(e){d=!!e.type[5];k=e.keyCode
k&1?I=k&16?d:-d:J=k&4?-d:d}
g(0);setInterval(function(){A-=A<I|A>420+I?0:I
B-=B<J|B>420+J?0:J
M+=X;N+=Y
N<0|N>471?Y=-Y:0
M==622&N>B&N<B+51|M==9&N>A&N<A+51?X=-X:M>630?g(0):M||g(1)
f(0,0,c.width=640,c.height=480)
C.fillStyle='tan';C.font='4em x';C.fillText(S,280,60)
f(0,A,9,60);f(631,B,9,60);f(M,N,9,9)},6)</script>

Thanks Shmiddty

share|improve this answer
    
I don't understand the objection. As far as I can recall, the 715 byte version (edited 3 hours before this post) is nearly identical to the original version of Pong I had for my Atari 2600. –  primo Mar 13 '13 at 1:50
    
@primo I'm assuming you're talking about my implied claim that your solution does not meet the "as close as possible" criterion. Well, the OP did not mention the Atari 2600 version, but a specific javascript implementation that he linked to. And at first sight there are 2 glaring differences in your code: no computer player and no "7-segment" score display. There are probably a lot more differences in the "mechanics". If these things are not important, then I think this solution should be valid too. –  aditsu Mar 13 '13 at 2:09
    
This is my mistake. I did really mean "as close as possible" so your first solution is the best so far. –  felipa Mar 13 '13 at 8:01
    
you can remove the c=window.c. You're assigning a global variable to itself. –  Shmiddty Mar 13 '13 at 22:17
    
You can save 1 more character by moving ++S[n] inside of .random(++S[n]) –  Shmiddty Mar 13 '13 at 22:35

HTML & JavaScript - 1663

Against my better judgment, I took the crazy approach of golfing the actual code from the demo. I removed some features and interface elements, but generally it works exactly the same - 0, 1 or 2 to choose the number of human players, Q/A and P/L to move.

Unless I made some mistakes, gameplay should be identical, pixel for pixel and millisecond for millisecond, to the original at 640*480 (hint: resizing the browser window changes the game size in the demo). It just doesn't give instructions, doesn't announce the winner and doesn't handle esc.

The code is fully self-contained and I tested it in Chromium 25 on Linux. Firefox doesn't like it very much.

<body bgcolor=0><canvas id=c height=480><script>R=Math.random
C=c.getContext('2d');f=C.fillRect.bind(C)
S=[l=G=I=J=K=L=0,0];r=17;u=463;o=24;q=12;z=10;s=640;v=36
function T(z,t,u,v){P=0;if(e=v*E-u*F){a=(u*t-v*z)/e;b=(E*t-F*z)/e
a<0|a>1|b<0|b>1?0:P={x:M+a*E,y:N+a*F,d:u,s:0,X:X,Y:Y}}}function
i(p,q,h){T(p-22*(E<0),q,0,h)
P?0:T(p,q-h*(F<0),22,0)}function
U(p){if(p.a)if(M<p.x&X<0|M>p.x+q&X>0)p.u=0
else{P=p.P;if(P&&P.X*X>0&P.Y*Y>0&P.s<p.l/z)P.s+=t
else{E=X*z;F=Y*z;i(M-p.x+5,s*q,s*o)
if(p.P=P){y=P.y;while(y<r|y>u)y=y<r?34-y:y>u?u+u-y:y
P.y=y+R(e=(p.l+2)*(X<0?M-p.x-q:p.x-M)/64)*2*e-e}}P?p.u=P.y<p.y+25?1:P.y>p.y+35?-1:0:0}y=p.y-p.u*t*198
p.y=y<q?q:y>408?408:y}function
W(n,x){a=9.6;b=[~8,3,62,31,75,93,~2,7,-1,u][n]
b&4&&f(x,o,v,a);b&64&&f(x,o,a,o)
b&2&&f(x+v,o,-a,o);b&8&&f(x,43.2,v,a)
b&32&&f(x,48,a,o);b&1&&f(x+v,48,-a,o)
b&16&&f(x,72,v,-a)}A={u:0,x:0,y:210};B={u:0,x:628,y:210}
function g(n){if(++S[n]>8)G=A.a=B.a=0
else{N=R(M=n?635:5)*446+r;Y=157.5;X=n?-Y:Y
A.l=z+S[0]-S[1];B.l=20-A.l}}D=document
D.onkeydown=D.onkeyup=function(e){d=!!e.type[5]
k=e.keyCode-45;if(k>2&k<6&d&!G){G=S=[-1,0];A.a=k<4;B.a=k<5
g(0)}k^31?k^35?k^20?k^v?0:I=d:J=d:K=d:L=d
A.a?0:A.u=I-J;B.a?0:B.u=K-L}
setInterval(function(){t=new Date()/1000-l;l+=t;U(A);U(B)
if(G){E=t*X+4*t*t;F=t*Y+4*t*t
x=M+E;y=N+F;m=X+t*(X>0?8:-8);n=Y+t*(Y>0?8:-8)
if(n>0&y>u){y=u;n=-n}if(n<0&y<r){y=r;n=-n}p=m<0?A:B
i(M-p.x+5,N-p.y+5,70)
if(P){if(P.d){y=P.y;n=-n}else{x=P.x;m=-m}n*=n*p.u<0?.5:p.u?1.5:1}M=x;N=y
X=m;Y=n;M>645?g(0):M<-5&&g(1)}c.width=s;C.fillStyle='#fff'
f(0,0,s,q);f(0,468,s,q);for(j=o;j--;)f(314,6+o*j,q,q)
W(S[0],266.5);W(S[1],338.5)
f(0,A.y,q,60);f(s,B.y,-q,60);G&&f(M-5,N-5,z,z)},50/3)</script>

Some credits to Shmiddty for improvements

share|improve this answer

Just a joke answer to set the bar low. :)

J

   '0|.|0'
0|.|0
share|improve this answer
    
Your answer honours your name :) –  tomsmeding Jul 30 '13 at 21:39

Your Answer

 
discard

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

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