| Class | NimController |
| In: |
app/controllers/nim_controller.rb
|
| Parent: | ApplicationController |
# File app/controllers/nim_controller.rb, line 71
71: def backspace
72: session[:sticks]=nil
73: redirect_to :action => "first_time"
74: end
# File app/controllers/nim_controller.rb, line 23
23: def extras
24: @sticks=get_sticks
25: @title="#{@sticks} sticks left"
26: @user_choice=session[:user_choice]
27: @computer_choice=session[:computer_choice]
28: @displayed=get_displayed
29: if @sticks == 0
30: session[:sticks]=nil
31: end
32: end
# File app/controllers/nim_controller.rb, line 2 2: def first_time 3: session[:user_choice]=nil 4: session[:computer_choice]=nil 5: session[:display]=nil 6: redirect_to :action => "index" 7: end
# File app/controllers/nim_controller.rb, line 17
17: def get_computer_choice
18: session[:computer_choice] ||= 0
19: end
# File app/controllers/nim_controller.rb, line 11
11: def get_sticks
12: session[:sticks] ||= 7 + rand(10)
13: end
# File app/controllers/nim_controller.rb, line 8
8: def get_title
9: 'pick 1-3 sticks; pick the last one, and you lose'
10: end
# File app/controllers/nim_controller.rb, line 14
14: def get_user_choice
15: session[:user_choice] ||= 0
16: end
# File app/controllers/nim_controller.rb, line 33
33: def selected(user_choice)
34: session[:user_choice] = user_choice.to_i
35: if session[:sticks] && (session[:user_choice] <= session[:sticks])
36: #we have a legal move
37: session[:sticks] -= session[:user_choice]
38: if session[:sticks]==0 #computer has won
39: session[:displayed]=
40: 'remember, the computer and you take turns '+
41: 'to pick 1..3 sticks. If you pick the last '+
42: 'one, you lose, as you just did ;-)'
43: session[:computer_choice]=nil
44: # session[:choices]=nil
45: else #computer makes move
46: session[:computer_choice]= (session[:sticks]-1) % 4
47: #since 1,5,9,.. is a series of losing positions,
48: #we try to get the opponent to one of them
49: if session[:computer_choice] == 0
50: #we are losing,
51: #because sticks=4n+1, a losing position
52: session[:computer_choice] = 1+ rand(3)
53: #doesn't matter what we pick here, long as it
54: #isn't more than the sticks available.
55: if session[:computer_choice] >
56: session[:sticks]
57: session[:computer_choice] =
58: session[:sticks]
59: end
60: end
61: session[:sticks] -= session[:computer_choice]
62: if session[:sticks] == 0 #user has won
63: session[:displayed] = 'you won!'
64: # session[:choices]=[]
65: else
66: session[:displayed]=nil
67: end
68: end
69: end
70: end