Last active
April 15, 2024 05:35
-
-
Save amirrajan/32c6a53f800c3e1ac63e9380fe3b7a6a to your computer and use it in GitHub Desktop.
Flappy Bird - DragonRuby Game Toolkit: Apples to Apples
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# https://www.reddit.com/r/ruby/comments/1bzxlsl/ive_made_an_article_on_how_to_create_a_flappy/ | |
# https://www.reddit.com/r/ruby/comments/1c44s4s/saw_an_interest_post_about_how_to_create_a_flappy/ | |
class Game | |
attr_gtk | |
def tick | |
Grid.origin_center! | |
calc | |
render | |
end | |
def calc | |
if state.tick_count == 0 | |
new_game! | |
elsif !state.game_over | |
calc_bird | |
calc_pipes | |
elsif inputs.keyboard.key_down.r | |
new_game! | |
end | |
end | |
def calc_bird | |
state.bird.dy = 15 if inputs.keyboard.key_down.up | |
state.bird.dy -= 1 | |
state.bird.y += state.bird.dy | |
state.bird.angle = state.bird.dy * 2.5 | |
passed_pipes = state.pipes.find_all { |pipe| pipe.x + pipe.w < Grid.left } | |
state.pipes -= passed_pipes | |
state.score += passed_pipes.find_all { |pipe| pipe.flip_vertically }.length | |
if state.bird.y < Grid.bottom || Geometry.find_intersect_rect(state.bird, state.pipes) | |
state.game_over = true | |
end | |
end | |
def calc_pipes | |
state.pipes.each { |pipe| pipe.x -= 5 } | |
if state.tick_count.zmod? 120 | |
gap = 100.randomize(:sign) | |
state.pipes << { x: Grid.right, y: 0 + gap + 125, w: 64, h: Grid.h, path: "sprites/pipe.png", flip_vertically: true } | |
state.pipes << { x: Grid.right, y: -(Grid.h - gap) - 125, w: 64, h: Grid.h, path: "sprites/pipe.png" } | |
end | |
end | |
def render | |
outputs.sprites << { **Grid.rect, path: "sprites/bg.png" } | |
outputs.sprites << state.bird | |
outputs.sprites << state.pipes | |
outputs.labels << { x: 0, y: Grid.top - 64, text: "Score: #{state.score}", size_px: 64, anchor_x: 0.5, anchor_y: 0.5 } | |
if state.game_over | |
outputs.labels << { x: 0, y: 0, text: "Press R to Restart", size_px: 64, anchor_x: 0.5, anchor_y: 0.5 } | |
end | |
end | |
def new_game! | |
state.bird = { x: Grid.left + 100, y: 0, w: 64, h: 64, dy: 0, angle: 0, path: "sprites/bird.png" } | |
state.pipes = [] | |
state.score = 0 | |
state.game_over = false | |
end | |
end | |
def tick args | |
$game ||= Game.new | |
$game.args = args | |
$game.tick | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment