我正在RoR上構建一個井字遊戲。目前,整個董事會成立,下面有一個表格來跟蹤這些舉動。我被告知要用這個模型來弄清楚這樣的事情,比如有一個勝利者(連續3個),一個領帶(全盤)等等。我認爲我有,但顯然不是。不知道我在模型中的players
方法做錯了什麼。將數據從查看錶單傳輸到模型方法
show.html.erb
:
<div id="board" align = center>
<table>
<tr>
<td data-position="0" class="square <%= class_for_move(0)%>"></td>
<td data-position="1" class="square v <%= class_for_move(1)%>"></td>
<td data-position="2" class="square <%= class_for_move(2)%>"></td>
</tr>
<tr>
<td data-position="3" class="square h <%= class_for_move(3)%>"></td>
<td data-position="4" class="square v h <%= class_for_move(4)%>"></td>
<td data-position="5" class="square h <%= class_for_move(5)%>"></td>
</tr>
<tr>
<td data-position="6" class="square <%= class_for_move(6)%>"></td>
<td data-position="7" class="square v <%= class_for_move(7)%>"></td>
<td data-position="8" class="square <%= class_for_move(8)%>"></td>
</tr>
</table>
</div>
<table>
<tr>
<td><%= @game.player_1 %></td>
<td><%= @game.player_2 %></td>
</tr>
<tr>
<td>X</td>
<td>O</td>
</tr>
</table>
<%= link_to "Play Again", games_path %>
<%= nested_form_for @game do |f| %>
<%= f.fields_for :moves do |move_form| %>
<div id="table" data-current-player="<%=session[:current_player] %>">
<%= move_form.label :position %><br>
<%= move_form.text_field :player, data: {position: move_form.object.position} %>
<%= move_form.hidden_field :id %>
</div>
<% end %>
<input type="Submit">
<% end %>
game.rb
:
class Game < ActiveRecord::Base
has_many :moves
after_create :initialize_moves
accepts_nested_attributes_for :moves
def initialize_moves
9.times do |i|
Move.create(position: i, game:self)
end
end
def players(number)
move = moves.find_by(position: number)
player = move.player
end
def tie?
end
def winner?
if players(0) == players(1) && players(1) == players(2)
return players(0)
end
end
end
games_controller
:
class GamesController < ApplicationController
def create
@game = Game.new(game_params)
@game.save
redirect_to @game
end
def update
@game = Game.find(params[:id])
@game.update(game_params)
if @game.tie?
flash[:error] = "Game over. 'Tis a tie."
elsif @game.winner?
flash[:notice] = "Winner is #{session[:current_player]}"
else
switch_player
end
redirect_to @game
end
def show
@game = Game.find(params[:id])
end
def switch_player
session[:current_player] = session[:current_player] == "X" ? "O" : "X"
end
private
def game_params
params.require(:game).permit(:player_1, :player_2, moves_attributes: [:player, :id])
end
end
當我跑我有什麼的那一刻,遊戲劇本,直到我有一個三在一排(只做0,1,2時隙測試),switchin g球員和演技正常。一旦三連串成立,它就會保持在當前玩家的位置,並且不會切換。它不會結束遊戲,或者給我閃光燈通知。只要堅持當前的球員。如果我嘗試添加一個試圖放入另一個獲勝位置組合的elsif,也是一樣。
我意識到這可能是初級水平的東西,但我似乎無法包圍我的頭,並且到目前爲止還沒有發現任何有用的東西。而且,如果聲明路線不是正確的路線,我願意換一種方式。我現在無法想出另一種方式。
任何幫助,非常感謝。
哇,似曾相識... – 2014-09-25 17:47:28
我用不同的信息設置了一個新的問題,以避免用大多數相同的問題淹沒網站。 – Briknthewall 2014-09-25 18:03:30
有點想通了......雖然看起來你正在取得進展。祝你好運,它隨着時間的推移變得更加困惑。 – 2014-09-25 18:06:38