Preperations for setting up game picker 1.0

This commit is contained in:
2023-11-22 12:06:58 +10:00
parent c2ea96445d
commit a7fc6da2cb
10 changed files with 18 additions and 3 deletions

145
src/py/Acronymbot.py Normal file
View File

@@ -0,0 +1,145 @@
import random
import discord
import sqlite3
from discord import app_commands
from BlackJack import BlackJack
from Calculator import Calculator
from Gamepicker import pick_game
botIntents = discord.Intents.all()
client = discord.Client(intents=botIntents)
tree = app_commands.CommandTree(client)
blackJack = BlackJack()
@client.event
async def on_ready():
await tree.sync()
print('Itsa me Mario!')
# @client.event
# async def on_message_delete(message: discord.Message):
# channel = client.get_channel(message.channel.id)
# await channel.send(f"{message.author} deleted a message! @everyone, get him!")
# dmessage = await channel.send(f"Here's the message they deleted! \"{message.content}\". What a sick fuck")
# await dmessage.delete()
"""
#### Test ####
"""
class Buttons(discord.ui.View):
def __init__(self, *, timeout=180):
super().__init__(timeout=timeout)
@discord.ui.button(label="Pay $5", style=discord.ButtonStyle.green)
async def green_button(self, interaction: discord.Interaction, button: discord.ui.Button):
print(f"{interaction.user} pressed the green button")
button.disabled = True
button.label = "No Refunds!"
for child in self.children:
child.disabled = True
await interaction.response.edit_message(content=f"Mario Moment Achieved", view=self)
@discord.ui.button(label="Punch AcryBot", style=discord.ButtonStyle.red)
async def red_button(self, interaction: discord.Interaction, button: discord.ui.Button):
print(f"{interaction.user} pressed the red button")
button.disabled = True
button.label = f"fuck you {interaction.user}"
for child in self.children:
child.disabled = True
await interaction.response.edit_message(content=f"Ouch!", view=self)
@tree.command(description="Lmao")
async def test(interaction:discord.Interaction):
print(f"{interaction.user} used command! Woohoo!")
try:
await interaction.response.send_message("Pay $5 for a Mario Moment", view=Buttons())
except discord.app_commands.errors.CommandInvokeError:
print("Uh oh! It failed!")
"""
#### Black Jack ####
"""
class HitOrStand(discord.ui.View):
def __init__(self, *, timeout=180):
super().__init__(timeout=timeout)
self.content = False
@discord.ui.button(label="Hit", style=discord.ButtonStyle.green)
async def hit(self, interaction: discord.Interaction, button: discord.ui.Button):
self.content = True
for child in self.children:
child.disabled = True
await interaction.response.edit_message(content="You Hit!", view=self)
self.stop()
@discord.ui.button(label="Stand", style=discord.ButtonStyle.red)
async def stand(self, interaction: discord.Interaction, button: discord.ui.Button):
self.content = False
for child in self.children:
child.disabled = True
await interaction.response.edit_message(content="You stood!", view=self)
self.stop()
@tree.command(description="Play Black Jack!")
async def bj(interaction: discord.Interaction):
discinput = lambda m: discordInput(interaction, m)
discoutput = lambda m: discordOutput(interaction, m)
await interaction.response.send_message("Let's play Black Jack!")
await blackJack.play_game(interaction.user.id, 100, discinput, discoutput)
async def discordInput(interaction: discord.Interaction, message:str):
response = HitOrStand()
await interaction.followup.send(message, view=response)
await response.wait()
return response.content
async def discordOutput(interaction: discord.Interaction, message):
await interaction.followup.send(message)
@tree.command(description="Find your Balance")
async def bal(interaction: discord.Interaction):
ID = interaction.user.id
data = blackJack.ledger.read(ID)
data = list(data)
await interaction.response.send_message(f"Wins:{data[2]}, Losses:{data[3]}. ${data[1]}")
"""
#### Calculator ####
"""
@tree.command(description="Do Meth")
async def calculator(interaction: discord.Interaction):
await interaction.response.defer()
calculator = Calculator()
await interaction.followup.send(content="`" + " " * calculator.MAXIMUMBARSIZE + "0`", view=calculator)
"""
#### Game Picker ####
"""
@tree.command(description="Pick a game")
async def gg(interaction: discord.Interaction):
game = pick_game()
await interaction.response.send_message("Barotrauma")
@tree.command(description="Roll a Dice")
@app_commands.choices(dice = [
app_commands.Choice(name = 'd4', value=4),
app_commands.Choice(name = 'd6', value=6),
app_commands.Choice(name = 'd8', value=8),
app_commands.Choice(name = 'd10', value=10),
app_commands.Choice(name = 'd12', value=12),
app_commands.Choice(name = 'd20', value=20),
app_commands.Choice(name = 'd100', value=100),
])
async def roll(interaction: discord.Interaction, dice:app_commands.Choice[int]):
roll = random.randint(1, dice.value)
await interaction.response.send_message(f"{dice.name}: {roll}")
"""
#### Fin ####
"""
client.run('NzgwNzg4NDIwMjkzMDM0MDA0.GEKkUB.Bbl09D3lWMGea_mcIESPMLUyGlkW-6N53BPFjI')

