Skip to content

Instantly share code, notes, and snippets.

@gabebw
Created July 17, 2011 18:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gabebw/1087881 to your computer and use it in GitHub Desktop.
Save gabebw/1087881 to your computer and use it in GitHub Desktop.
require 'rubygems'
require 'ray'
WIDTH = 800
HEIGHT = 800
PADDLE_X_OFFSET = 40
PADDLE_WIDTH = 40
BALL_RADIUS = 20
SCORE_TEXT_X_OFFSET = 40
def paddle(paddle_x_coord, paddle_y_coord)
arguments_array = [paddle_x_coord, paddle_y_coord, PADDLE_WIDTH, HEIGHT / 3]
Ray::Polygon.rectangle(arguments_array, Ray::Color.white)
end
def ball
Ray::Polygon.circle([WIDTH/2, HEIGHT/2], BALL_RADIUS, Ray::Color.white)
end
def center_x_pos
WIDTH / 2
end
def pixels_left_of_center(num_pixels)
center_x_pos - num_pixels
end
def pixels_right_of_center(num_pixels)
center_x_pos + num_pixels
end
def adjust_paddle_height_by(paddle, delta)
pos = paddle.pos
pos.height += delta
paddle.pos = pos
end
def move_paddle_up(paddle)
pos = paddle.pos
pos.height = pos.height - 3
paddle.pos = pos
# Need to return the paddle otherwise it chokes on some NilClass thing
# paddle
end
def move_paddle_down(paddle)
adjust_paddle_height_by(paddle, 3)
# Need to return the paddle otherwise it chokes on some NilClass thing
paddle
end
def middle_line
line_width = 5
line_x_pos = center_x_pos
Ray::Polygon.line([line_x_pos, 0], [line_x_pos, HEIGHT], line_width, Ray::Color.white)
end
Ray.game 'Pong', :size => [WIDTH, HEIGHT] do
register { add_hook(:quit, method(:exit!)) }
scene :start do
def left_paddle_up; key(:d); end
LEFT_PADDLE_DOWN = :c
LEFT_PADDLE_UP = :d
RIGHT_PADDLE_UP = :up
RIGHT_PADDLE_DOWN = :down
@left_paddle = paddle(PADDLE_X_OFFSET, 100)
@right_paddle = paddle(WIDTH - (PADDLE_X_OFFSET + PADDLE_WIDTH), 100)
@ball = ball
@left_score = text "left", :at => [pixels_left_of_center(SCORE_TEXT_X_OFFSET), 20], :size => 20
@right_score = text "right", :at => [pixels_right_of_center(SCORE_TEXT_X_OFFSET), 20], :size => 20
@middle_line = middle_line
@scores = [@left_score, @right_score]
always do
# Left paddle
if holding?(LEFT_PADDLE_UP)
move_paddle_up(@left_paddle)
elsif holding?(LEFT_PADDLE_DOWN)
move_paddle_down(@left_paddle)
end
# Right paddle
if holding?(RIGHT_PADDLE_UP)
move_paddle_up(@right_paddle)
elsif holding?(RIGHT_PADDLE_DOWN)
move_paddle_down(@right_paddle)
end
end
# Exit when q is pressed
on :key_press, key(:q){ exit! }
render do |win|
win.draw @left_paddle
win.draw @right_paddle
win.draw @ball
win.draw @middle_line
@scores.each{|score| win.draw score }
end
end
scenes << :start
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment