forked from Team-Teamwork-CS/CS-Build-Week-1-Flask
/
adventure.py
321 lines (259 loc) · 11.1 KB
/
adventure.py
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
import hashlib
import json
from time import time
from uuid import uuid4
from flask import Flask, jsonify, request, render_template, make_response
# from pusher import Pusher
# from decouple import config
from room import Room
from player import Player
from world import World
from items import Item, Food, Weapon
from store import Store
# Look up decouple for config variables
# pusher = Pusher(app_id=config('PUSHER_APP_ID'), key=config('PUSHER_KEY'), secret=config('PUSHER_SECRET'), cluster=config('PUSHER_CLUSTER'))
world = World()
# world.print_rooms()
app = Flask(__name__)
# CORS(app, supports_credentials = True)
# app.config['CORS_ALLOW_HEADERS'] = "Content-Type"
# app.config['CORS_RESOURCES'] = {r"/": {"origins": "https://client-lilac.now.sh/"}}
@app.after_request
def after_request(response):
response.headers.add('Access-Control-Allow-Origin', '*')
response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')
response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS')
return response
def get_player_by_header(world, auth_header):
if auth_header is None:
return None
auth_key = auth_header.split(" ")
if auth_key[0] != "Token" or len(auth_key) != 2:
return None
player = world.get_player_by_auth(auth_key[1])
return player
@app.route('/api/registration/', methods=['POST'])
def register():
# if request.method == 'OPTIONS':
# response = make_response()
# response.headers['Access-Control-Allow-Origin'] = '*'
# response.headers['Access-Control-Allow-Headers'] = '*'
# response.headers['Access-Control-Allow-Methods'] = '*'
# return response, 200
values = request.get_json()
required = ['username', 'password1', 'password2']
if not all(k in values for k in required):
response = {'message': "Missing Values"}
return jsonify(response), 400
username = values.get('username')
password1 = values.get('password1')
password2 = values.get('password2')
# response = make_response(world.add_player(username, password1, password2))
# response.headers['Access-Control-Allow-Origin'] = '*'
response = world.add_player(username, password1, password2)
if 'error' in response:
return jsonify("Registration error", response), 500
else:
# pusher.trigger(
# 'world', 'joined', {'pusher': f"{username} has joined the game"}
# )
return jsonify(response), 200
# test endpoint
@app.route('/', methods=['GET'])
def test_method():
return 'Welcome Adventurer'
@app.route('/api/login/', methods=['POST'])
def login():
# IMPLEMENT THIS
values = request.get_json()
required = ['username', 'password']
if not all(k in values for k in required):
response = {'message': "Missing Values"}
return jsonify(response), 400
username = values.get('username')
password = values.get('password')
response = world.authenticate_user(username, password)
if response is None:
return jsonify(response), 500
else:
# pusher.trigger(
# 'world', 'joined', {'pusher': f"{username} has joined the game"}
# )
return jsonify(response), 200
@app.route('/api/adv/init/', methods=['GET'])
def init():
player = get_player_by_header(world, request.headers.get("Authorization"))
if player is None:
response = {'error': "Malformed auth header"}
return response, 500
response = {
'id': player.current_room.id,
'title': player.current_room.name,
'description': player.current_room.description,
'exits': player.current_room.get_exits(),
'items': player.current_room.get_items()
}
# print('THIS IS THE ROOM: ', player.current_room)
return jsonify(response), 200
@app.route('/api/adv/move/', methods=['POST'])
def move():
player = get_player_by_header(world, request.headers.get("Authorization"))
if player is None:
response = {'error': "Malformed auth header"}
return jsonify(response), 500
values = request.get_json()
required = ['direction']
if not all(k in values for k in required):
response = {'message': "Missing Values"}
return jsonify(response), 400
direction = values.get('direction')
if player.travel(direction):
response = {
'title': player.current_room.name,
'description': player.current_room.description,
}
return jsonify(response), 200
else:
response = {
'error': "You cannot move in that direction.",
}
return jsonify(response), 500
@app.route('/api/adv/take/', methods=['POST'])
def take_item():
# IMPLEMENT THIS
# {
# "item_name":"Torch"
# }
player = get_player_by_header(world, request.headers.get("Authorization"))
if player is None:
response = {'error': "Malformed auth header"}
return response, 500
values = request.get_json()
items = player.current_room.items
for item in items:
if item.name.lower() == values['item_name'].lower():
player.add_to_inventory(item)
# print('THIS IS THE ITEM: ', item.name)
player.current_room.items.remove(item)
return jsonify(f"You have picked up {item.name}"), 200
return jsonify(f"{values['item_name']} not found"), 500
@app.route('/api/adv/drop/', methods=['POST'])
def drop_item():
# IMPLEMENT THIS
# {
# "item":"{name: "Short sword", price: 5, description: "It's sharp."}"
# }
player = get_player_by_header(world, request.headers.get("Authorization"))
if player is None:
response = {'error': "Malformed auth header"}
return response, 500
values = request.get_json()
inventory = player.inventory
for item in inventory:
if item.name.lower() == values['item_name'].lower():
player.inventory.remove(item)
player.current_room.items.append(item)
return jsonify(f"You have dropped {item.name}"), 200
return jsonify(f"{values['item_name']} not found"), 500
@app.route('/api/adv/inventory/', methods=['GET'])
def inventory():
# IMPLEMENT THIS
player = get_player_by_header(world, request.headers.get("Authorization"))
if player is None:
response = {'error': "Malformed auth header"}
return response, 500
# response = {
# 'name': player.coin_purse,
# 'description':
# }
response = []
for i in range(len(player.inventory)):
if (type(player.inventory[i]) is Weapon):
response.append({'name': player.inventory[i].name, 'description': player.inventory[i].description, 'price': player.inventory[i].price, 'weapon_type': player.inventory[i].weapon_type,
'damage': player.inventory[i].damage})
elif (type(player.inventory[i]) is Food):
response.append({'name': player.inventory[i].name, 'description': player.inventory[i].description, 'price': player.inventory[i].price, 'food_type': player.inventory[i].food_type,
'healing_amount': player.inventory[i].healing_amount})
elif (type(player.inventory[i]) is Item):
response.append({'name': player.inventory[i].name, 'description': player.inventory[i].description, 'price': player.inventory[i].price})
return jsonify({'Inventory': response, 'Money': player.coin_purse}), 200
@app.route('/api/adv/buy/', methods=['POST'])
def buy_item():
# IMPLEMENT THIS
player = get_player_by_header(world, request.headers.get("Authorization"))
if player is None:
response = {'error': "Malformed auth header"}
return response, 500
values = request.get_json()
if (player.current_room.store is not None):
stock = player.current_room.store.stock
else:
return jsonify("There's no store here!"), 500
for item in stock:
if item.name.lower() == values['item_name'].lower():
if (item.price <= player.coin_purse):
player.add_to_inventory(item)
player.coin_purse -= item.price
player.current_room.store.vault += item.price
player.current_room.store.stock.remove(item)
return jsonify(f"You have bought up {item.name}. You have {player.coin_purse} gold coins left."), 200
else:
return jsonify('You do not have enough gold coins to buy that item.'), 500
return jsonify(f"{values['item_name']} not found"), 500
@app.route('/api/adv/sell/', methods=['POST'])
def sell_item():
# IMPLEMENT THIS
player = get_player_by_header(world, request.headers.get("Authorization"))
if player is None:
response = {'error': "Malformed auth header"}
return response, 500
values = request.get_json()
if (player.current_room.store is not None):
inventory = player.inventory
stock = player.current_room.store.stock
else:
return jsonify("There's no store here!"), 500
for item in inventory:
if item.name.lower() == values['item_name'].lower():
if (item.price <= player.current_room.store.vault):
player.inventory.remove(item)
stock.append(item)
player.coin_purse += item.price
player.current_room.store.vault -= item.price
return jsonify(f"You have sold your {item.name}. You have {player.coin_purse} gold coins left."), 200
else:
return jsonify('Store does not have enough gold coins to buy that item from you.'), 500
return jsonify(f"{values['item_name']} not found"), 500
@app.route('/api/adv/store', methods=['GET'])
def check_store():
player = get_player_by_header(world, request.headers.get("Authorization"))
if player is None:
response = {'error': "Malformed auth header"}
return response, 500
if not player.current_room.store:
return jsonify('There is no store in this room!'), 500
stock = player.current_room.store.stock
response = []
for i in range(len(stock)):
if (type(stock[i]) is Weapon):
response.append({'name': stock[i].name, 'description': stock[i].description, 'price': stock[i].price, 'weapon_type': stock[i].weapon_type,
'damage': stock[i].damage})
elif (type(stock[i]) is Food):
response.append({'name': stock[i].name, 'description': stock[i].description, 'price': stock[i].price, 'food_type': stock[i].food_type,
'healing_amount': stock[i].healing_amount})
else:
response.append({'name': stock[i].name, 'description': stock[i].description, 'price': stock[i].price})
return jsonify({'Stock': response}), 200
@app.route('/api/adv/rooms', methods=['GET'])
def rooms():
# IMPLEMENT THIS
response = {'rooms': world.print_rooms()}
return jsonify(response), 200
@app.route('/api/adv/grid', methods=['GET'])
def grid():
# IMPLEMENT THIS
response = {'grid': world.get_matrix()}
return jsonify(response), 200
# Run the program on port 5000
if __name__ == '__main__':
app.run(debug=False, port=5000)