Class: Process::Roulette::Player

Inherits:
Object
  • Object
show all
Defined in:
lib/process/roulette/player.rb

Overview

Encapsulates the player entity, participating in the roulette game by killing random processes in coordination with the croupier server.

Instance Method Summary collapse

Constructor Details

#initialize(host, port, username) ⇒ Player

Returns a new instance of Player.



12
13
14
15
16
# File 'lib/process/roulette/player.rb', line 12

def initialize(host, port, username)
  @host = host
  @port = port
  @username = username
end

Instance Method Details

#_handle_packet(socket, packet) ⇒ Object



50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/process/roulette/player.rb', line 50

def _handle_packet(socket, packet)
  if packet == 'GO'
    _pull_trigger(socket)

    puts 'survived!'
    socket.send_packet('OK')
  else
    puts "unexpected packet: #{packet.inspect}"
  end

  false
end

#_handshake(socket) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
# File 'lib/process/roulette/player.rb', line 29

def _handshake(socket)
  socket.send_packet("OK:#{@username}")

  packet = socket.wait_with_ping
  abort 'lost connection' unless packet

  return if packet == 'OK'

  socket.close
  abort 'username already taken!'
end

#_play_loop(socket) ⇒ Object



41
42
43
44
45
46
47
48
# File 'lib/process/roulette/player.rb', line 41

def _play_loop(socket)
  loop do
    packet = socket.wait_with_ping
    abort 'lost connection' unless packet

    break if _handle_packet(socket, packet)
  end
end

#_pull_trigger(socket) ⇒ Object



63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/process/roulette/player.rb', line 63

def _pull_trigger(socket)
  processes = ::Sys::ProcTable.ps
  victim = processes.sample

  # alternatively: write to random memory locations?
  socket.send_packet(victim.comm)

  puts "pulling the trigger on \##{victim.pid} (#{victim.comm})"
  Process.kill('KILL', victim.pid)

  # give some time to make sure the kill has its effect
  sleep 0.1
end

#playObject



18
19
20
21
22
23
24
25
26
27
# File 'lib/process/roulette/player.rb', line 18

def play
  puts 'connecting...'
  socket = Process::Roulette::EnhanceSocket(TCPSocket.new(@host, @port))

  _handshake(socket)
  _play_loop(socket)

  puts 'finishing...'
  socket.close
end