Skip to content

Instantly share code, notes, and snippets.

@ConorOBrien-Foxx
Last active October 2, 2016 17:43
Show Gist options
  • Save ConorOBrien-Foxx/792115ee4b624a7e7ad37078346f96be to your computer and use it in GitHub Desktop.
Save ConorOBrien-Foxx/792115ee4b624a7e7ad37078346f96be to your computer and use it in GitHub Desktop.
chess displayer in ruby, powered by gosu

Please run gem install gosu before running. Run as ruby chess.rb <fileName>, and make sure the board is formatted as above. Press the Escape key or simply press the x button to exit.

14... Qe8
+---+---+---+---+---+---+---+---+
8 |bR |bN.|bB | .|bQ |bR.|bK | .|
+---+---+---+---+---+---+---+---+
7 | .| | .| | .| | b.| b |
+---+---+---+---+---+---+---+---+
6 | | .| | .| b | .| | .|
+---+---+---+---+---+---+---+---+
5 | b.|wQ |wB.| | .| b | .| |
+---+---+---+---+---+---+---+---+
4 | | .| | .| | .| | .|
+---+---+---+---+---+---+---+---+
3 | .| | w.| | .|wN | .| |
+---+---+---+---+---+---+---+---|
2 | w | w.| | .| | w.| w | w.|
+---+---+---+---+---+---+---+---|
1 | .| |wK.|wR | .| | .|wR |
+---+---+---+---+---+---+---+---+
A B C D E F G H
require 'gosu'
board = File.read ARGV[0]
$cells = board.scan(/(?<=\|)(.)(.)(.)(?=\|)/)
turn_num, color = board.scan(/^(\d+)(\.+)/).pop
next_col = color == "." ? "black" : "white"
next_turn = turn_num.to_i + (color == "." ? 0 : 1)
$caption = "Waiting for #{next_col} to play turn #{next_turn}..."
# team = 0, 1 (0 for white, 1 for black)
def get_chess(chr, team)
ind = "KQRBNP".index chr
return " " if ind < 0
[0x2654 + ind + 6 * team].pack("U")
end
class Cell
def initialize(arr)
color, piece, tileColor = arr
# print arr
@tileColor = tileColor == "." ? 0 : 1
if color == " "
unless piece == " "
color = piece
piece = "P"
else
@color = 0
@piece = " "
end
end
@color = @color || color == "b" ? 1 : 0
@piece = @piece || get_chess(piece, @color)
# print [@color, @piece]
end
attr_accessor :piece, :tileColor, :color
end
$cell_width = 64
$height = 8 * $cell_width
$width = $height
class DisplayWindow < Gosu::Window
def initialize
super $width, $height
self.caption = $caption
@tiles = []
$cells.each { |cell| @tiles.push Cell.new cell }
@font = Gosu::Font.new $cell_width
end
def update
if Gosu::button_down? Gosu::KbEscape
close
end
end
def draw
row = column = 0
@tiles.each do |tile|
if tile.tileColor == 1
# white
tile_color = Gosu::Color.new 255, 221, 198, 166
else
# black
tile_color = Gosu::Color.new 255, 174, 139, 85
end
if tile.color == 1
# black
font_color = Gosu::Color.new 255, 0, 0, 0
else
# white
font_color = Gosu::Color.new 255, 255, 255, 255
end
y = row * $cell_width
x = column * $cell_width
Gosu.draw_rect(
x,
y,
$cell_width,
$cell_width,
tile_color
)
column += 1
if column == 8
row += 1
column = 0
end
@font.draw(tile.piece, x + 7, y, 3, 1, 1, font_color)
end
end
end
window = DisplayWindow.new
window.show
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment