public final int UP=1, DOWN=2, LEFT=4, RIGHT=8;

This is common practice where something needs a value but it's not any basic data type. I'm using these for directions. The question is, why did I pick 1, 2, 4, and 8? Why not 1, 2, 3, and 4 or 0, 1, 2 and 3? The reason is the binary representations of the numbers:

1 | 1 |

2 | 10 |

4 | 100 |

8 | 1000 |

Notice each number has exactly one '1' and they're in different places. Now, about basic bitwise operations- I used | (OR) and & (AND). What happens when you bitwise-OR two numbers together is if either one of the numbers has a 1 in that spot, so will the result. If both numbers have a 0 in that spot, the result will have a 0. Example:

9 | 5 = 1001 | 0101 = 1101 = 13

When you bitwise-AND two numbers together, BOTH of the numbers must have a 1 in a position for the result to be 1 in that position, and if EITHER number has a 0 in a position, the result will have a 0 in that postion. Example:

9 & 5 = 1001 & 0101 = 0001 = 1

In my program, I do this to identify directions. First of all, a |= b means a = a | b. The same thing can be done with the & operation. So it seems like the bounce operation can only take in 4 possible integers, but in reality it can take in 16. It will only effectively process 8, though. Let's take a look at the code again:

public void bounce(int direction) { if ((direction&UP)>0) v=-9*Math.abs(v)/10; else if ((direction&DOWN)>0) v=Math.abs(v); if ((direction&LEFT)>0) vx=-Math.abs(vx); else if ((direction&RIGHT)>0) vx=Math.abs(vx); }

direction(%16) | binary | direction&UP | direction&DOWN | direction&LEFT | direction&RIGHT | Actual direction |
---|---|---|---|---|---|---|

0 | 0000 | 0 | 0 | 0 | 0 | none |

1 | 0001 | 1 | 0 | 0 | 0 | up |

2 | 0010 | 0 | 2 | 0 | 0 | down |

3 | 0011 | 1 | 2 | 0 | 0 | up |

4 | 0100 | 0 | 0 | 4 | 0 | left |

5 | 0101 | 1 | 0 | 4 | 0 | up/left |

6 | 0110 | 0 | 2 | 4 | 0 | down/left |

7 | 0111 | 1 | 2 | 4 | 0 | up/left |

8 | 1000 | 0 | 0 | 0 | 8 | right |

9 | 1001 | 1 | 0 | 0 | 8 | up/right |

10 | 1010 | 0 | 2 | 0 | 8 | down/right |

11 | 1011 | 1 | 2 | 0 | 8 | up/right |

12 | 1100 | 0 | 0 | 4 | 8 | left |

13 | 1101 | 1 | 0 | 4 | 8 | up/left |

14 | 1110 | 0 | 2 | 4 | 8 | down/left |

15 | 1111 | 1 | 2 | 4 | 8 | up/left |