This is designed to be a simple example of a RPG battle, for a talk I hope to give. The rules:
- Alice and Bob both have 5 hit points and inflict 2 damage.
- Each turn, Alice attacks Bob, and Bob attacks Alice.
- 3/4 of attacks hit their target.
- 1/2 of the attacks that hit their target are blocked, inflicting half damage.
- When one character is dead, the game is over.
Important ideas:
- Sending the attack and receiving the attack are handled separately.
- It's a re-usable API for characters, so
game.rb
is a single use case. There could be others.
character.rb
class Character
attr_accessor :name, :hit_points
def initialize(name, hit_points, hit_chance, block_chance, damage)
@name = name
@hit_points = hit_points
@hit_chance = hit_chance
@block_chance = block_chance
@damage = damage
end
def attack(other_character)
puts "#{name} attacks #{other_character.name}"
if roll(@hit_chance)
puts " The attack hits"
other_character.be_attacked(@damage)
else
puts " The attack missed"
end
end
def be_attacked(damage)
if roll(@block_chance)
puts " It was blocked, half damage done."
take_damage(damage / 2)
else
take_damage(damage)
end
end
def take_damage(damage)
@hit_points -= damage
puts " -#{damage} hit points"
puts " #{name} has been defeated" if dead?
end
def dead?
@hit_points <= 0
end
private
def roll(chance)
rand(100) < chance
end
end
game.rb
class Game
def initialize
@alice = Character.new('Alice', 5, 75, 50, 2)
@bob = Character.new('Bob', 5, 75, 50, 2)
end
def turn
@alice.attack(@bob)
@bob.attack(@alice)
report_status
sleep 1
end
def over?
(@alice.dead? or @bob.dead?)
end
def report_status
puts ''
if over?
puts "The game is over!"
else
puts "Alice: #{@alice.hit_points} - Bob: #{@bob.hit_points}"
puts ''
end
end
end
script.rb (executable file)
require_relative 'character.rb'
require_relative 'game.rb'
game = Game.new
game.turn until game.over?
Example output:
Alice attacks Bob
The attack missed
Bob attacks Alice
The attack hits
-2 hit points
Alice: 3 - Bob: 5
Alice attacks Bob
The attack hits
-2 hit points
Bob attacks Alice
The attack missed
Alice: 3 - Bob: 3
Alice attacks Bob
The attack hits
-2 hit points
Bob attacks Alice
The attack hits
-2 hit points
Alice: 1 - Bob: 1
Alice attacks Bob
The attack hits
It was blocked, half damage done.
-1 hit points
Bob has been defeated
Bob attacks Alice
The attack hits
-2 hit points
Alice has been defeated
The game is over!