324
src/py/BlackJack.py Normal file
View File

@@ -0,0 +1,324 @@
import random
from Ledger import Ledger
#TODO Starting a game with 21 fucks with hidden cards
#TODO Look into 5card jack thingo that Tim mentioned
#TODO Insurance - If dealer starts with 21, you can bet against it and win your money back
#TODO Make each game session more distinct (Embeds?)
# Game States
INIT = 0
PLAYERTURN = 1
DEALERTURN = 2
FINISHED = 3
OVER = 5
"""
Class which describes playing cards
"""
class Card():
"""
A joker card has value 0 and suit 0
"""
HEARTS = 1
DIAMONDS = 2
SPADES = 3
CLUBS = 4
def __init__(self, value, suit) -> None:
self.value = value
self.suit = suit
self.hidden = False
def turn_card(self):
# XOR to flip hidden element
self.hidden = self.hidden != True
def get_value(self):
return self.value
def get_suit(self):
return self.suit
def __str__(self) -> str:
suits = ["J", "", "", "", ""]
special_cards = {1: "A", 11: "J", 12: "Q", 13: "K"}
strValue = ""
if self.value in special_cards.keys():
strValue = special_cards[self.value]
else:
strValue = str(self.value)
string = ""
string = f"{suits[self.suit]}{strValue}"
if self.hidden:
string = "??"
return string
def __repr__(self) -> str:
return str(self)
"""
Class for interacting with a deck of cards
"""
class Deck():
def __init__(self, joker = False) -> None:
self.deck = []
self.discard = []
self.joker = joker
self.deck.extend([Card(x, Card.HEARTS) for x in range(1, 13)])
self.deck.extend([Card(x, Card.DIAMONDS) for x in range(1, 13)])
self.deck.extend([Card(x, Card.SPADES) for x in range(1, 13)])
self.deck.extend([Card(x, Card.CLUBS) for x in range(1, 13)])
if joker:
self.deck.append(Card(0, 0))
def shuffle(self):
random.shuffle(self.deck)
def sort(self):
self.deck.sort()
def take_from_deck(self):
card = self.deck.pop()
return card
def return_to_deck_top(self, card):
self.deck.insert(0, card)
def returnToDeckBottom(self, card):
self.deck.append(card)
def addToDiscard(self, card):
self.discard.insert(0, card)
def returnFromDiscard(self):
self.returnToDeckTop(self.discard.pop())
def return_all_from_discard(self):
self.deck.extend(self.discard)
self.discard = []
def __str__(self) -> str:
string = ""
for card in self.deck:
string += str(card)
return string
def __len__(self):
return len(self.deck)
class Hand():
def __init__(self) -> None:
self.hand = []
def sortHand(self):
self.hand.sort()
def add_to_hand(self, card, index = None):
if index is None:
self.hand.append(card)
else:
self.hand.insert(index, card)
def remove_from_hand(self, index):
return self.hand.pop(index)
def peek_card(self, index):
return self.hand[index]
def hide_card(self, index):
self.peek_card(index).turn_card()
def __len__(self):
return len(self.hand)
def __str__(self) -> str:
string = ""
for card in self.hand:
string += str(card)
string += " "
return string
def __repr__(self) -> str:
value = 0
aces = 0
# Add static values
for card in self.hand:
if card.value == 1:
aces += 1
continue
if card.value > 10:
card.value = 10
value += card.value
# Dynamically add ace value based on ideal rules
maxAceValue = aces * 11
tempValue = value + maxAceValue
if tempValue < 21:
return str(tempValue)
while (tempValue > 21) and aces > 0:
tempValue = tempValue - 10
aces = aces - 1
value = tempValue
return str(value)
def __iter__(self):
self.iter = iter(self.hand)
return self.iter
def __next__(self):
return next(self.iter)
class BlackJack:
def __init__(self) -> None:
self.deck = Deck()
self.playerHand = Hand()
self.dealerHand = Hand()
self.ledger = Ledger()
def deal_card(self, hand):
hand.add_to_hand(self.deck.take_from_deck())
def game_setup(self):
# Deal cards in alternate order
self.deck.shuffle()
for _ in range(2):
self.deal_card(self.playerHand)
self.deal_card(self.dealerHand)
# Hide one of the dealers cards
self.dealerHand.hide_card(1)
def discard_hand(self, hand):
for _ in range(len(hand)):
card = hand.remove_from_hand(0)
self.deck.addToDiscard(card)
async def show_cards(self, send, displayDealerScore=False):
# Show Cards to player
string = f"Player Hand = {repr(self.playerHand)}: {self.playerHand}\nDealer Hand = ??: {self.dealerHand}"
if displayDealerScore:
string = f"Player Hand = {repr(self.playerHand)}: {self.playerHand}\nDealer Hand = {repr(self.dealerHand)}: {self.dealerHand}"
await send(string)
async def play_game(self, ID, bet, recv, send):
gameState = INIT
while gameState != OVER:
if gameState == INIT:
playerStats = self.ledger.read(ID)
if playerStats is None:
self.ledger.write(ID)
playerStats = self.ledger.read(ID)
self.game_setup()
gameState = PLAYERTURN
if gameState == PLAYERTURN:
await self.show_cards(send)
playerHit = await recv("Hit or Stand?")
if playerHit:
self.deal_card(self.playerHand)
else:
#TODO Rename hide_card function
self.dealerHand.hide_card(1)
gameState = DEALERTURN
if int(repr(self.playerHand)) >= 21:
self.dealerHand.hide_card(1)
gameState = FINISHED
if gameState == DEALERTURN:
if int(repr(self.dealerHand)) > int(repr(self.playerHand)):
gameState = FINISHED
continue
self.deal_card(self.dealerHand)
if int(repr(self.dealerHand)) >= 17:
gameState = FINISHED
if gameState == FINISHED:
playerBlackJack = False
dealerBlackJack = False
playerBust = False
dealerBust = False
playerHigher = False
dealerHigher = False
tie = False
playerScore = int(repr(self.playerHand))
dealerScore = int(repr(self.dealerHand))
await self.show_cards(send, True)
if playerScore == 21:
playerBlackJack = True
if dealerScore == 21:
dealerBlackJack = True
if playerScore > 21:
playerBust = True
if dealerScore > 21:
dealerBust = True
if dealerScore > playerScore:
dealerHigher = True
elif playerScore > dealerScore:
playerHigher = True
else:
tie = True
self.discard_hand(self.playerHand)
self.discard_hand(self.dealerHand)
if tie:
await send("You tied")
elif playerBlackJack:
await send("You reached BlackJack!")
win = (2*bet, 1, 0, ID)
self.ledger.update(ID, win)
elif dealerBlackJack:
await send("The dealer reached BlackJack!")
loss = (-bet, 0, 1, ID)
self.ledger.update(ID, loss)
elif playerBust:
await send("You busted!")
loss = (-bet, 0, 1, ID)
self.ledger.update(ID, loss)
elif dealerBust:
await send("The dealer busted!")
win = (2*bet, 1, 0, ID)
self.ledger.update(ID, win)
elif playerHigher:
await send("You won!")
win = (2*bet, 1, 0, ID)
self.ledger.update(ID, win)
elif dealerHigher:
await send("You lost!")
loss = (-bet, 0, 1, ID)
self.ledger.update(ID, loss)
else:
await send("Report this game to my creator!")
if len(self.deck) < 0.25 * 51:
self.deck.return_all_from_discard()
self.deck.shuffle()
await send("Everyday I'm shuffling")
gameState = OVER
def main():
game = BlackJack()
trueFalseInput = lambda x: input(x) == "h"
game.play_game(recv=trueFalseInput, send=print)
pass
if __name__ == "__main__":
main()

