Skip to content

Instantly share code, notes, and snippets.

@viniciuspereiras
Created December 24, 2024 20:00
Show Gist options
  • Save viniciuspereiras/6040e47b05745b9749b34942a9be371c to your computer and use it in GitHub Desktop.
Save viniciuspereiras/6040e47b05745b9749b34942a9be371c to your computer and use it in GitHub Desktop.
I used whatbeatsrock.com api to code a TUI version of the game, but with "saved sessions" and "try again" features and GPT, the prompt is not refined yet, try your own.
import requests
import sys
import os
import readline
import random
import uuid
import json
from openai import OpenAI
from time import sleep
def uuid_generator():
return str(uuid.uuid4())
def random_string():
randomstr = ''.join(random.choices('abcdefghijklmnopqrstuvwxyz', k=10))
return f'{randomstr}'
def send(prev, guess):
sleep(2) # prevent to be banned by the rate limit, I hope
url = "https://www.whatbeatsrock.com:443/api/vs"
headers = {"User-Agent": "Chrome/125.0.6422.60 Safari/537.36", "Content-Type": "application/json"}
json={"gid": UUID_SESSION, "guess": guess, "prev": prev}
res = requests.post(url, headers=headers, json=json)
return res.json()
def rebuild_session(history):
print('Rebuilding session...')
for position, guess in enumerate(history):
if position == len(history) - 1:
break
if type(guess) != dict:
guess_text = guess.split(';')[0]
next_guess = history[position + 1].split(';')[0]
else:
guess_text = guess['name']
next_guess = history[position + 1]['name']
send(guess_text, next_guess)
def load_session():
with open(SESSION_FILE, 'r') as f:
data = f.read()
data = json.loads(data)
if len(data) > 1:
rebuild_session(data)
return data
def write_session(data: dict):
with open(SESSION_FILE, 'r') as f:
content = f.read()
content = json.loads(content)
content.append(data)
with open(SESSION_FILE, 'w') as f:
f.write(json.dumps(content))
print("pwning whatbeatsrock.com")
if len(sys.argv) == 1:
print("usage: python main.py <session>")
sys.exit(1)
SESSION_FILE = sys.argv[1]
UUID_SESSION = uuid_generator()
if not os.path.exists(SESSION_FILE):
print('creating session file')
data = []
data.append({'name': 'rock', 'emoji': '🪨'})
with open(SESSION_FILE, 'w') as f:
f.write(json.dumps(data))
# gpt logic
client = OpenAI(
api_key="sk-YOUROPENAIKEY")
def gpt_awnser(target, prohibited):
a = prohibited[0]
wrong = [
{"role": "assistant", "content": a},
{"role": "user", "content": 'wrong, try again'},
]
while a in prohibited:
# breakpoint()
chat_completion = client.chat.completions.create(
messages=[
{"role": "system", "content": f"You are designed to choose what beats something. User will provide you an word and you will decide what beats that. Your response should be ONLY the name of the option that beats the other. Be carrerful with oposite words, like 'up' and 'down'. Be creative!"},
{"role": "user", "content": f'Who beats {target}? Dont say {", ".join(prohibited)}, find something else.'},
] + wrong,
temperature=2,
model="gpt-4o",
)
a = chat_completion.choices[0].message.content.lower()
wrong.append({"role": "assistant", "content": a})
wrong.append({"role": "user", "content": 'wrong, try again'})
return a
prohibited_words = []
# play loop
playing = True
session_history = load_session()
score = len(session_history)
actual = session_history[-1]['name']
actual_emoji = session_history[-1]['emoji']
while playing:
print(f'Score: {score}')
print(f'Who beats {actual} {actual_emoji}?')
guess = gpt_awnser(actual, [session_history[i]['name'] for i in range(len(session_history))] + prohibited_words)
print('GPT-4o: ', guess)
send_response = send(actual, guess)
if send_response['data']['guess_wins']:
print(f'Yes! {send_response["data"]["reason"]}')
data_to_write = {'name': guess, 'emoji': send_response["data"]["guess_emoji"]}
write_session(data_to_write)
session_history.append(data_to_write)
score += 1
actual = guess
actual_emoji = send_response["data"]["guess_emoji"]
else:
print(f'No! {send_response["data"]["reason"]}')
playing = False
print('Game Over!')
print(f'Your score was {score}')
print('Trying again...')
prohibited_words.append(guess)
UUID_SESSION = uuid_generator()
rebuild_session(session_history)
score = len(session_history)
playing = True
print('Bye!')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment