Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
check for collision before rotating piece
  • Loading branch information
lau committed Apr 8, 2013
1 parent 4ef4ced commit 3c532d0
Show file tree
Hide file tree
Showing 4 changed files with 44 additions and 8 deletions.
18 changes: 14 additions & 4 deletions lib/letris/board.rb
Expand Up @@ -8,7 +8,6 @@ class Board
BOARD_HEIGHT = 20
PIECE_INITIAL_POSITION_X = 4
PIECE_INITIAL_POSITION_Y = 19

MAX_POSSIBLE_PIECE_HEIGHT = 4
MAX_POSSIBLE_PIECE_WIDTH = 4

Expand Down Expand Up @@ -125,6 +124,17 @@ def move_piece_right
@current_piece_pos[0] = @current_piece_pos[0]+1
end

def try_rotate_piece
rotated = @current_piece.dup
rotated.change_to_next_state!
if would_piece_collide_at_position?(cur_piece_pos_x, cur_piece_pos_y, rotated)
return false
else
rotate_piece
return true
end
end

def rotate_piece
@current_piece.change_to_next_state!
end
Expand Down Expand Up @@ -152,10 +162,10 @@ def is_out_of_bounds_at_position(p_x, p_y, piece = @current_piece)

def would_piece_collide_at_position?(p_x, p_y, piece = @current_piece)
return true if is_out_of_bounds_at_position(p_x, p_y, piece)
4.times do |y|
4.times do |x|
MAX_POSSIBLE_PIECE_HEIGHT.times do |y|
MAX_POSSIBLE_PIECE_WIDTH.times do |x|
if p_y+y <= 19 # we don't look at rows above no. 19 (top row)
return true if @current_piece.has_tile?(x,y) && @rows[p_y+y][p_x+x]
return true if piece.has_tile?(x,y) && @rows[p_y+y][p_x+x]
end
end
end
Expand Down
6 changes: 3 additions & 3 deletions lib/letris/piece_type.rb
Expand Up @@ -8,12 +8,12 @@ class PieceType
],

:i => [
["XXXX"],

["X",
"X",
"X",
"X"]
"X"],

["XXXX"]
],

:t => [
Expand Down
2 changes: 1 addition & 1 deletion run.rb
Expand Up @@ -40,7 +40,7 @@ def draw_board(board)
command = STDIN.getc
end
if command == 'r'
board.rotate_piece
board.try_rotate_piece
draw_board board
end
if command=='h'
Expand Down
26 changes: 26 additions & 0 deletions spec/unit/board_spec.rb
Expand Up @@ -28,6 +28,32 @@
end
end

describe 'When trying to rotate a piece and another brick is in the way' do
before do
@board = Letris::Board.new
# Place an I piece upright at the bottom of the board
@board.add_new_piece_by_name(:i)
4.times { @board.move_piece_right }
20.times { @board.move_piece_down }
# Place another I piece almost at the bottom, next to the first one
@board.add_new_piece_by_name(:i)
3.times { @board.move_piece_right }
18.times { @board.move_piece_down }
end


it 'should return false' do
@board.try_rotate_piece.must_equal false
end

it 'should not be rotated' do
@board.try_rotate_piece
# If there is a piece at this positiom the second piece
# is still upright and thus not rotated
@board.current_piece_has_tile_at?(7,4).must_equal true
end
end

describe "When trying to move a piece right and the wall is in the way" do
before do
@board = Letris::Board.new
Expand Down

0 comments on commit 3c532d0

Please sign in to comment.