Skip to content

Instantly share code, notes, and snippets.

@lnit
Last active May 9, 2026 14:46
Show Gist options
  • Select an option

  • Save lnit/a56dc8fc27fb9013382a92343f5f3fdc to your computer and use it in GitHub Desktop.

Select an option

Save lnit/a56dc8fc27fb9013382a92343f5f3fdc to your computer and use it in GitHub Desktop.
Spinelで動くTic Tac Toe
class TicTacToe
# 0: 空, 1: プレイヤー1, 2: プレイヤー2
MARKS = ["◯", "✕", " "]
WIN_PATTERNS = [
[0, 1, 2], [3, 4, 5], [6, 7, 8], # 横
[0, 3, 6], [1, 4, 7], [2, 5, 8], # 縦
[0, 4, 8], [2, 4, 6] # 斜め
].freeze
def initialize
@board = [2, 2, 2, 2, 2, 2, 2, 2, 2]
@current_player = 0
end
def play
clear_screen
puts "=== ◯✕ゲーム ==="
puts "プレイヤー1: #{MARKS[0]} プレイヤー2: #{MARKS[1]}"
puts "位置は1-9の番号で指定してください"
puts "\n何かキーを押してスタート..."
gets
loop do
display_board
break if game_over?
make_move
switch_player
end
display_result
end
private
def clear_screen
system("clear") || system("cls")
end
def display_board
clear_screen
puts "=== ◯✕ゲーム ==="
puts "\n現在のボード:"
puts " #{cell(0)} │ #{cell(1)} │ #{cell(2)} "
puts "───┼───┼───"
puts " #{cell(3)} │ #{cell(4)} │ #{cell(5)} "
puts "───┼───┼───"
puts " #{cell(6)} │ #{cell(7)} │ #{cell(8)} "
puts "\n位置番号:"
puts " 1 │ 2 │ 3 "
puts "───┼───┼───"
puts " 4 │ 5 │ 6 "
puts "───┼───┼───"
puts " 7 │ 8 │ 9 "
puts
end
def cell(index)
MARKS[@board[index]]
end
def make_move
loop do
print "#{MARKS[@current_player]} のターン (1-9): "
input = gets.chomp
position = input.to_i - 1
if valid_move?(position)
@board[position] = @current_player
break
else
puts "\n❌ 無効な入力です。空いているマス(1-9)を選んでください。"
sleep(1.5)
display_board
end
end
end
def valid_move?(position)
position.between?(0, 8) && @board[position] == 2
end
def switch_player
@current_player = (@current_player == 0) ? 1 : 0
end
def game_over?
winner? || board_full?
end
def winner?
WIN_PATTERNS.each do |pattern|
a = @board[pattern[0]]
b = @board[pattern[1]]
c = @board[pattern[2]]
return true if a == b && b == c && a != 2
end
false
end
def board_full?
i = 0
while i < 9
return false if @board[i] == 2
i += 1
end
true
end
def display_result
clear_screen
puts "=== ゲーム終了 ==="
puts "\n最終ボード:"
puts " #{cell(0)} │ #{cell(1)} │ #{cell(2)} "
puts "───┼───┼───"
puts " #{cell(3)} │ #{cell(4)} │ #{cell(5)} "
puts "───┼───┼───"
puts " #{cell(6)} │ #{cell(7)} │ #{cell(8)} "
puts
if winner?
switch_player # 最後にスイッチしたので戻す
puts "🎉 #{MARKS[@current_player]} の勝ちです!"
else
puts "引き分けです!"
end
end
end
# ゲーム実行
if __FILE__ == $PROGRAM_NAME
game = TicTacToe.new
game.play
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment