Skip to content

Commit

Permalink
refactor: create single map to hold games
Browse files Browse the repository at this point in the history
Every game is stored in a map and retrieved when a new message is fired, so the bot can only keep one handler and games are continued where they were started.
  • Loading branch information
Théo Vidal committed Jan 6, 2021
1 parent 35874ab commit 1ecf8ef
Show file tree
Hide file tree
Showing 9 changed files with 207 additions and 133 deletions.
6 changes: 3 additions & 3 deletions assets/irregular_verbs.csv
Original file line number Diff line number Diff line change
Expand Up @@ -54,13 +54,13 @@ bend,bent,bent,"plier, courber, (se) pencher"
come,came,come,venir
drive,drove,driven,conduire
fly,flew,flown,voler
sit,sat,sat,s’asseoir
sit,sat,sat,"s’asseoir"
go,went,gone,aller
kneel,knelt,knelt,s’agenouiller
kneel,knelt,knelt,"s’agenouiller"
lean,leant,leant,pencher
leave,left,left,"partir, quitter"
ride,rode,ridden,"faire du cheval, du vélo"
rise,rose,risen,s’élever
rise,rose,risen,"s’élever"
run,ran,run,courir
sit,sat,sat,s’asseoir
speed,sped,sped,aller vite
Expand Down
122 changes: 0 additions & 122 deletions commands/irregular_verbs.go

This file was deleted.

52 changes: 52 additions & 0 deletions games/irregular_verbs/answer.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package irregular_verbs

import (
"fmt"
"github.com/bwmarrin/discordgo"
"github.com/theovidal/105quiz/lib"
"github.com/theovidal/onyxcord"
)

func HandleAnswer(bot *onyxcord.Bot, message *discordgo.Message, player *lib.Client) {
if message.Author.Bot {
return
}
trial := lib.TrimNonLetters(message.Content)

if lib.Contains(stopSentences, trial) {
player.Props["answers"] = player.Props["answers"].(int) - 1
bot.Client.ChannelMessageSend(
message.ChannelID,
fmt.Sprintf(
":stop_sign: **Arrêt du quiz en cours!** Vous avez réussi %d questions sur %d (note de %.2f/20)",
player.Props["successfulAnswers"].(int),
player.Props["answers"].(int),
(float64(player.Props["successfulAnswers"].(int))/float64(player.Props["answers"].(int)))*20.0,
),
)
VerbsPlayers.RemovePlayer(message.ChannelID)
return
}

if lib.Contains(skipSentences, trial) {
bot.Client.ChannelMessageSend(
message.ChannelID,
fmt.Sprintf(":fast_forward: Le mot recherché était **%s**", player.Props["unknownVerb"]),
)
SendQuestion(bot, player)
return
}

println(trial, lib.TrimNonLetters(player.Props["unknownVerb"].(string)))

if trial == lib.TrimNonLetters(player.Props["unknownVerb"].(string)) {
bot.Client.MessageReactionAdd(message.ChannelID, message.ID, "✅")
if player.Props["succeeded"].(bool) {
player.Props["successfulAnswers"] = player.Props["successfulAnswers"].(int) + 1
}
SendQuestion(bot, player)
} else {
bot.Client.MessageReactionAdd(message.ChannelID, message.ID, "❌")
player.Props["succeeded"] = false
}
}
30 changes: 30 additions & 0 deletions games/irregular_verbs/command.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package irregular_verbs

import (
"github.com/bwmarrin/discordgo"
"github.com/theovidal/onyxcord"

"github.com/theovidal/105quiz/lib"
)

var VerbsPlayers lib.Players

func Command() *onyxcord.Command {
return &onyxcord.Command{
Description: "Lancer un quiz sur les verbes irréguliers en anglais",
Show: true,
ListenInPublic: true,
ListenInDM: true,
Execute: func(arguments []string, bot onyxcord.Bot, message *discordgo.MessageCreate) (err error) {
player := lib.NewClient(message)
player.Props["answers"] = 0
player.Props["successfulAnswers"] = 0
VerbsPlayers.AddPlayer(&player)

bot.Client.ChannelMessageSend(message.ChannelID, ":flag_gb: **Quiz sur les verbes irréguliers**")
SendQuestion(&bot, &player)

return
},
}
}
32 changes: 32 additions & 0 deletions games/irregular_verbs/questionSend.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package irregular_verbs

import (
"fmt"
"github.com/theovidal/onyxcord"
"math/rand"
"time"

"github.com/theovidal/105quiz/lib"
)

