Spaces:
Sleeping
Sleeping
File size: 5,125 Bytes
933256c 33bff5d 933256c 72c9352 933256c 72c9352 933256c 20fcd1d 933256c 72c9352 933256c 72c9352 933256c 72c9352 20fcd1d 72c9352 20fcd1d 72c9352 933256c 72c9352 933256c 72c9352 933256c 72c9352 933256c 72c9352 20fcd1d 72c9352 20fcd1d 72c9352 933256c 72c9352 |
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 |
from flask import Flask, render_template, jsonify, request
import json
import random
from transformers import AutoTokenizer, AutoModelForCausalLM
import torch
import os
# Set the TRANSFORMERS_CACHE environment variable
os.environ['TRANSFORMERS_CACHE'] = '/app/cache'
app = Flask(__name__)
# Load initial coins
with open('coins.json', 'r') as f:
coins = json.load(f)
# Initialize game state
game_state = {
'balance': 0,
'flips_left': 1000,
'current_coin': 0
}
# Load leaderboard
try:
with open('leaderboard.json', 'r') as f:
leaderboard = json.load(f)
except FileNotFoundError:
leaderboard = []
# Load AI model
tokenizer = AutoTokenizer.from_pretrained("TinyLlama/TinyLlama-1.1B-Chat-v1.0")
model = AutoModelForCausalLM.from_pretrained("TinyLlama/TinyLlama-1.1B-Chat-v1.0")
@app.route('/')
def index():
return render_template('index.html', coins=coins, game_state=game_state, leaderboard=leaderboard)
@app.route('/flip', methods=['POST'])
def flip_coin():
if game_state['flips_left'] > 0:
coin = coins[game_state['current_coin']]
is_heads = random.random() < coin['winrate']
if is_heads:
game_state['balance'] += coin['value']
# Apply coin bonus if it exists
if coin['bonus'] != 'none':
apply_bonus(coin['bonus'])
game_state['flips_left'] -= 1
return jsonify({
'result': 'H' if is_heads else 'T',
'balance': game_state['balance'],
'flips_left': game_state['flips_left']
})
return jsonify({'error': 'No flips left'})
@app.route('/buy', methods=['POST'])
def buy_coin():
index = int(request.json['index'])
if index < len(coins) and game_state['balance'] >= coins[index]['price'] and index != game_state['current_coin']:
game_state['balance'] -= coins[index]['price']
game_state['current_coin'] = index
return jsonify({'success': True, 'balance': game_state['balance']})
return jsonify({'success': False})
@app.route('/generate_coin', methods=['POST'])
def generate_coin():
if game_state['balance'] < 4:
return jsonify({'success': False, 'error': 'Not enough balance to generate a coin'})
prompt = """Generate a new coin for a game in JSON format with the following properties:
name (a creative name for the coin),
color (as a hex code),
price (higher than 10),
value (higher than 0.1),
winrate (between 0.5 and 0.8),
bonus (a bonus effect that triggers on successful flips, e.g., '+2 flips_left', '+0.5 balance', 'none')
Example:
{
"name": "Lucky Clover",
"color": "#2ecc71",
"price": 15,
"value": 0.2,
"winrate": 0.65,
"bonus": "+2 flips_left"
}
"""
inputs = tokenizer(prompt, return_tensors="pt")
with torch.no_grad():
outputs = model.generate(**inputs, max_length=300)
response = tokenizer.decode(outputs[0], skip_special_tokens=True)
try:
new_coin = json.loads(response)
if validate_coin(new_coin):
coins.append(new_coin)
with open('coins.json', 'w') as f:
json.dump(coins, f)
game_state['balance'] -= 4
return jsonify({'success': True, 'coin': new_coin, 'balance': game_state['balance']})
else:
return jsonify({'success': False, 'error': 'Invalid coin format'})
except json.JSONDecodeError:
return jsonify({'success': False, 'error': 'Invalid JSON format'})
@app.route('/game_over', methods=['POST'])
def game_over():
initials = request.json['initials']
score = game_state['balance']
leaderboard.append({'initials': initials, 'score': score})
leaderboard.sort(key=lambda x: x['score'], reverse=True)
leaderboard = leaderboard[:10] # Keep only top 10
with open('leaderboard.json', 'w') as f:
json.dump(leaderboard, f)
return jsonify({'success': True})
@app.route('/reset_game', methods=['POST'])
def reset_game():
game_state['balance'] = 0
game_state['flips_left'] = 1000
game_state['current_coin'] = 0
return jsonify({'success': True})
def validate_coin(coin):
required_keys = ['name', 'color', 'price', 'value', 'winrate', 'bonus']
return all(key in coin for key in required_keys) and \
isinstance(coin['name'], str) and \
isinstance(coin['color'], str) and coin['color'].startswith('#') and \
isinstance(coin['price'], (int, float)) and coin['price'] > 10 and \
isinstance(coin['value'], (int, float)) and coin['value'] > 0.1 and \
isinstance(coin['winrate'], (int, float)) and 0.5 <= coin['winrate'] <= 0.8 and \
isinstance(coin['bonus'], str)
def apply_bonus(bonus):
if bonus.startswith('+'):
value, attribute = bonus.split()[0][1:], bonus.split()[1]
if attribute == 'flips_left':
game_state['flips_left'] += int(value)
elif attribute == 'balance':
game_state['balance'] += float(value)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=7860) |