Best of Ruby Quiz Pragmatic programmers phần 9

kết thúc cuối def khởi tạo (hình vuông) - hình vuông = hình vuông kết thúc bao gồm Làm thế nào tôi biết được câu trả lời cho các trường hợp thử nghiệm được mã hóa trước khi tôi đã có một chương trình làm việc? Nó không phải chỉ là tôi đang ở gần với tác giả bài kiểm tra, tôi đảm bảo với bạn. | Answer 22. Learning Tic-Tac-Toe 226 def index if index 6 c index - 5 .to_s elsif index 3 b index - 2 .to_s else a index 1 .to_s end end def initialize squares @square s square s end include SquaresContainer def indices if indice 2 super indice s 0 indices 1 3 elsif indices 0 .is_a Fixnum super indices 0 else super indices 0 .to_s end end def each_row rows 0 1 2 3 4 5 6 7 8 0 3 6 1 4 7 2 5 8 0 4 8 2 4 6 do e yield e e end end def moves moves @ do s i moves i if s end moves end def won each_row do row return X if 3 return O if 3 end return if blanks 0 false end Report erratum Answer 22. Learning Tic-Tac-Toe 227 def to_s end end end Breaking that code down we see that our tools live in the TicTacToe namespace. The first of those is a mix-in module called SquaresCon-tainer. It provides methods for indexing a given square and counting blanks Xs and Os. We then reach the definition of a TicTacToe Board. This begins by defining a helper class called Row. Row accepts an array of squares and their corresponding board names or positions on the actual Board. it includes SquaresContainer so we get access to all its methods. Finally it defines a helper method to_board_name you can use to ask Row what a given square would be called in the Board object. Now we can actually dig into how Board works. it begins by creating class methods that translate between a chess-like square name such as b3 and the internal index representation. We can see from initialize that Board is just a collection of squares. We can also see right under that that it too includes SquaresContainer. However Board overrides the method to allow indexing by name x and y indices or a single 0 to 8 index. Next we run into Board s primary iterator each_row . The method builds a list of all the Rows we care about in tic-tac-toe three across three down and two .

Không thể tạo bản xem trước, hãy bấm tải xuống
TỪ KHÓA LIÊN QUAN
TÀI LIỆU MỚI ĐĂNG
34    71    1    26-06-2024
Đã phát hiện trình chặn quảng cáo AdBlock
Trang web này phụ thuộc vào doanh thu từ số lần hiển thị quảng cáo để tồn tại. Vui lòng tắt trình chặn quảng cáo của bạn hoặc tạm dừng tính năng chặn quảng cáo cho trang web này.