func SendQuestion(bot *onyxcord.Bot, player *lib.Client) {
rand.Seed(time.Now().UnixNano())
row := rand.Intn(len(verbs))
questionColumn := rand.Intn(4)
verbColumn := questionColumn

for verbColumn == questionColumn {
verbColumn = rand.Intn(4)
}

question := verbs[row][questionColumn]
verb := verbs[row][verbColumn]
player.Props["verb"] = verb

player.Props["answers"] = player.Props["answers"].(int) + 1
player.Props["succeeded"] = true
bot.Client.ChannelMessageSend(
player.Context.ChannelID,
fmt.Sprintf("**#%d** `%s` - Indiquer %s", player.Props["answers"], question, categories[verbColumn]),
)
}
28 changes: 28 additions & 0 deletions games/irregular_verbs/utils.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package irregular_verbs

import (
"encoding/csv"
"log"
"os"
)

var categories = []string{"la **base verbale**", "le **prétérit**", "le **participe passé**", "la **traduction**"}
var skipSentences = []string{"jepasse", "passe", "passer", "suivant", "skip", "jsp", "jesaispas", "jesaipa", "jesaispa", "jesaipas", "aucuneidee"}
var stopSentences = []string{"stop", "arret", "arreter", "tg", "areter"}

var verbs = OpenVerbs()

func OpenVerbs() [][]string {
file, err := os.Open("assets/irregular_verbs.csv")
if err != nil {
log.Panicln(err)
}

reader := csv.NewReader(file)
records, err := reader.ReadAll()
if err != nil {
log.Panicln(err)
}

return records
}
45 changes: 45 additions & 0 deletions lib/players.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package lib

import (
"sync"

"github.com/bwmarrin/discordgo"
)

type Client struct {
Context *discordgo.MessageCreate
Props map[string]interface{}
}

func NewClient(context *discordgo.MessageCreate) Client {
return Client{
Context: context,
Props: make(map[string]interface{}),
}
}

type Players struct {
sync.RWMutex
clients map[string]*Client
}

func (p *Players) Initialize() {
p.clients = make(map[string]*Client)
}

func (p *Players) AddPlayer(client *Client) {
p.Lock()
p.clients[client.Context.ChannelID] = client
p.Unlock()
}

func (p *Players) RemovePlayer(channel string) {
p.Lock()
delete(p.clients, channel)
p.Unlock()
}

func (p *Players) GetPlayer(channel string) (player *Client, exists bool) {
player, exists = p.clients[channel]
return
}
10 changes: 5 additions & 5 deletions commands/utils.go → lib/utils.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package commands
package lib

import (
"log"
Expand All @@ -11,17 +11,17 @@ import (
"golang.org/x/text/unicode/norm"
)

func trimNonLetters(input string) (output string) {
func TrimNonLetters(input string) (output string) {
output = strings.ToLower(input)
output = trimAccents(input)
output = TrimAccents(output)

regex := regexp.MustCompile(`[^a-z]`)
output = string(regex.ReplaceAll([]byte(output), []byte{}))

return
}

func trimAccents(input string) string {
func TrimAccents(input string) string {
transformer := transform.Chain(norm.NFD, runes.Remove(runes.In(unicode.Mn)), norm.NFC)
output, _, err := transform.String(transformer, input)
if err != nil {
Expand All @@ -32,7 +32,7 @@ func trimAccents(input string) string {
}

// Checks if a specific slice contains a string
func contains(slice []string, text string) bool {
func Contains(slice []string, text string) bool {
for _, item := range slice {
if item == text {
return true
Expand Down
15 changes: 12 additions & 3 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,22 @@ import (
"github.com/bwmarrin/discordgo"
"github.com/theovidal/onyxcord"

"github.com/theovidal/105quiz/commands"
"github.com/theovidal/105quiz/games/irregular_verbs"
)

func main() {
bot := onyxcord.RegisterBot("105quiz")
bot := onyxcord.RegisterBot("105quiz", false)

bot.RegisterCommand("verbs", commands.IrregularVerbs())
bot.RegisterCommand("verbs", irregular_verbs.Command())
irregular_verbs.VerbsPlayers.Initialize()

bot.Client.AddHandler(func(session *discordgo.Session, message *discordgo.MessageCreate) {
verbsPlayer, exists := irregular_verbs.VerbsPlayers.GetPlayer(message.ChannelID)
if exists {
irregular_verbs.HandleAnswer(&bot, message.Message, verbsPlayer)
}
bot.OnCommand(session, message)
})

bot.Client.Identify.Intents = discordgo.MakeIntent(discordgo.IntentsGuildMessages | discordgo.IntentsDirectMessages)

Expand Down

0 comments on commit 1ecf8ef

Please sign in to comment.