Class: BTetrisKp::Piece

Inherits:
Object
  • Object
show all
Defined in:
lib/btetris_kp/core/piece.rb

Overview

class representing actual piece in game

Instance Method Summary collapse

Constructor Details

#initialize(board, posx, posy, piece_nr) ⇒ Piece

Returns a new instance of Piece.



6
7
8
9
10
11
12
13
14
# File 'lib/btetris_kp/core/piece.rb', line 6

def initialize(board, posx, posy, piece_nr)
  @board = board
  @posx = posx
  @posy = posy
  @nr = piece_nr
  @rot = 0
  @color = rand(Const::TILE_COLORS_NR) + 1
  @piece = Const::TILES[@nr][@rot]
end

Instance Method Details

#can_be_set?Boolean

returns true if there is no collision with peace on board

Returns:

  • (Boolean)


49
50
51
52
53
54
55
56
57
58
59
# File 'lib/btetris_kp/core/piece.rb', line 49

def can_be_set?
  return false if @posx < 0 || @posy < 0
  @piece.each_with_index do |row, x|
    row.each_with_index do |val, y|
      return false if @posx + x > Const::PNR_VER - 1 ||
                      @posy + y > Const::PNR_HOR - 1
      return false if @board[@posx + x][@posy + y] > 0 && val > 0
    end
  end
  true
end

#move_down!Object

moves piece one block down



32
33
34
# File 'lib/btetris_kp/core/piece.rb', line 32

def move_down!
  @posx += 1
end

#move_left!Object

moves piece one block to the left



17
18
19
# File 'lib/btetris_kp/core/piece.rb', line 17

def move_left!
  @posy -= 1
end

#move_right!Object

moves piece one block to the right



22
23
24
# File 'lib/btetris_kp/core/piece.rb', line 22

def move_right!
  @posy += 1
end

#move_up!Object

moves piece one block up



27
28
29
# File 'lib/btetris_kp/core/piece.rb', line 27

def move_up!
  @posx -= 1
end

#rotate_left!Object

rotates piece left



37
38
39
40
# File 'lib/btetris_kp/core/piece.rb', line 37

def rotate_left!
  @rot = (@rot - 1) % Const::TILES[@nr].size
  @piece = Const::TILES[@nr][@rot]
end

#rotate_right!Object

rotates piece right



43
44
45
46
# File 'lib/btetris_kp/core/piece.rb', line 43

def rotate_right!
  @rot = (@rot + 1) % Const::TILES[@nr].size
  @piece = Const::TILES[@nr][@rot]
end

#set_on_boardObject

sets peace on board



62
63
64
65
66
67
68
# File 'lib/btetris_kp/core/piece.rb', line 62

def set_on_board
  @piece.each_with_index do |row, x|
    row.each_with_index do |val, y|
      @board[@posx + x][@posy + y] = @color if val == 1
    end
  end
end

#unset_on_boardObject

unsets peace from board



71
72
73
74
75
76
77
# File 'lib/btetris_kp/core/piece.rb', line 71

def unset_on_board
  @piece.each_with_index do |row, x|
    row.each_with_index do |val, y|
      @board[@posx + x][@posy + y] = 0 if val == 1
    end
  end
end