This repository has been archived by the owner on Aug 7, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathPuzzle.rb
89 lines (84 loc) · 2.26 KB
/
Puzzle.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
class Puzzle
attr_accessor :answers,:questions,:total_cnt,:side_cnt,:moves,:empty_no,:difficult
def initialize(in_num=9)
@side_cnt=Math::sqrt(in_num).truncate
@total_cnt=@side_cnt*@side_cnt
@answers=Array.new
@questions=Array.new
@moves=Array.new
@@shuffle_cnt = 0
@empty_no=@total_cnt
@difficult=:Normal
generate_answer
@questions=Marshal.load(Marshal.dump(@answers))
end
def set_shuffle_cnt()
case @difficult
when :Easy
@@shuffle_cnt = @total_cnt * 3
when :Normal
@@shuffle_cnt = @total_cnt * 6
when :Hard
@@shuffle_cnt = @total_cnt *10
end
end
def generate_answer()
@answers=[*0..@total_cnt].to_a
end
def generate_question()
set_shuffle_cnt
@@shuffle_cnt.times do
random_move
end
random_move if complete?
end
def complete?()
if (@answers == @questions)
@moves=Array.new
return true
else
return false
end
end
def set_move()
#動かせるセルを特定する
@moves[1]=@empty_no-1 #空白から右のセル
@moves[2]=@empty_no+1 #空白から左のセル
@moves[3]=@empty_no+@side_cnt #空白から下のセル
@moves[4]=@empty_no-@side_cnt #空白から上のセル
tmp=@empty_no % @side_cnt
#枠外にはみ出たものはゼロにする
@moves[4]=0 if (@moves[4]<0)
@moves[3]=0 if (@moves[3]>@total_cnt)
@moves[2]=0 if (tmp==0)
@moves[1]=0 if (tmp==1)
end
def random_move()
set_move
while(true)
tmp=(rand(4)+1).truncate #動かすセル1-4をランダムにひとつ選ぶ
if (@moves[tmp]!=0)
swap_empty_cell(@moves[tmp])
return
end
end
end
def move(in_move_no)
return if complete?
if (in_move_no.to_i >=1 and in_move_no.to_i <=@total_cnt)
set_move
(1..4).each {|i| #4つの動かせるセルのどれかを選択されたか?
if (@moves[i]==in_move_no.to_i)
swap_empty_cell(in_move_no.to_i)
end
}
end
end
def swap_empty_cell(in_move_no)
tmp=@questions[in_move_no.to_i]
@questions[in_move_no.to_i]=@questions[@empty_no]
@questions[@empty_no]=tmp
@empty_no=in_move_no.to_i
end
private :random_move ,:set_shuffle_cnt ,:swap_empty_cell
end