File size: 8,024 Bytes
9357dc3
 
 
 
 
 
 
 
 
 
ef770ae
9357dc3
c6ca805
9357dc3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dfd2ecb
 
 
 
 
 
 
 
 
26d7bcd
 
9357dc3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1660f5f
9357dc3
 
 
 
 
 
 
 
 
 
 
 
 
 
1660f5f
9357dc3
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import threading
import openai
import os
import time
import random

openai.api_key = os.environ["OPENAI_KEY"]

games = {}
all_games_lock = threading.Lock()
TIME_TO_SUBMIT = 45
TIME_TO_VOTE = 30
TIME_TO_REVEAL = 18

GUESS_AI_PTS = 2
GUESSED_AS_AI_PTS = 1

with open("prompt.txt", "r") as f:
    PROMPT = f.read()


def new_minigame():
    return "Write a poem about mice!"


def ai_response(question):
    prompt = PROMPT.format(
        question,
    )
    completions = None
    while completions is None:
        try:
            completions = openai.Completion.create(
                engine="text-davinci-003", prompt=prompt, max_tokens=200, n=1, temperature=0.5
            )
        except:
            print("OpenAI connection error")
            time.sleep(1)
    response = completions["choices"][0]["text"].strip()
    
    return response


class Game:
    def __init__(self, room_name):
        self.room_name = room_name
        self.command = None
        self.players = []
        self.prompts = []
        self.prompts_completed = 0
        self.responses = {}
        self.response_list = []
        self.ai_response_index = None
        self.lock = threading.Lock()
        self.started = False
        self.stage = None
        self.stage_start_time = None
        self.stage_time_remaining = None
        self.total_stage_time = None
        self.complete = False
        self.last_update_index = 0
        self.input_allowed = False
        self.last_update_time = time.time()
        self.chat = []
        self.player_status = {}
        self.player_scores = {}
        self.player_guess = {}
        self.ai_answer = None

        games[room_name] = self

    def update(self):
        self.last_update_index += 1
        self.last_update_time = time.time()

    def start(self):
        self.started = True
        self.stage = "START"
        self.update()

    def get_player_state(self):
        return [
            [player, self.player_status[player], self.player_scores[player]]
            for player in self.players
        ]

    def format_chat(self, player_name):
        formatted_chat = [[None, self.command]]
        if self.stage == "COLLECTING_RESPONSSES":
            if player_name in self.responses:
                formatted_chat.append([self.responses[player_name], None])
        elif self.stage == "COLLECTING_VOTES":
            for msg_player, msg in self.response_list:
                if msg_player == player_name:
                    formatted_chat.append([msg, None])
                else:
                    formatted_chat.append([None, msg])
        elif self.stage == "REVEALING":
            for msg_player, msg in self.response_list:
                output_msg = f"**{msg_player or 'GPT'}**: {msg}\nGuessed by: {', '.join(player for player, guess in self.player_guess.items() if guess == msg_player)}"
                if msg_player == player_name:
                    formatted_chat.append([output_msg, None])
                else:
                    formatted_chat.append([None, output_msg])
        return formatted_chat

    def add_player(self, player_name, player_prompt):
        with self.lock:
            self.players.append(player_name)
            self.prompts.append(player_prompt)
            self.player_status[player_name] = None
            self.player_scores[player_name] = 0
            if len(self.players) == 1:
                self.command = f"You have entered the game."
            else:
                self.command = f"{', '.join(self.players[:-1])} and {self.players[-1]} are in this room."
            self.update()

    def add_chat(self, player, message):
        with self.lock:
            self.player_status[player] = "Submitted"
            self.responses[player] = message

    def select_chat(self, player, index):
        with self.lock:
            if self.stage != "COLLECTING_VOTES":
                return
            index = index - 1
            selected_player = self.response_list[index][0]
            self.player_guess[player] = selected_player
            self.player_status[player] = "Voted"


def new_game(room_name):
    with all_games_lock:
        if room_name in games:
            game = games[room_name]
            return game
        return Game(room_name)


def game_thread():
    while True:
        now = time.time()
        for room_name, game in games.items():
            if not game.started or game.complete:
                continue
            with game.lock:
                if game.stage == "START":
                    prompt = game.prompts[game.prompts_completed]
                    game.command = (
                        f"**{game.players[game.prompts_completed]}**: {prompt}"
                    )
                    game.input_allowed = True
                    game.player_status = {player: None for player in game.players}
                    game.player_guess = {player: None for player in game.players}
                    game.ai_answer = ai_response(prompt)
                    game.stage = "COLLECTING_RESPONSES"
                    game.responses = {}
                    game.stage_start_time = now
                    game.total_stage_time = TIME_TO_SUBMIT
                    game.stage_time_remaining = TIME_TO_SUBMIT
                    game.update()

                stage_time_remaining = int(
                    game.total_stage_time - (now - game.stage_start_time)
                )
                if stage_time_remaining != game.stage_time_remaining:
                    game.stage_time_remaining = stage_time_remaining
                    game.update()
                out_of_time = stage_time_remaining <= 0

                if game.stage == "COLLECTING_RESPONSES":
                    if out_of_time or all(
                        val == "Submitted" for val in game.player_status.values()
                    ):
                        game.stage = "COLLECTING_VOTES"
                        game.stage_start_time = now
                        game.total_stage_time = TIME_TO_VOTE
                        game.command = "Select the AI response!"
                        game.player_status = {player: None for player in game.players}
                        game.response_list = list(game.responses.items())
                        game.input_allowed = False
                        ai_answer = (None, game.ai_answer)
                        game.response_list.append(ai_answer)
                        random.shuffle(game.response_list)
                        game.ai_response_index = game.response_list.index(ai_answer)
                        game.update()

                elif game.stage == "COLLECTING_VOTES":
                    if out_of_time or all(
                        val == "Voted" for val in game.player_status.values()
                    ):
                        game.stage = "REVEALING"
                        game.command = "Here's the results!"
                        game.stage_start_time = now
                        game.total_stage_time = TIME_TO_REVEAL
                        for player, guess in game.player_guess.items():
                            if guess == None:
                                game.player_scores[player] += GUESS_AI_PTS
                            else:
                                game.player_scores[guess] += GUESSED_AS_AI_PTS
                        game.update()

                elif game.stage == "REVEALING":
                    if out_of_time:
                        game.stage = "START"
                        game.prompts_completed += 1
                        if game.prompts_completed == len(game.players):
                            game.complete = True
                            game.command = f"Game complete! Winners: {', '.join(player for player, score in game.player_scores.items() if score == max(game.player_scores.values()))}"
                        game.update()

        time.sleep(0.1)


thread = threading.Thread(target=game_thread)
thread.daemon = True
thread.start()