151
src/py/Calculator.py Normal file
View File

@@ -0,0 +1,151 @@
import discord
addition = lambda x, y: x + y
subtraction = lambda x, y: x - y
multiplication = lambda x, y: x * y
division = lambda x, y: x / y
exponent = lambda x, y: x ** y
funckyDict = {
addition: "+",
subtraction: "-",
multiplication: "*",
division: "/",
exponent: "^"
}
async def number(self, interaction: discord.Interaction, number):
if self.output is not None:
self.inputOne = 0
self.output = None
self.inputOne = self.inputOne * 10 + number
self.numDigs = self.numDigs + 1
await interaction.response.edit_message(
content=self.display(),
view=self)
async def operator(self, interaction: discord.Interaction, operation):
self.output = None
self.inputTwo = self.inputOne
self.inputOne = 0
self.expression = operation
await interaction.response.edit_message(
content=self.display(),
view=self)
class NumberButton(discord.ui.Button):
def __init__(self, number: int, row) -> None:
super().__init__()
self.number = number
self.row = row
self.style = discord.ButtonStyle.blurple
self.label = str(number)
async def callback(self, interaction: discord.Interaction):
await number(self.view, interaction, self.number)
class OperatorButton(discord.ui.Button):
def __init__(self, function, row) -> None:
super().__init__()
self.function = function
self.row = row
self.style = discord.ButtonStyle.red
self.label = funckyDict[function]
async def callback(self, interaction: discord.Interaction):
await operator(self.view, interaction, self.function)
class Calculator(discord.ui.View):
def __init__(self, *, timeout=180):
super().__init__(timeout=timeout)
self.numDigs = 0
self.MAXIMUMBARSIZE = 30
m = 0
self.inputOne = 0
self.inputTwo = None
self.expression = None
self.output = None
self.digit = 1
self.clearRequirement = 0
numRows = 4
numColumns = 4
buttonFunctions = [
[1, 2, 3, addition],
[4, 5, 6, multiplication],
[7, 8, 9, subtraction],
[exponent, 0, None, division]
]
for i in range(0, numRows):
for j in range(0, numColumns):
item = buttonFunctions[i][j]
if item is None:
continue
if isinstance(item, int):
button = NumberButton(item, i)
else:
button = OperatorButton(item, i)
self.add_item(button)
def numDigits(self, integer):
numDigits = 0
while(integer):
numDigits += 1
integer = integer // 10
return numDigits
def clear(self):
self.inputOne = 0
self.inputTwo = None
self.output = None
self.clearRequirement = 0
def display(self):
inputOneLength = self.numDigits(self.inputOne)
inputTwoLength = self.numDigits(self.inputTwo)
outputLength = self.numDigits(self.output)
if (self.inputTwo is None) and (self.output is None):
padding = self.MAXIMUMBARSIZE - inputOneLength - 1
displayOutput = " ".join(['`', ' ' * padding, f"{self.inputOne}", "`"])
elif (self.output is None):
padding = self.MAXIMUMBARSIZE - inputOneLength - inputTwoLength - 3
displayOutput = " ".join(['`', ' ' * padding, f"{self.inputTwo}", f"{funckyDict[self.expression]}", f"{self.inputOne}", "`"])
else:
padding = self.MAXIMUMBARSIZE - inputOneLength - inputTwoLength - outputLength - 4
displayOutput = " ".join(['`', ' ' * padding, f"{self.inputTwo}", f"{funckyDict[self.expression]}", f"{self.inputOne}", "=", f"{self.output}", "`"])
return displayOutput
@discord.ui.button(label="=", style=discord.ButtonStyle.green, row=3)
async def equals(self, interaction: discord.Interaction, button: discord.ui.Button):
if self.inputTwo is None:
await interaction.response.edit_message(
content="ERROR",
view=self)
if self.clearRequirement:
self.clearRequirement = 0
self.clear()
else:
self.clearRequirement += 1
self.output = self.expression(self.inputTwo, self.inputOne)
if (self.inputTwo == 9) and (self.inputOne == 10) and (self.expression == addition):
self.output = 21
await interaction.response.edit_message(
content=self.display(),
view=self)
self.inputOne = self.output
self.inputTwo = None

