-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBattleManager.py
More file actions
200 lines (165 loc) · 8.02 KB
/
BattleManager.py
File metadata and controls
200 lines (165 loc) · 8.02 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
import json
import cartesi_wallet.wallet as Wallet
from cartesi_wallet.outputs import Notice, Log
import arena
import hashlib
class BattleManager:
def __init__(self, wallet: Wallet):
# Initializes a new instance of the BattleManager class
self.__challenge_counter = 0
self.challenges = {} # Stores challenges by their ID
self.wallet = wallet
def list_matches(self):
return list(self.challenges.values())
def list_user_matches(self, user):
challenge_list = self.challenges.values()
user_list = []
for chall in challenge_list:
if chall['owner'].lower() == user.lower():
user_list.append(chall)
return user_list
def create_challenge(self, owner_id, fighter_hash, token, amount):
balance = self.wallet.balance_get(owner_id)
token_balance = balance.erc20_get(token)
if int(token_balance) < 2* amount:
raise Exception("User does not have enough balance to propose such a duel")
self.wallet.erc20_transfer(owner_id, "0x0", token, amount) ## How much the user is betting
self.wallet.erc20_transfer(owner_id, "0x0", token, amount) ## The staking as colateral
# Creates a new challenge
challenge_id = self._generate_match_id()
self.challenges[challenge_id] = {
'id': challenge_id,
'owner': owner_id,
'fighter_hash': fighter_hash,
'token': token,
'amount': str(amount),
'status': 'pending', # possible statuses: pending, accepted
'opponent': None
}
return self.challenges[challenge_id]
def create_challenge_eth(self, owner_id, fighter_hash, amount):
balance = self.wallet.balance_get(owner_id)
token_balance = balance.ether_get()
if int(token_balance) < 2 * amount:
raise Exception("User does not have enough balance to propose such a duel")
self.wallet.ether_transfer(owner_id, "0x0", amount) ## How much the user is betting
self.wallet.ether_transfer(owner_id, "0x0", amount) ## The staking as colateral
# Creates a new challenge
challenge_id = self._generate_match_id()
self.challenges[challenge_id] = {
'id': challenge_id,
'owner': owner_id,
'fighter_hash': fighter_hash,
'token': None,
'amount': str(amount),
'status': 'pending', # possible statuses: pending, accepted
'opponent': None
}
return self.challenges[challenge_id]
def accept_challenge(self, challenge_id, opponent_id, fighter):
# Accepts a challenge
if challenge_id not in self.challenges:
raise Exception("Challenge does not exist.")
challenge = self.challenges[challenge_id]
if challenge['status'] != 'pending':
raise Exception("Challenge is not available for acceptance.")
balance = self.wallet.balance_get(opponent_id)
token_balance = balance.ether_get()
if challenge['token'] is not None:
token_balance = balance.erc20_get(challenge['token'])
if int(challenge['amount']) > int(token_balance):
raise Exception("User does not have enough balance to propose such a duel")
d = fighter
char2 = arena.Character(1, d["name"], d["weapon"], d["hp"], d["atk"], d["def"], d["spd"])
if char2.is_cheater():
raise Exception("Invalid fighter data")
if challenge['token'] is None:
self.wallet.ether_transfer(opponent_id, "0x0", int(challenge['amount']))
else:
self.wallet.erc20_transfer(opponent_id, "0x0", challenge['token'], int(challenge['amount']))
## Transfer the stake of openent's token
challenge['status'] = 'accepted'
challenge['opponent'] = opponent_id
challenge['opponent_fighter'] = fighter
return challenge
def start_match(self, challenge_id, sender_id, fighter):
if challenge_id not in self.challenges:
raise Exception("Challenge does not exist.")
challenge = self.challenges[challenge_id]
if challenge['status'] != 'accepted':
raise Exception("Challenge is not yet accepted by anyone.")
if sender_id != challenge['owner']:
raise Exception("You are not the owner, can't start match.")
is_eth_challenge = challenge['token'] is None
d = fighter
char1 = arena.Character(0, d["name"], d["weapon"], d["hp"], d["atk"], d["def"], d["spd"])
d = challenge['opponent_fighter']
char2 = arena.Character(1, d["name"], d["weapon"], d["hp"], d["atk"], d["def"], d["spd"])
opponent_id = challenge['opponent']
token = challenge['token']
amount = int(challenge['amount'])
if (char1.is_cheater() or not self._hash_matches_fighter(fighter, challenge['fighter_hash'])):
## ends duel and player 2 gets everything, even the stake
self.challenges.pop(challenge_id)
if is_eth_challenge:
self.wallet.ether_transfer("0x0", opponent_id, amount) # their money
self.wallet.ether_transfer("0x0", opponent_id, amount) # owner money
self.wallet.ether_transfer("0x0", opponent_id, amount) # owner stake
else:
self.wallet.erc20_transfer("0x0", opponent_id, token, amount) # their money
self.wallet.erc20_transfer("0x0", opponent_id, token, amount) # owner money
self.wallet.erc20_transfer("0x0", opponent_id, token, amount) # owner stake
return
if is_eth_challenge:
self.wallet.ether_transfer("0x0", sender_id, amount)
else:
self.wallet.erc20_transfer("0x0", sender_id, token, amount) # game creator gets it's stake back
result, log = arena.battle(char1, char2)
self.challenges.pop(challenge_id) # delete fight
if result["winner"]["id"] == -1: # and everyone gets their money back
if is_eth_challenge:
self.wallet.ether_transfer("0x0", opponent_id, amount)
self.wallet.ether_transfer("0x0", sender_id, amount)
else:
self.wallet.erc20_transfer("0x0", opponent_id, token, amount)
self.wallet.erc20_transfer("0x0", sender_id, token, amount)
return
elif result["winner"]["id"] == 0: # game creator wins
if is_eth_challenge:
self.wallet.ether_transfer("0x0", sender_id, amount)
self.wallet.ether_transfer("0x0", sender_id, amount)
else:
self.wallet.erc20_transfer("0x0", sender_id, token, amount)
self.wallet.erc20_transfer("0x0", sender_id, token, amount)
else: # opponent wins
if is_eth_challenge:
self.wallet.ether_transfer("0x0", opponent_id, amount)
self.wallet.ether_transfer("0x0", opponent_id, amount)
else:
self.wallet.erc20_transfer("0x0", opponent_id, token, amount)
self.wallet.erc20_transfer("0x0", opponent_id, token, amount)
notice_payload = result
notice_payload['owner_id'] = sender_id
notice_payload['opponent_id'] = opponent_id
notice_payload['game_id'] = challenge_id
notice_payload['fighters'] = [
fighter,
challenge['opponent_fighter']
]
report_payload = {
"rounds": result['rounds'],
"log": log,
'game_id': challenge_id
}
return notice_payload, report_payload
def _generate_match_id(self):
# Generates a unique match ID
self.__challenge_counter += 1
return self.__challenge_counter
def _hash_matches_fighter(self, fighter, hash):
d = fighter
input_string = "-".join([d["name"], d["weapon"], str(d["hp"]), str(d["atk"]), str(d["def"]), str(d["spd"])])
prove = "0x" + hashlib.sha256(input_string.encode()).hexdigest()
if hash != prove:
return False
return True