-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathminecraft.rb
More file actions
354 lines (296 loc) · 9.19 KB
/
Copy pathminecraft.rb
File metadata and controls
354 lines (296 loc) · 9.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
#-- vim:sw=2:et
#++
#
# :title: Minecraft utilities for rbot (ruby >= 1.9!)
#
# Copyright:: (C) 2013 Matthias Hecker
#
# License:: GPLv3 license
require 'socket'
##
# Pings a minecraft server and returns motd and playercount.
# Works with ruby >=1.9.3/2.0.0
#
# More information and sample code here:
# http://wiki.vg/Server_List_Ping
##
class MinecraftPing
def initialize(host, port=25565)
@host = host
@port = port
end
def ping
socket = TCPSocket.open(@host, @port)
# packet identifier & payload ...
socket.write([0xFE, 0x01, 0xFA].pack('CCC'))
socket.write(encode_string('MC|PingHost'))
socket.write([7 + 2 * @host.length].pack('n'))
socket.write([74].pack('c'))
socket.write(encode_string(@host))
socket.write([@port].pack('N'))
# read server response
if socket.read(1).unpack('C').first != 0xFF # Kick packet
raise 'unexpected server response packet'
end
len = socket.read(2).unpack('n').first
resp = decode_string(socket.read(len*2)).split("\u0000")
socket.close
if resp.shift != "\u00A71"
raise 'unexpected server response fields'
end
return {
:protocol_version => resp.shift.to_i,
:minecraft_version => resp.shift,
:motd => resp.shift,
:current_players => resp.shift.to_i,
:max_players => resp.shift.to_i
}
end
private
def encode_string(s)
begin
[s.length].pack('n') + Iconv.conv('utf-16be', 'utf-8', s)
rescue
[s.length].pack('n') + s.encode('utf-16be').force_encoding('ASCII-8BIT')
end
end
def decode_string(s)
begin
Iconv.conv('utf-8', 'utf-16be', s)
rescue
s.force_encoding('utf-16be').encode('utf-8')
end
end
end
class Minecraft < Plugin
class Recipes
def initialize(recipes)
@recipes = recipes
log "Loaded #{length} recipes."
end
def length
@recipes.keys.length
end
def search(query)
log "Search for #{query}"
def unify(str)
str.downcase.gsub(/(\(|\))/,'')
end
results = []
@recipes.keys.each do |key|
results << key if unify(key).include? unify(query)
# exact match found:
if unify(key) == unify(query)
return [ key ]
end
end
return results
end
def get(product)
@recipes[product]
end
def craft(product, amount, checklist=[])
return if not @recipes.has_key? product
recipes = @recipes[product]
if recipes.length > 1
msg = "You can craft this in different ways:\n"
recipes.each do |recipe|
msg << craft_recipe(product, recipe, amount, checklist)+"\n"
end
return msg
else
return craft_recipe(product, recipes.first, amount, checklist)
end
end
def craft_recipe(product, recipe, amount, checklist=[])
checklist << product
amount += 1 while amount % recipe['output'].to_i != 0
factor = (amount / recipe['output'].to_i).to_i
# ingredients how many of each..
recipe_list = []
recipe_crafting_list = []
# count ingredients
counts = {}
recipe['recipe'].each do |ingredient|
next if not ingredient or ingredient.empty?
if counts.has_key? ingredient
counts[ingredient] += 1
else
counts[ingredient] = 1
end
end
counts.each_pair do |recipe_item, recipe_amount|
recipe_amount *= factor
recipe_list << "#{recipe_amount} #{recipe_item}"
if not checklist.include? recipe_item
recipe_crafting = craft(recipe_item, recipe_amount, checklist)
recipe_crafting_list << recipe_crafting if recipe_crafting
end
end
msg = ''
msg << "You craft #{amount} #{product}"
msg << " with #{recipe_list.join ', '}."
if not recipe_crafting_list.empty?
msg << " (For the ingredients: #{recipe_crafting_list.join ' '})"
end
return msg
end
end
def help(plugin, topic='')
"Minecraft utilities: craft [amount] [item] | recipe [item] | overworld [x] [y] [z] | nether [x] [y] [z] | mcpoll [host] [port]"
end
def initialize
super
recipe_path = File.dirname(__FILE__) + '/minecraft/recipes.json'
@recipes = Recipes.new JSON.parse(IO.read(recipe_path))
end
Config.register Config::StringValue.new('minecraft.numbered_stacks',
:default => true,
:desc => "Display amounts with stacks.")
def craft(m, params)
if params.has_key? :search
results = @recipes.search params[:search].join ' '
if results.length == 0
m.reply "Sorry, recipe not found :("
elsif results.length > 1
m.reply "What did you mean? #{results.join ', '}"
else
product = results.first
if params.has_key? :amount
amount = params[:amount].to_i
else
amount = 1
end
msg = @recipes.craft(product, amount)
msg.split("\n").each do |line|
m.reply line
end
end
else
m.reply "Found #{@recipes.length} crafting recipes."
end
end
def recipe(m, params)
results = @recipes.search params[:search].join ' '
if results.length == 0
m.reply "Sorry, recipe not found :("
elsif results.length > 1
m.reply "What did you mean? #{results.join ', '}"
else
product = results.first
recipe = @recipes.get(product).first
# m.reply '[dbg] product = ' + product.inspect
legend = {} # short character -> long ingredient name
# build legend (manage conflicts etc.)
recipe['recipe'].each do |ingredient|
next if not ingredient
# default wood plank uses oak wood planks (can use all types of wood)
ingredient = 'Wood Planks' if ingredient == 'Oak Wood Planks'
# short character for crafting grid and legend
short = ingredient[0]
# conflict search
if legend.has_key? short and legend[short] != ingredient
# first try to gracefully resolve the conflict by using the second word first letter
# of both ingredients:
if ingredient.split(' ').length > 1
short = ingredient.split(' ')[1][0]
elsif legend[short].split(' ').length > 1
# change the conflicting ingredient
new_short = legend[short].split(' ')[1][0]
legend[new_short] = legend[short]
end
# TODO: test if still conflicts
end
legend[short] = ingredient
end
lines = [] # recipe lines, 3 strings each 3 characters
line = '' # current line
recipe['recipe'].each do |ingredient|
# default wood plank uses oak wood planks (can use all types of wood)
ingredient = 'Wood Planks' if ingredient == 'Oak Wood Planks'
# search short:
short = ' '
legend.each_pair do |s, name|
if name == ingredient
short = s
break
end
end
line << short
if line.length == 3
lines << line
line = ''
end
end
# output formatting:
m.reply lines[0] + ' | Recipe for ' + product + ((recipe['shapeless'] == 1) ? ' (shapeless)' : '')
m.reply lines[1] + ' |'
legend_list = []
legend.each_pair { |short, name|
legend_list << [short, name].join('=')
}
m.reply lines[2] + ' | ' + legend_list.join(' ')
end
end
def overworld_nether(m, params)
coords = coords(m, params)
if not coords
return
end
x, y, z = coords
m.reply "Overworld(#{x}, #{y}, #{z}) -> Nether(#{(x/8).floor}, #{y}, #{(z/8).floor})"
end
def nether_overworld(m, params)
coords = coords(m, params)
if not coords
return
end
x, y, z = coords
m.reply "Nether(#{x}, #{y}, #{z}) -> Overworld(#{x*8}, #{y}, #{z*8})"
end
def poll(m, params)
host = params[:host]
port = params[:port]
begin
resp = MinecraftPing.new(host, port).ping
m.reply "The server responded: #{resp[:motd]} [#{resp[:minecraft_version]}] (#{resp[:current_players]}/#{resp[:max_players]})"
rescue
m.reply "error, #{$!}"
end
end
private
def coords(m, params)
return nil if not params.has_key? :coords or params[:coords].empty?
begin
# split the list of values by space or comma
coords = params[:coords]
if coords.length < 2
coords = params[:coords].join.split(',')
end
coords.map { |n| n.strip } # remove whitespaces & convert to integers
# either x, y, z OR x, z
if coords.length == 3
x, y, z = coords
elsif coords.length == 2
x, z = coords
y = 0
else
raise 'error parsing coordinates'
end
coords = [x.to_i, y.to_i, z.to_i]
rescue
m.reply 'error: ' + $!
debug $!
debug $@
return nil
end
return coords
end
end
plugin = Minecraft.new
plugin.map('craft', :action => 'craft')
plugin.map('craft [:amount] *search', :action => 'craft', :requirements => {:amount => /\d+/})
plugin.map('recipe *search', :action => 'recipe')
plugin.map('overworld *coords', :action => 'overworld_nether')
plugin.map('nether *coords', :action => 'nether_overworld')
plugin.map('mcpoll :host :port', :action => 'poll', :defaults => {:host => 'example.com', :port => 25565})