Class: Game

Inherits:
Object
  • Object
show all
Defined in:
lib/tetris/game.rb

Instance Method Summary collapse

Constructor Details

#initialize(w, h, speed, font_file) ⇒ Game

Returns a new instance of Game.



2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/tetris/game.rb', line 2

def initialize(w, h, speed, font_file)
  # Setup rubygame stuff
  @screen = Rubygame::Screen.new([w * $TileSize, h * $TileSize], 0, 
                                 [Rubygame::HWSURFACE, Rubygame::DOUBLEBUF])
  @queue = Rubygame::EventQueue.new
  @clock = Rubygame::Clock.new
  @clock.target_framerate = 30
  Rubygame::TTF.setup
  @ttf = Rubygame::TTF.new(font_file, 20)

  # Setup the game of tetris
  @screen.title = "Tetris"
  @map = Map.new(w, h)
  @piece = Piece.new
  @background = :white
  @speed = speed
  @step = 0
  @score = 0
end

Instance Method Details

#drawObject



72
73
74
75
76
77
78
79
80
81
# File 'lib/tetris/game.rb', line 72

def draw
  @screen.fill(@background)
  
  draw_squares = lambda {|x, y, colour| draw_square(x, y, colour)}
  @piece.squares.each &draw_squares
  @map.squares.each &draw_squares

  @ttf.render("Score: " + @score.to_s, true, :black).blit(@screen, [0,0])
  @screen.flip
end

#draw_square(x, y, colour, border = true) ⇒ Object



61
62
63
64
65
66
67
68
69
70
# File 'lib/tetris/game.rb', line 61

def draw_square(x, y, colour, border=true)
  # Setup the points for SDL
  x_pos = x * $TileSize
  y_pos = y * $TileSize
  pt1 = [x_pos, y_pos]
  pt2 = [x_pos + $TileSize, y_pos + $TileSize]
  # Draw the square and then the border
  @screen.draw_box_s(pt1, pt2, colour)
  @screen.draw_box(pt1, pt2, :black) if border
end

#runObject



22
23
24
25
26
27
# File 'lib/tetris/game.rb', line 22

def run
  loop do
    update(@clock.tick)
    draw
  end
end

#update(time_delta) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/tetris/game.rb', line 29

def update(time_delta)
  # Process the event queue
  @queue.each do |ev|
    case ev
    when Rubygame::KeyDownEvent
      case(ev.key)
      when Rubygame::K_LEFT
        @piece.move(-1, 0, @map)
      when Rubygame::K_RIGHT
        @piece.move(1, 0, @map)
      when Rubygame::K_DOWN
        @piece.move(0, 1, @map)
      when Rubygame::K_UP
        @piece.rotate(@map)
      when Rubygame::K_SPACE
        @piece.drop(@map)
      end
    when Rubygame::QuitEvent
      Rubygame.quit
      exit        
    end
  end
  # Update the game state
  @step += time_delta
  if @step > @speed
    @step -= @speed
    @piece.move(0, 1, @map)
  end
  @piece.update(@map) {|x, y, colour| @map.set(x, y, colour)}
  @score += @map.update
end