10
src/py/Dockerfile Normal file
View File

@@ -0,0 +1,10 @@
FROM python:3
RUN pip install discord
WORKDIR /usr/app/src
VOLUME /usr/app/src
# -v flag to mount to this volume. -v [from]:/usr/app/src
CMD [ "python", "./Acronymbot.py" ]

35
src/py/Gamepicker.py Normal file
View File

@@ -0,0 +1,35 @@
import discord
import random
# Temporary List
# games = ["Left 4 Dead 2",
# "Aragami",
# "Astroneer",
# "Factorio",
# "Borderlands",
# "Stardew Valley",
# "Viscera Cleanup Detail",
# "SCP",
# "Satisfactory",
# "Backrooms (Alternate Ending)",
# "Ghost Recon Wildlands"
# ]
games = ["Plate Up",
"Terraria",
"Ghost Recon"]
def add_game(game: str):
games.append(game)
def pick_game():
randomIndex = random.randrange(0, len(games))
coinFlip = random.randrange(0, 2)
if coinFlip:
return f"Valorant ({games[randomIndex]})"
else:
return games[randomIndex]

58
src/py/Ledger.py Normal file
View File

@@ -0,0 +1,58 @@
import sqlite3
class Database():
def __init__(self, name, tableCommand) -> None:
self.db = sqlite3.connect(name)
self.data = self.db.cursor()
self.data.execute(tableCommand)
def read(self, primaryKey, selectQuery):
self.data.execute(selectQuery, (primaryKey,))
data = self.data.fetchone()
return data
def write(self, ID, insertQuery):
self.data.execute(insertQuery, (ID,))
self.db.commit()
def update(self, ID, data, newData, updateQuery):
data = [data[i] + newData[i] for i in range(len(data))]
data.append(ID)
self.data.execute(updateQuery, data)
self.db.commit()
class Ledger(Database):
def __init__(self) -> None:
tableCommand = """ CREATE TABLE IF NOT EXISTS ledger (
ID integer PRIMARY KEY,
USERID integer,
MONEY integer DEFAULT 100,
WINS integer DEFAULT 0,
LOSSES integer DEFAULT 0
); """
super().__init__("ledger.db", tableCommand)
def read(self, ID):
selectQuery = """SELECT USERID, MONEY, WINS, LOSSES FROM ledger WHERE USERID = ?"""
data = super().read(ID, selectQuery)
return data
def write(self, ID):
insertQuery = """ INSERT INTO ledger(USERID)
VALUES(?) """
super().write(ID, insertQuery)
def update(self, ID, newData):
query = """ UPDATE ledger
SET MONEY = ?,
WINS = ?,
LOSSES = ?
WHERE USERID = ?"""
data = list(self.read(ID))[1:]
super().update(ID, data, newData, query)
def main():
pass
if __name__ == "__main__":
main()