-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtextbasedrpg.py
More file actions
151 lines (127 loc) · 4.92 KB
/
textbasedrpg.py
File metadata and controls
151 lines (127 loc) · 4.92 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
# -*- coding: utf-8 -*-
"""TextBasedRPG.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/12bECRA4b8cgVsxWuVISVsYnbqdv6iikN
"""
import numpy as np
import json
import random
#from google.colab import drive
#drive.mount('/content/drive')
#this is where to save the json file. Edit to accept json file, just save as data. Formatting of json file? Contact me at lawjiasen@gmail.com
with open('/content/drive/MyDrive/Schoolwork/REC/Chatbot Group/Story2.json', encoding='utf-8-sig') as f:
data = json.load(f)
print(data)
"""**the fuzzy string matching function**"""
def levenshtein_ratio_and_distance(s, t, ratio_calc = False):
""" levenshtein_ratio_and_distance:
Calculates levenshtein distance between two strings.
If ratio_calc = True, the function computes the
levenshtein distance ratio of similarity between two strings
For all i and j, distance[i,j] will contain the Levenshtein
distance between the first i characters of s and the
first j characters of t
"""
# Initialize matrix of zeros
rows = len(s)+1
cols = len(t)+1
distance = np.zeros((rows,cols),dtype = int)
# Populate matrix of zeros with the indeces of each character of both strings
for i in range(1, rows):
for k in range(1,cols):
distance[i][0] = i
distance[0][k] = k
# Iterate over the matrix to compute the cost of deletions,insertions and/or substitutions
for col in range(1, cols):
for row in range(1, rows):
if s[row-1] == t[col-1]:
cost = 0 # If the characters are the same in the two strings in a given position [i,j] then the cost is 0
else:
# In order to align the results with those of the Python Levenshtein package, if we choose to calculate the ratio
# the cost of a substitution is 2. If we calculate just distance, then the cost of a substitution is 1.
if ratio_calc == True:
cost = 2
else:
cost = 1
distance[row][col] = min(distance[row-1][col] + 1, # Cost of deletions
distance[row][col-1] + 1, # Cost of insertions
distance[row-1][col-1] + cost) # Cost of substitutions
if ratio_calc == True:
# Computation of the Levenshtein Distance Ratio
Ratio = ((len(s)+len(t)) - distance[row][col]) / (len(s)+len(t))
return Ratio
else:
# print(distance) # Uncomment if you want to see the matrix showing how the algorithm computes the cost of deletions,
# insertions and/or substitutions
# This is the minimum number of edits needed to convert string a to string b
return "The strings are {} edits away".format(distance[row][col])
"""**A sample code to map the response to an option**"""
def matching(options,rawInput):
Str1 = [x.lower() for x in options]
Str2 = rawInput.lower()
chunk=[]
i=0
for elements in Str1 :
ratio = levenshtein_ratio_and_distance(Str1[i],Str2, ratio_calc = True)
chunk.append([ratio])
i=i+1
return np.argmax(chunk)
def playScene():
global scene
# for item in range(len(scene['option'])):
# if userInput == scene['option'][item]:
# scene = data[scene['redirection'][item]]
#requirements
if 'requirements' in scene:
for required in scene['requirements']:
if required[1] == "=":
if required[0] == memory[required[2]]:
scene = required[3]
return
elif required[1] == ">":
if required[0] > memory[required[2]]:
scene = required[3]
return
elif required[1] == "<":
if required[0] < memory[required[2]]:
scene = required[3]
return
#text
print(scene['text'].format(memory))
#changing memory
if 'set' in scene:
for setting in scene['set']:
if setting[1] == "+":
memory[setting[0]] += setting[2]
elif setting[1] == "*":
memory[setting[0]] *= setting[2]
elif setting[1] == "=":
memory[setting[0]] = setting[2]
#options for user to go along
if 'options' in scene:
userInput = input()
print("\n-----------------------------------------------------\nFood: {}\nWater: {}".format(memory["food"],memory["water"]))
tempScene = scene['redirection'][matching(scene['options'],userInput)]
else:
tempScene = scene['redirection'][0]
#probability
if type(tempScene) is list:
random_variable = random.random()
random_limit = 0
for item in tempScene:
random_limit += item[0]
if random_variable<random_limit:
scene = data[item[1]]
# print("THIS IS A DEBUG",random_limit,random_variable,item[1])
break
else:
scene = data[tempScene]
"""#**Where the magic happens**"""
scene = data['0X']
memory = {
"water":5,
"food":5
}
while True:
playScene()