<commit_before>#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import curses
from locale import setlocale, LC_ALL
from random import choice, randint, shuffle
from math import ceil
from sys import exit
from time import sleep
from argparse import ArgumentParser

VERSION = '0.0.0'

setlocale(LC_ALL, '')

# Symbols
ARCHIVE = {
    'ASCII': {
        '0000': ' ',
        '0001': '-',
        '0010': '|',
        '0011': '\\',
        '0100': '-',
        '0101': '-',
        '0110': '/',
        '0111': 'v',
        '1000': '|',
        '1001': '/',
        '1010': '|',
        '1011': '<',
        '1100': '\\',
        '1101': '^',
        '1110': '>',
        '1111': '+',
    },
    'THICK': {
        '0000': ' ',
        '0001': '╸',
        '0010': '╻',
        '0011': '┓',
        '0100': '╺',
        '0101': '━',
        '0110': '┏',
        '0111': '┳',
        '1000': '╹',
        '1001': '┛',
        '1010': '┃',
        '1011': '┫',
        '1100': '┗',
        '1101': '┻',
        '1110': '┣',
        '1111': '╋',
    },
    'THIN': {
        '0000': ' ',
        '0001': '╴',
        '0010': '╷',
        '0011': '┐',
        '0100': '╶',
        '0101': '─',
        '0110': '┌',
        '0111': '┬',
        '1000': '╵',
        '1001': '┘',
        '1010': '│',
        '1011': '┤',
        '1100': '└',
        '1101': '┴',
        '1110': '├',
        '1111': '┼',
    },
    'DOUBLE': {
        '0000': ' ',
        '0001': '═',
        '0010': '║',
        '0011': '╗',
        '0100': '═',
        '0101': '═',
        '0110': '╔',
        '0111': '╦',
        '1000': '║',
        '1001': '╝',
        '1010': '║',
        '1011': '╣',
        '1100': '╚',
        '1101': '╩',
        '1110': '╠',
        '1111': '╬',
    },
}

# possible kinds of color sets, user can also use 'random' to pick a different
# one each iteration
COLOR_SETS = ['basic', 'rainbow', 'drab']

MAX_FRAMERATE_CHOICES = [1, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

# Create a randomized color palette based on the given color set with at least
# 'colors_needed' values
def get_color_palette(color_set, colors_needed):
    if color_set == 'random' or color_set not in COLOR_SETS:
        color_set = choice(COLOR_SETS)

    base_palette = None

    if color_set == 'rainbow':
        base_palette = [1, 2, 3, 4, 5, 9, 10, 11, 12, 13]
    elif color_set == 'drab':
        base_palette = [0, 7, 8, 15]
    elif color_set == 'basic':
        base_palette = [1, 2, 4]

    full_palette = base_palette * ceil(colors_needed / len(base_palette))
    shuffle(full_palette)

    return full_palette

def init(screen, all_symbols, color_set, min_pipes, max_pipes):
    rows, cols = screen.getmaxyx()

    matrix = {
        'symbols': all_symbols,
        'grid': [[None for _ in range(rows)] for _ in range(cols)],
        'cols': cols,
        'rows': rows
    }

    screen.clear()

    def redraw(all_symbols, matrix, seq):
        for point in seq:
            render(screen, all_symbols, matrix, point)

    mazes = []

    seed_count = randint(min_pipes, max_pipes)

    palette = get_color_palette(color_set, seed_count)

    for i in range(seed_count):
        maze = Maze(matrix,
                    color=palette[i])
        maze.redraw(redraw)
        mazes.append(maze)

    return matrix, mazes

def init_colors():
    if curses.has_colors():
        for c in range(0, 8):
            curses.init_pair(c + 1, c, -1)

def get_color(n):
    if not curses.has_colors():
        return curses.color_pair(0)

    if n in range(0, 8):
        return curses.color_pair(n + 1)

    if n in range(8, 16):
        return curses.color_pair(n + 1 - 8) | curses.A_BOLD

    return curses.color_pair(0)

# Render matrix
def render(screen, all_symbols, matrix, loc):

    def in_bounds(matrix, col, row):
        cols = len(matrix)
        rows = len(matrix[0])
        return 0 <= col and col < cols and 0 <= row and row < rows

    col = loc[0]
    row = loc[1]
    dirs = [(0, 0), (0, -1), (1, 0), (0, 1), (-1, 0)]
    for dir in dirs:
        ncol = col + dir[0]
        nrow = row + dir[1]
        if not in_bounds(matrix, ncol, nrow):
            continue
        srows, scols = screen.getmaxyx()
        try:
            if matrix[ncol][nrow] is None:
                screen.addstr(nrow, ncol,
                              all_symbols[matrix[ncol][nrow][2]]['0000'])
            else:
                key = ''
                for val in matrix[ncol][nrow][0]:
                    key += str(val)
                screen.addstr(nrow, ncol,
                              all_symbols[matrix[ncol][nrow][2]][key],
                              get_color(matrix[ncol][nrow][1]))
        except (TypeError, curses.error):
            # when drawing to the bottom-right corner, addstr() moves the
            # cursor one-past the end, thus failing...
            pass

class Maze:

    def __init__(self, matrix, color=None, symbol=None):
        self._matrix = matrix['grid']
        self._cols = matrix['cols']
        self._rows = matrix['rows']
        self._all_symbols = matrix['symbols']
        col = randint(0, self._cols - 1)
        row = randint(0, self._rows - 1)
        self._color = 0 if color is None else color
        if symbol is None:
            self._symbol = randint(0, len(self._all_symbols) - 1)
        else:
            self._symbol = symbol % len(self._all_symbols)
        if self._matrix[col][row] is None:
            self._matrix[col][row] = [[0, 0, 0, 0], self._color, self._symbol]
            self._stack = [(col, row)]
        else:
            self._stack = []
        self._redraw = None

    def redraw(self, f):
        self._redraw = f

    # Bounds check
    def _in_bounds(self, col, row):
        return 0 <= col and col < self._cols and 0 <= row and row < self._rows

    # Get neighbors
    def _neighbors(self, col, row):
        dirs = [(0, -1), (1, 0), (0, 1), (-1, 0)]
        adj = []
        for i, dir in enumerate(dirs):
            ncol = col + dir[0]
            nrow = row + dir[1]
            comb = self._in_bounds(ncol, nrow) and self._matrix[ncol][nrow]
            if comb is None:
                adj.append({
                    'dir': i,
                    'col': ncol,
                    'row': nrow
                })
        return adj

    def step(self, multi=True):
        if multi is True:
            while not self._step():
                pass
        else:
            self._step()

        return len(self._stack) != 0

    # Step internal
    def _step(self):
        if len(self._stack) < 1:
            return True

        col = self._stack[-1][0]
        row = self._stack[-1][1]

        adj = self._neighbors(col, row)
        if len(adj) == 0:  # no neighbors...
            self._stack = self._stack[:-1]
            return False

        next = choice(adj)
        self._matrix[col][row][0][next['dir']] = 1
        self._matrix[next['col']][next['row']] = [[0, 0, 0, 0],
                                                  self._color, self._symbol]
        self._matrix[next['col']][next['row']][0][(next['dir'] + 2) % 4] = 1
        self._stack.append((next['col'], next['row']))
        self._redraw(self._all_symbols, self._matrix, self._stack[-1:-3:-1])
        return True

def run(max_framerate, all_symbols, color_set, min_pipes, max_pipes):
    curses.initscr()
    curses.start_color()
    curses.use_default_colors()
    curses.noecho()
    curses.curs_set(0)
    screen = curses.initscr()
    screen.nodelay(1)
    screen.keypad(1)
    screen.clear()

    init_colors()

    frame_sleep_time = 1.0 / max_framerate

    matrix, mazes = init(screen, all_symbols, color_set, min_pipes, max_pipes)

    (running, paused, quitting) = range(0, 3)
    state = running

    while state != quitting:

        if state != paused:
            mazes = set([maze for maze in mazes if maze.step()])

            if len(mazes) < 1:
                matrix, mazes = init(screen, all_symbols, color_set, min_pipes,
                                     max_pipes)

        sleep(frame_sleep_time)

        event = screen.getch()

        if event == curses.ERR:
            continue
        elif event == ord('q'):
            state = quitting
        elif event == ord('p'):
            state = running if state == paused else paused
        elif event == ord(' '):
            matrix, mazes = init(screen, all_symbols, color_set, min_pipes,
                                 max_pipes)
            state = running
        elif event == curses.KEY_RESIZE:
            matrix, mazes = init(screen, all_symbols, color_set, min_pipes,
                                 max_pipes)
            state = running

    screen.clear()
    screen.keypad(0)
    screen.nodelay(0)
    curses.echo()
    curses.endwin()

    return 0

def main():
    p = ArgumentParser(description='Simple curses pipes')
    p.add_argument(
        '-s', '--symbol_set', nargs='*',
        choices=list(ARCHIVE.keys()), default=['ASCII'],
        help=('One or more allowable symbol sets to use, defaults to ASCII '
              'symbols')
        )
    p.add_argument(
        '-f', '--max_framerate', type=int, choices=MAX_FRAMERATE_CHOICES,
        default=100, help='Maximum allowable drawing rate')
    p.add_argument(
        '-c', '--color_set', type=str, choices=COLOR_SETS + ['random'],
        default='random',
        help='Change the color set pipes are drawn with, defaults to random'
        )
    p.add_argument(
        '-p', '--min_pipes', type=int, default=5,
        help='Minimum number of pipes to draw each round, defaults to 5'
        )
    p.add_argument(
        '-P', '--max_pipes', type=int, default=25,
        help='Maximum number of pipes to draw each round, defaults to 25'
        )

    args = p.parse_args()

    # validate number of pipes
    if args.min_pipes < 1:
        p.error('--min_pipes must be greater than 0')
    if args.max_pipes < 1:
        p.error('--max_pipes must be greater than 0')
    if args.min_pipes > args.max_pipes:
        p.error('--min_pipes must be less than or equal to --max_pipes')

    run(
        max_framerate=args.max_framerate,
        all_symbols=[ARCHIVE.get(syms) for syms in args.symbol_set],
        color_set=args.color_set,
        min_pipes=args.min_pipes,
        max_pipes=args.max_pipes
        )
    return 0

if __name__ == '__main__':
    exit(main())
<commit_msg>refactor ARCHIVE symbols<commit_after>#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import curses
from locale import setlocale, LC_ALL
from random import choice, randint, shuffle
from math import ceil
from sys import exit
from time import sleep
from argparse import ArgumentParser

VERSION = '0.0.0'

setlocale(LC_ALL, '')

# Symbols
ARCHIVE = {
    'ASCII': ' -|\\--/v|/|<\\^>+',
    'THICK': ' ╸╻┓╺━┏┳╹┛┃┫┗┻┣╋',
    'THIN': ' ╴╷┐╶─┌┬╵┘│┤└┴├┼',
    'DOUBLE': ' ═║╗══╔╦║╝║╣╚╩╠╬',
}

# possible kinds of color sets, user can also use 'random' to pick a different
# one each iteration
COLOR_SETS = ['basic', 'rainbow', 'drab']

MAX_FRAMERATE_CHOICES = [1, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

# Create a randomized color palette based on the given color set with at least
# 'colors_needed' values
def get_color_palette(color_set, colors_needed):
    if color_set == 'random' or color_set not in COLOR_SETS:
        color_set = choice(COLOR_SETS)

    base_palette = None

    if color_set == 'rainbow':
        base_palette = [1, 2, 3, 4, 5, 9, 10, 11, 12, 13]
    elif color_set == 'drab':
        base_palette = [0, 7, 8, 15]
    elif color_set == 'basic':
        base_palette = [1, 2, 4]

    full_palette = base_palette * ceil(colors_needed / len(base_palette))
    shuffle(full_palette)

    return full_palette

def init(screen, all_symbols, color_set, min_pipes, max_pipes):
    rows, cols = screen.getmaxyx()

    matrix = {
        'symbols': all_symbols,
        'grid': [[None for _ in range(rows)] for _ in range(cols)],
        'cols': cols,
        'rows': rows
    }

    screen.clear()

    def redraw(all_symbols, matrix, seq):
        for point in seq:
            render(screen, all_symbols, matrix, point)

    mazes = []

    seed_count = randint(min_pipes, max_pipes)

    palette = get_color_palette(color_set, seed_count)

    for i in range(seed_count):
        maze = Maze(matrix,
                    color=palette[i])
        maze.redraw(redraw)
        mazes.append(maze)

    return matrix, mazes

def init_colors():
    if curses.has_colors():
        for c in range(0, 8):
            curses.init_pair(c + 1, c, -1)

def get_color(n):
    if not curses.has_colors():
        return curses.color_pair(0)

    if n in range(0, 8):
        return curses.color_pair(n + 1)

    if n in range(8, 16):
        return curses.color_pair(n + 1 - 8) | curses.A_BOLD

    return curses.color_pair(0)

# Render matrix
def render(screen, all_symbols, matrix, loc):

    def in_bounds(matrix, col, row):
        cols = len(matrix)
        rows = len(matrix[0])
        return 0 <= col and col < cols and 0 <= row and row < rows

    col = loc[0]
    row = loc[1]
    dirs = [(0, 0), (0, -1), (1, 0), (0, 1), (-1, 0)]
    for dir in dirs:
        ncol = col + dir[0]
        nrow = row + dir[1]
        if not in_bounds(matrix, ncol, nrow):
            continue
        srows, scols = screen.getmaxyx()
        try:
            cell = matrix[ncol][nrow]
            if matrix[ncol][nrow] is None:
                screen.addstr(nrow, ncol, all_symbols[[2]][0])
            else:
                key = sum(cell[0][i] << (3 - i) for i in range(0, 4))
                screen.addstr(nrow, ncol, all_symbols[cell[2]][key],
                              get_color(cell[1]))
        except (TypeError, curses.error):
            # when drawing to the bottom-right corner, addstr() moves the
            # cursor one-past the end, thus failing...
            pass

class Maze:

    def __init__(self, matrix, color=None, symbol=None):
        self._matrix = matrix['grid']
        self._cols = matrix['cols']
        self._rows = matrix['rows']
        self._all_symbols = matrix['symbols']
        col = randint(0, self._cols - 1)
        row = randint(0, self._rows - 1)
        self._color = 0 if color is None else color
        if symbol is None:
            self._symbol = randint(0, len(self._all_symbols) - 1)
        else:
            self._symbol = symbol % len(self._all_symbols)
        if self._matrix[col][row] is None:
            self._matrix[col][row] = [[0, 0, 0, 0], self._color, self._symbol]
            self._stack = [(col, row)]
        else:
            self._stack = []
        self._redraw = None

    def redraw(self, f):
        self._redraw = f

    # Bounds check
    def _in_bounds(self, col, row):
        return 0 <= col and col < self._cols and 0 <= row and row < self._rows

    # Get neighbors
    def _neighbors(self, col, row):
        dirs = [(0, -1), (1, 0), (0, 1), (-1, 0)]
        adj = []
        for i, dir in enumerate(dirs):
            ncol = col + dir[0]
            nrow = row + dir[1]
            comb = self._in_bounds(ncol, nrow) and self._matrix[ncol][nrow]
            if comb is None:
                adj.append({
                    'dir': i,
                    'col': ncol,
                    'row': nrow
                })
        return adj

    def step(self, multi=True):
        if multi is True:
            while not self._step():
                pass
        else:
            self._step()

        return len(self._stack) != 0

    # Step internal
    def _step(self):
        if len(self._stack) < 1:
            return True

        col = self._stack[-1][0]
        row = self._stack[-1][1]

        adj = self._neighbors(col, row)
        if len(adj) == 0:  # no neighbors...
            self._stack = self._stack[:-1]
            return False

        next = choice(adj)
        self._matrix[col][row][0][next['dir']] = 1
        self._matrix[next['col']][next['row']] = [[0, 0, 0, 0],
                                                  self._color, self._symbol]
        self._matrix[next['col']][next['row']][0][(next['dir'] + 2) % 4] = 1
        self._stack.append((next['col'], next['row']))
        self._redraw(self._all_symbols, self._matrix, self._stack[-1:-3:-1])
        return True

def run(max_framerate, all_symbols, color_set, min_pipes, max_pipes):
    curses.initscr()
    curses.start_color()
    curses.use_default_colors()
    curses.noecho()
    curses.curs_set(0)
    screen = curses.initscr()
    screen.nodelay(1)
    screen.keypad(1)
    screen.clear()

    init_colors()

    frame_sleep_time = 1.0 / max_framerate

    matrix, mazes = init(screen, all_symbols, color_set, min_pipes, max_pipes)

    (running, paused, quitting) = range(0, 3)
    state = running

    while state != quitting:

        if state != paused:
            mazes = set([maze for maze in mazes if maze.step()])

            if len(mazes) < 1:
                matrix, mazes = init(screen, all_symbols, color_set, min_pipes,
                                     max_pipes)

        sleep(frame_sleep_time)

        event = screen.getch()

        if event == curses.ERR:
            continue
        elif event == ord('q'):
            state = quitting
        elif event == ord('p'):
            state = running if state == paused else paused
        elif event == ord(' '):
            matrix, mazes = init(screen, all_symbols, color_set, min_pipes,
                                 max_pipes)
            state = running
        elif event == curses.KEY_RESIZE:
            matrix, mazes = init(screen, all_symbols, color_set, min_pipes,
                                 max_pipes)
            state = running

    screen.clear()
    screen.keypad(0)
    screen.nodelay(0)
    curses.echo()
    curses.endwin()

    return 0

def main():
    p = ArgumentParser(description='Simple curses pipes')
    p.add_argument(
        '-s', '--symbol_set', nargs='*',
        choices=list(ARCHIVE.keys()), default=['ASCII'],
        help=('One or more allowable symbol sets to use, defaults to ASCII '
              'symbols')
        )
    p.add_argument(
        '-f', '--max_framerate', type=int, choices=MAX_FRAMERATE_CHOICES,
        default=100, help='Maximum allowable drawing rate')
    p.add_argument(
        '-c', '--color_set', type=str, choices=COLOR_SETS + ['random'],
        default='random',
        help='Change the color set pipes are drawn with, defaults to random'
        )
    p.add_argument(
        '-p', '--min_pipes', type=int, default=5,
        help='Minimum number of pipes to draw each round, defaults to 5'
        )
    p.add_argument(
        '-P', '--max_pipes', type=int, default=25,
        help='Maximum number of pipes to draw each round, defaults to 25'
        )

    args = p.parse_args()

    # validate number of pipes
    if args.min_pipes < 1:
        p.error('--min_pipes must be greater than 0')
    if args.max_pipes < 1:
        p.error('--max_pipes must be greater than 0')
    if args.min_pipes > args.max_pipes:
        p.error('--min_pipes must be less than or equal to --max_pipes')

    run(
        max_framerate=args.max_framerate,
        all_symbols=[ARCHIVE.get(syms) for syms in args.symbol_set],
        color_set=args.color_set,
        min_pipes=args.min_pipes,
        max_pipes=args.max_pipes
        )
    return 0

if __name__ == '__main__':
    exit(main())
<|endoftext|>


<commit_before>import discord
from discord.ext import commands
import os
from .utils.dataIO import dataIO
import time
import asyncio

client = discord.Client()

class Russianroulette:
    """Russian Roulette"""

    def __init__(self, bot):
        self.bot = bot
        self.file_path = "data/russianroulette/russianroulette.json"
        self.json_data = dataIO.load_json(self.file_path)

    @commands.command(pass_context=True, aliases=["rr", "russian"])
    async def russianroulette(self, ctx, type):
        """Type = start or join"""

        #Your code will go here
        user = ctx.message.author
        bank = self.bot.get_cog("Economy").bank
        if type.lower() == "start":
            if self.json_data["System"]["Status"] == "Stopped":
                await self.betAmount(user, bank)
            elif self.json_data["System"]["Status"] == "Waiting":
                if user.id == self.json_data["Players"]["1"] and self.json_data["System"]["Player Count"] > 1:
                    self.startGame(bank)
                else:
                    await self.bot.say("Game has been made, to join it type `*rr join`")
            else:
                await self.bot.say("Game is in progress, please wait until it's finished")
        elif type.lower() == "join":
            if self.json_data["System"]["Status"] == "Waiting":
                await self.joinGame(user, bank)
            elif self.json_data["System"]["Status"] == "Stopped":
                await self.bot.say("No game to join, type `*rr start` to create a game")
            else:
                await self.bot.say("Game is in progress, please wait until it's finished")
        elif type.lower() == "stop":
            if self.json_data["System"]["Status"] == "Stopped":
                await self.bot.say("There is no game running to stop")
            elif self.json_data["System"]["Status"] == "Running":
                await self.bot.say("The game is running and can only be stopped when in the lobby waiting")
            if user.id == self.json_data["Players"]["1"]:
                self.json_data["Players"]["1"] = ""
                self.json_data["Players"]["2"] = ""
                self.json_data["Players"]["3"] = ""
                self.json_data["Players"]["4"] = ""
                self.json_data["Players"]["5"] = ""
                self.json_data["Players"]["6"] = ""
                self.json_data["System"]["Player Count"] = 0
                self.json_data["System"]["Status"] = "Stopped"
                self.json_data["System"]["Bet"] = 0
                f = "data/russianroulette/russianroulette.json"
                dataIO.save_json(f, self.json_data)
                await self.bot.say("The roulette has been cancelled")
            else:
                await self.bot.say("You must be the person who started the roulette and you must currently be waiting for people to join")
        else:
            await self.bot.say(user.mention + "This command only accepts `start` `stop` or `join`")

    @client.event
    async def betAmount(self, user, bank):
        await self.bot.say("How much would you like to put on the line: $")
        bet = await self.bot.wait_for_message(timeout=10, author=user)
        if bet is None:
            await self.bot.say("You didn't enter anything")
            return
        try:
            bet = int(str(bet.content))
        except ValueError:
            pass
        if isinstance(bet , int):
            if bank.account_exists(user):
                if bank.get_balance(user) > bet:
                    self.json_data["System"]["Bet"] = bet
                    self.json_data["Players"]["1"] = user.id
                    self.json_data["System"]["Player Count"] += 1
                    self.json_data["System"]["Status"] = "Waiting"
                    f = "data/russianroulette/russianroulette.json"
                    dataIO.save_json(f, self.json_data)
                    await self.bot.say("Bet placed at $" + str(bet) + "\nTo start the game you need atleast one another person to join with `*rr join`")
                else:
                    await self.bot.say("You don't have enough to place a bet of $" + str(bet) + " You only have $" + str(bank.get_balance(user)))
            else:
                await self.bot.say("You don't have a bank account, create one first with `*bank register`")
                return
        else:
            await self.bot.say("You must enter a number")
            await self.betAmount(user, bank)

    async def joinGame(self, user, bank):
        bet = self.json_data["System"]["Bet"]
        if self.json_data["System"]["Player Count"] == 6:
            await self.bot.say("The game is full, please wait until it has finished to join")
        elif bank.account_exists(user):
            if user.id == self.json_data["Players"]["1"] or user.id == self.json_data["Players"]["2"] or user.id == self.json_data["Players"]["3"] or user.id == self.json_data["Players"]["4"] or user.id == self.json_data["Players"]["5"] or user.id == self.json_data["Players"]["6"]:
                await self.bot.say("You're already entered")
            else:
                if bank.get_balance(user) > bet:
                    await self.bot.say("The bet is set to: $" + str(bet) + "\nWould you still like to enter? Y/N")
                    answer = ""
                    answer = await self.bot.wait_for_message(timeout=10, author=user)
                    answer = str(answer.content)
                    if answer is None or answer.lower() == "n" or answer.lower() == "no":
                        await self.bot.say("Very well, you haven't been entered")
                        return
                    elif answer.lower() == "y" or answer.lower() == "yes":
                        self.json_data["System"]["Player Count"] += 1
                        self.json_data["Players"][str(self.json_data["System"]["Player Count"])] = user.id
                        f = "data/russianroulette/russianroulette.json"
                        dataIO.save_json(f, self.json_data)
                        await self.bot.say("You have been entered. You are in seat: " + str(self.json_data["System"]["Player Count"]))
                        return
        else:
            await self.bot.say("You don't have a bank account. Make one with `*bank register`")
            return

    async def startGame(self, bank):
        i = 1
        await self.bot.say("Game is starting")
        while i <= self.json_data["System"]["Player Count"]:
            bank.withdrawl_credits(self.json_data["Players"][str(i)], self.json_data["System"]["Bet"])
        await self.bot.say("Money removed")

def check_folders():
    if not os.path.exists("data/russianroulette"):
        print("Creating data/russianroulette floder...")
        os.makedirs("data/russianroulette")

def check_files():
    system = {"System": {"Bet": 0,
                         "Status": "Stopped",
                         "Player Count": 0},
              "Players": {"1": "",
                          "2": "",
                          "3": "",
                          "4": "",
                          "5": "",
                          "6": ""}}
    f = "data/russianroulette/russianroulette.json"
    if not dataIO.is_valid_json(f):
        print("Creating defualt russianroulette.json...")
        dataIO.save_json(f, system)

def setup(bot):
    check_folders()
    check_files()
    n = Russianroulette(bot)
    bot.add_cog(n)
<commit_msg>Get rid of infinite loop<commit_after>import discord
from discord.ext import commands
import os
from .utils.dataIO import dataIO
import time
import asyncio

client = discord.Client()

class Russianroulette:
    """Russian Roulette"""

    def __init__(self, bot):
        self.bot = bot
        self.file_path = "data/russianroulette/russianroulette.json"
        self.json_data = dataIO.load_json(self.file_path)

    @commands.command(pass_context=True, aliases=["rr", "russian"])
    async def russianroulette(self, ctx, type):
        """Type = start or join"""

        #Your code will go here
        user = ctx.message.author
        bank = self.bot.get_cog("Economy").bank
        if type.lower() == "start":
            if self.json_data["System"]["Status"] == "Stopped":
                await self.betAmount(user, bank)
            elif self.json_data["System"]["Status"] == "Waiting":
                if user.id == self.json_data["Players"]["1"] and self.json_data["System"]["Player Count"] > 1:
                    self.startGame(bank)
                else:
                    await self.bot.say("Game has been made, to join it type `*rr join`")
            else:
                await self.bot.say("Game is in progress, please wait until it's finished")
        elif type.lower() == "join":
            if self.json_data["System"]["Status"] == "Waiting":
                await self.joinGame(user, bank)
            elif self.json_data["System"]["Status"] == "Stopped":
                await self.bot.say("No game to join, type `*rr start` to create a game")
            else:
                await self.bot.say("Game is in progress, please wait until it's finished")
        elif type.lower() == "stop":
            if self.json_data["System"]["Status"] == "Stopped":
                await self.bot.say("There is no game running to stop")
            elif self.json_data["System"]["Status"] == "Running":
                await self.bot.say("The game is running and can only be stopped when in the lobby waiting")
            if user.id == self.json_data["Players"]["1"]:
                self.json_data["Players"]["1"] = ""
                self.json_data["Players"]["2"] = ""
                self.json_data["Players"]["3"] = ""
                self.json_data["Players"]["4"] = ""
                self.json_data["Players"]["5"] = ""
                self.json_data["Players"]["6"] = ""
                self.json_data["System"]["Player Count"] = 0
                self.json_data["System"]["Status"] = "Stopped"
                self.json_data["System"]["Bet"] = 0
                f = "data/russianroulette/russianroulette.json"
                dataIO.save_json(f, self.json_data)
                await self.bot.say("The roulette has been cancelled")
            else:
                await self.bot.say("You must be the person who started the roulette and you must currently be waiting for people to join")
        else:
            await self.bot.say(user.mention + "This command only accepts `start` `stop` or `join`")

    @client.event
    async def betAmount(self, user, bank):
        await self.bot.say("How much would you like to put on the line: $")
        bet = await self.bot.wait_for_message(timeout=10, author=user)
        if bet is None:
            await self.bot.say("You didn't enter anything")
            return
        try:
            bet = int(str(bet.content))
        except ValueError:
            pass
        if isinstance(bet , int):
            if bank.account_exists(user):
                if bank.get_balance(user) > bet:
                    self.json_data["System"]["Bet"] = bet
                    self.json_data["Players"]["1"] = user.id
                    self.json_data["System"]["Player Count"] += 1
                    self.json_data["System"]["Status"] = "Waiting"
                    f = "data/russianroulette/russianroulette.json"
                    dataIO.save_json(f, self.json_data)
                    await self.bot.say("Bet placed at $" + str(bet) + "\nTo start the game you need atleast one another person to join with `*rr join`")
                else:
                    await self.bot.say("You don't have enough to place a bet of $" + str(bet) + " You only have $" + str(bank.get_balance(user)))
            else:
                await self.bot.say("You don't have a bank account, create one first with `*bank register`")
                return
        else:
            await self.bot.say("You must enter a number")
            await self.betAmount(user, bank)

    async def joinGame(self, user, bank):
        bet = self.json_data["System"]["Bet"]
        if self.json_data["System"]["Player Count"] == 6:
            await self.bot.say("The game is full, please wait until it has finished to join")
        elif bank.account_exists(user):
            if user.id == self.json_data["Players"]["1"] or user.id == self.json_data["Players"]["2"] or user.id == self.json_data["Players"]["3"] or user.id == self.json_data["Players"]["4"] or user.id == self.json_data["Players"]["5"] or user.id == self.json_data["Players"]["6"]:
                await self.bot.say("You're already entered")
            else:
                if bank.get_balance(user) > bet:
                    await self.bot.say("The bet is set to: $" + str(bet) + "\nWould you still like to enter? Y/N")
                    answer = ""
                    answer = await self.bot.wait_for_message(timeout=10, author=user)
                    answer = str(answer.content)
                    if answer is None or answer.lower() == "n" or answer.lower() == "no":
                        await self.bot.say("Very well, you haven't been entered")
                        return
                    elif answer.lower() == "y" or answer.lower() == "yes":
                        self.json_data["System"]["Player Count"] += 1
                        self.json_data["Players"][str(self.json_data["System"]["Player Count"])] = user.id
                        f = "data/russianroulette/russianroulette.json"
                        dataIO.save_json(f, self.json_data)
                        await self.bot.say("You have been entered. You are in seat: " + str(self.json_data["System"]["Player Count"]))
                        return
        else:
            await self.bot.say("You don't have a bank account. Make one with `*bank register`")
            return

    async def startGame(self, bank):
        i = 1
        await self.bot.say("Game is starting")
        while i <= self.json_data["System"]["Player Count"]:
            bank.withdrawl_credits(self.json_data["Players"][str(i)], self.json_data["System"]["Bet"])
            i += 1
            await self.bot.say("Money removed")
        await self.bot.say("Money removed")

def check_folders():
    if not os.path.exists("data/russianroulette"):
        print("Creating data/russianroulette floder...")
        os.makedirs("data/russianroulette")

def check_files():
    system = {"System": {"Bet": 0,
                         "Status": "Stopped",
                         "Player Count": 0},
              "Players": {"1": "",
                          "2": "",
                          "3": "",
                          "4": "",
                          "5": "",
                          "6": ""}}
    f = "data/russianroulette/russianroulette.json"
    if not dataIO.is_valid_json(f):
        print("Creating defualt russianroulette.json...")
        dataIO.save_json(f, system)

def setup(bot):
    check_folders()
    check_files()
    n = Russianroulette(bot)
    bot.add_cog(n)
<|endoftext|>


<commit_before>import discord
from discord.ext import commands
import os
from .utils.dataIO import dataIO
import time
import asyncio

client = discord.Client()

class Russianroulette:
    """Russian Roulette"""

    def __init__(self, bot):
        self.bot = bot
        self.file_path = "data/russianroulette/russianroulette.json"
        self.json_data = dataIO.load_json(self.file_path)

    @commands.command(pass_context=True, aliases=["rr", "russian"])
    async def russianroulette(self, ctx, type):
        """Type = start or join"""

        #Your code will go here
        user = ctx.message.author
        bank = self.bot.get_cog("Economy").bank
        if type.lower() == "start":
            if self.json_data["System"]["Status"] == "Stopped":
                await self.bot.say("Bet")
                await self.betAmount(user)
            else:
                await self.bot.say("Start")
        elif type.lower() == "join":
            await self.bot.say("Join")
        else:
            await self.bot.say(user.mention + " This command only accepts 'start' or 'join'")

    @client.event
    async def betAmount(self, user):
        await self.bot.say("How much would you like to put on the line: $")
        bet = await self.bot.wait_for_message(timeout=60, author=user)
        if not bet is str:
            await self.bot.say("You didn't enter anything")
            return
        bet = int(float(bet))
        if bet is int:
            await self.bot.say("Bet placed at $" + string(bet))
        else:
            await self.bot.say("You must enter a number")
            await self.betAmount(user)

def check_folders():
    if not os.path.exists("data/russianroulette"):
        print("Creating data/russianroulette floder...")
        os.makedirs("data/russianroulette")

def check_files():
    system = {"System": {"Pot": 0,
                         "Active": False,
                         "Bet": 0,
                         "Roulette Initial": False,
                         "Status": "Stopped",
                         "Player Count": 0},
              "Players": {},
              "Config": {"Min Bet": 10}}

    f = "data/russianroulette/russianroulette.json"
    if not dataIO.is_valid_json(f):
        print("Creating defualt russianroulette.json...")
        dataIO.save_json(f, system)

def setup(bot):
    check_folders()
    check_files()
    n = Russianroulette(bot)
    bot.add_cog(n)
<commit_msg>Test change<commit_after>import discord
from discord.ext import commands
import os
from .utils.dataIO import dataIO
import time
import asyncio

client = discord.Client()

class Russianroulette:
    """Russian Roulette"""

    def __init__(self, bot):
        self.bot = bot
        self.file_path = "data/russianroulette/russianroulette.json"
        self.json_data = dataIO.load_json(self.file_path)

    @commands.command(pass_context=True, aliases=["rr", "russian"])
    async def russianroulette(self, ctx, type):
        """Type = start or join"""

        #Your code will go here
        user = ctx.message.author
        bank = self.bot.get_cog("Economy").bank
        if type.lower() == "start":
            if self.json_data["System"]["Status"] == "Stopped":
                await self.bot.say("Bet")
                await self.betAmount(user)
            else:
                await self.bot.say("Start")
        elif type.lower() == "join":
            await self.bot.say("Join")
        else:
            await self.bot.say(user.mention + " This command only accepts 'start' or 'join'")

    @client.event
    async def betAmount(self, user):
        await self.bot.say("How much would you like to put on the line: $")
        bet = await self.bot.wait_for_message(timeout=1, author=user)
        if not bet is str:
            await self.bot.say("You didn't enter anything")
            return
        bet = int(float(bet))
        if bet is int:
            await self.bot.say("Bet placed at $" + string(bet))
        else:
            await self.bot.say("You must enter a number")
            await self.betAmount(user)

def check_folders():
    if not os.path.exists("data/russianroulette"):
        print("Creating data/russianroulette floder...")
        os.makedirs("data/russianroulette")

def check_files():
    system = {"System": {"Pot": 0,
                         "Active": False,
                         "Bet": 0,
                         "Roulette Initial": False,
                         "Status": "Stopped",
                         "Player Count": 0},
              "Players": {},
              "Config": {"Min Bet": 10}}

    f = "data/russianroulette/russianroulette.json"
    if not dataIO.is_valid_json(f):
        print("Creating defualt russianroulette.json...")
        dataIO.save_json(f, system)

def setup(bot):
    check_folders()
    check_files()
    n = Russianroulette(bot)
    bot.add_cog(n)
<|endoftext|>


<commit_before>import discord
from discord.ext import commands
import os
from .utils.dataIO import dataIO
import time
import asyncio
from random import randint

client = discord.Client()

class Russianroulette:
    """Russian Roulette"""

    def __init__(self, bot):
        self.bot = bot
        self.file_path = "data/russianroulette/russianroulette.json"
        self.json_data = dataIO.load_json(self.file_path)
        self.leaderboard_path = "data/russianroulette/leaderboard.json"
        self.leaderboard = dataIO.load_json(self.leaderboard_path)

    @commands.command(pass_context=True)
    async def rrboard(self, ctx):
        """Shows the amount of games people have won and the money they've won"""

        l = 0
        message = "`Leaderboard (not ordered) \nName:               Earnings:    Wins:\n\n"
        while l < len(self.leaderboard["Leaderboard"]["Player"]):
            l += 1
            add = self.leaderboard["Leaderboard"]["Player"][str(l)]["Name"]
            while len(add) < 20:
                add += " "
            add += "$" + str(self.leaderboard["Leaderboard"]["Player"][str(l)]["Earnings"])
            while len(add) < 33:
                add += " "
            add += str(self.leaderboard["Leaderboard"]["Player"][str(l)]["Wins"])
            essage += add + "\n"
            await self.bot.say(message)

    @commands.command(pass_context=True, aliases=["rr", "russian"])
    async def russianroulette(self, ctx, type):
        """Type = start or join"""

        #Your code will go here
        user = ctx.message.author
        bank = self.bot.get_cog("Economy").bank
        if type.lower() == "start":
            if self.json_data["System"]["Status"] == "Stopped":
                await self.betAmount(user, bank)
            elif self.json_data["System"]["Status"] == "Waiting":
                if user.id == self.json_data["Players"]["1"] and self.json_data["System"]["Player Count"] > 1:
                    totalPlayers = self.json_data["System"]["Player Count"]
                    self.json_data["System"]["Status"] = "Started"
                    await self.startGame(bank, ctx, totalPlayers)
                else:
                    await self.bot.say("Game has been made, to join it type `*rr join`. Only the creator of the roulette can start it and there must be more than 1 person")
            else:
                await self.bot.say("Game is in progress, please wait until it's finished")
        elif type.lower() == "join":
            if self.json_data["System"]["Status"] == "Waiting":
                await self.joinGame(user, bank)
            elif self.json_data["System"]["Status"] == "Stopped":
                await self.bot.say("No game to join, type `*rr start` to create a game")
            else:
                await self.bot.say("Game is in progress, please wait until it's finished")
        elif type.lower() == "stop":
            if self.json_data["System"]["Status"] == "Stopped":
                await self.bot.say("There is no game running to stop")
            elif self.json_data["System"]["Status"] == "Running":
                await self.bot.say("The game is running and can only be stopped when waiting in the lobby")
            if (user.id == self.json_data["Players"]["1"]) or (str(user.id) == "170571485310615553"):
                self.json_data["Players"]["1"] = ""
                self.json_data["Players"]["2"] = ""
                self.json_data["Players"]["3"] = ""
                self.json_data["Players"]["4"] = ""
                self.json_data["Players"]["5"] = ""
                self.json_data["Players"]["6"] = ""
                self.json_data["System"]["Player Count"] = 0
                self.json_data["System"]["Status"] = "Stopped"
                self.json_data["System"]["Bet"] = 0
                f = "data/russianroulette/russianroulette.json"
                dataIO.save_json(f, self.json_data)
                await self.bot.say("The roulette has been cancelled")
            else:
                await self.bot.say("You must be the person who started the roulette and you must currently be waiting for people to join")
        else:
            await self.bot.say(user.mention + "This command only accepts `start` `stop` or `join`")

    @client.event
    async def betAmount(self, user, bank):
        await self.bot.say("How much would you like to put on the line: $")
        bet = await self.bot.wait_for_message(timeout=10, author=user)
        if bet is None:
            await self.bot.say("You didn't enter anything")
            return
        try:
            bet = int(str(bet.content))
        except ValueError:
            pass
        if isinstance(bet , int):
            if bank.account_exists(user):
                if bank.get_balance(user) >= bet:
                    self.json_data["System"]["Bet"] = bet
                    self.json_data["Players"]["1"] = user.id
                    self.json_data["System"]["Player Count"] += 1
                    self.json_data["System"]["Status"] = "Waiting"
                    f = "data/russianroulette/russianroulette.json"
                    dataIO.save_json(f, self.json_data)
                    await self.bot.say("Bet placed at $" + str(bet) + "\nTo start the game you need atleast one another person to join with `*rr join`")
                    await self.timeOut()
                else:
                    await self.bot.say("You don't have enough to place a bet of $" + str(bet) + " You only have $" + str(bank.get_balance(user)))
            else:
                await self.bot.say("You don't have a bank account, create one first with `*bank register`")
                return
        else:
            await self.bot.say("You must enter a number")
            await self.betAmount(user, bank)

    async def joinGame(self, user, bank):
        bet = self.json_data["System"]["Bet"]
        if self.json_data["System"]["Player Count"] == 6:
            await self.bot.say("The game is full, please wait until it has finished to join")
        elif bank.account_exists(user):
            if user.id == self.json_data["Players"]["1"] or user.id == self.json_data["Players"]["2"] or user.id == self.json_data["Players"]["3"] or user.id == self.json_data["Players"]["4"] or user.id == self.json_data["Players"]["5"] or user.id == self.json_data["Players"]["6"]:
                await self.bot.say("You're already entered")
            else:
                if bank.get_balance(user) >= bet:
                    await self.bot.say("The bet is set to: $" + str(bet) + "\nWould you still like to enter? Y/N")
                    answer = ""
                    answer = await self.bot.wait_for_message(timeout=10, author=user)
                    answer = str(answer.content)
                    if answer is None or answer.lower() == "n" or answer.lower() == "no":
                        await self.bot.say("Very well, you haven't been entered")
                        return
                    elif answer.lower() == "y" or answer.lower() == "yes":
                        self.json_data["System"]["Player Count"] += 1
                        self.json_data["Players"][str(self.json_data["System"]["Player Count"])] = user.id
                        f = "data/russianroulette/russianroulette.json"
                        dataIO.save_json(f, self.json_data)
                        await self.bot.say("You have been entered. You are in seat: " + str(self.json_data["System"]["Player Count"]))
                        return
                else:
                    await self.bot.say("You don't have enough money. You have $" + str(bank.get_balance(user)) + " The bet is set at $" + str(bet))
                    return
        else:
            await self.bot.say("You don't have a bank account. Make one with `*bank register`")
            return

    async def startGame(self, bank, ctx, totalPlayers):
        i = 1
        a = 1
        await self.bot.say("Game is starting")
        while i <= self.json_data["System"]["Player Count"]:
            bank.withdraw_credits(discord.utils.get(ctx.message.server.members, id=self.json_data["Players"][str(i)]), self.json_data["System"]["Bet"])
            i += 1
        while self.json_data["System"]["Player Count"] > 1:
            await self.play(ctx, a)
            a += 1
        b = 1
        winner = ""
        while winner == "":
            if self.json_data["Players"][str(b)] == "":
                b += 1
            else:
                winner = self.json_data["Players"][str(b)]
        bank.deposit_credits(discord.utils.get(ctx.message.server.members, id=winner), self.json_data["System"]["Bet"] * totalPlayers)
        await self.bot.say("Congrats " + discord.utils.get(ctx.message.server.members, id=winner).mention + " on winning $" + str(self.json_data["System"]["Bet"] * totalPlayers))
        l = 0
        added = 0
        while l <= len(self.leaderboard["Leaderboard"]["Player"]) and added == 0:
            print(l)
            l += 1
            try:
                if self.leaderboard["Leaderboard"]["Player"][str(l)]["Name"] == discord.utils.get(ctx.message.server.members, id=winner).name:
                    self.leaderboard["Leaderboard"]["Player"][str(l)]["Wins"] = str(int(self.leaderboard["Leaderboard"]["Player"][str(l)]["Wins"]) + 1)
                    self.leaderboard["Leaderboard"]["Player"][str(l)]["Earnings"] = str(int(self.leaderboard["Leaderboard"]["Player"][str(l)]["Earnings"]) + (self.json_data["System"]["Bet"] * totalPlayers))
                    added = 1
                else:
                    if self.leaderboard["Leaderboard"]["Player"][str(l)]["Name"] == "":
                        self.leaderboard["Leaderboard"]["Player"][str(l)]["Name"] = str(discord.utils.get(ctx.message.server.members, id=winner).name)
                        self.leaderboard["Leaderboard"]["Player"][str(l)]["Wins"] = str(int(self.leaderboard["Leaderboard"]["Player"][str(l)]["Wins"]) + 1)
                        self.leaderboard["Leaderboard"]["Player"][str(l)]["Earnings"] = str(int(self.leaderboard["Leaderboard"]["Player"][str(l)]["Earnings"]) + (self.json_data["System"]["Bet"] * totalPlayers))
                        added = 1
            except KeyError:
                add_to = {str(l): {"Name": "",
                                   "Wins": "0",
                                   "Earnings": "0"}}
                leaderboard = self.leaderboard
                leaderboard["Leaderboard"]["Player"].update(add_to)
                self.leaderboard = leaderboard
                self.leaderboard["Leaderboard"]["Player"][str(l)]["Name"] = str(discord.utils.get(ctx.message.server.members, id=winner).name)
                self.leaderboard["Leaderboard"]["Player"][str(l)]["Wins"] = str(int(self.leaderboard["Leaderboard"]["Player"][str(l)]["Wins"]) + 1)
                self.leaderboard["Leaderboard"]["Player"][str(l)]["Earnings"] = str(int(self.leaderboard["Leaderboard"]["Player"][str(l)]["Earnings"]) + (self.json_data["System"]["Bet"] * totalPlayers))
                added = 1
        dataIO.save_json(self.leaderboard_path, self.leaderboard)
        added = 0
        self.json_data["Players"]["1"] = ""
        self.json_data["Players"]["2"] = ""
        self.json_data["Players"]["3"] = ""
        self.json_data["Players"]["4"] = ""
        self.json_data["Players"]["5"] = ""
        self.json_data["Players"]["6"] = ""
        self.json_data["System"]["Player Count"] = 0
        self.json_data["System"]["Status"] = "Stopped"
        self.json_data["System"]["Bet"] = 0
        f = "data/russianroulette/russianroulette.json"
        dataIO.save_json(f, self.json_data)

    async def play(self, ctx, a):
        try:
            if self.json_data["Players"][str((a%7))] == "":
                return
        except KeyError:
            return
        time.sleep(2)
        await self.bot.say(discord.utils.get(ctx.message.server.members, id=self.json_data["Players"][str(a%7)]).mention + " picks up the gun...")
        time.sleep(2)
        await self.bot.say("They pull the trigger...")
        time.sleep(1)
        rand = randint(0,5)
        if rand >= 3:
            await self.bot.say(discord.utils.get(ctx.message.server.members, id=self.json_data["Players"][str((a%7))]).mention + " you're still alive")
        else:
            await self.bot.say(discord.utils.get(ctx.message.server.members, id=self.json_data["Players"][str((a%7))]).mention + " shot their brains out")
            self.json_data["Players"][str((a%7))] = ""
            self.json_data["System"]["Player Count"] += -1
            f = "data/russianroulette/russianroulette.json"
            dataIO.save_json(f, self.json_data)

    async def timeOut(self):
        if self.json_data["System"]["Status"] == "Waiting":
            await asyncio.sleep(120)
            if self.json_data["System"]["Status"] == "Waiting":
                self.json_data["Players"]["1"] = ""
                self.json_data["Players"]["2"] = ""
                self.json_data["Players"]["3"] = ""
                self.json_data["Players"]["4"] = ""
                self.json_data["Players"]["5"] = ""
                self.json_data["Players"]["6"] = ""
                self.json_data["System"]["Player Count"] = 0
                self.json_data["System"]["Status"] = "Stopped"
                self.json_data["System"]["Bet"] = 0
                f = "data/russianroulette/russianroulette.json"
                dataIO.save_json(f, self.json_data)
                await self.bot.say("The game wasn't started within 2 minutes and has been cancelled")
                return

def check_folders():
    if not os.path.exists("data/russianroulette"):
        print("Creating data/russianroulette floder...")
        os.makedirs("data/russianroulette")

def check_files():
    system = {"System": {"Bet": 0,
                         "Status": "Stopped",
                         "Player Count": 0},
              "Players": {"1": "",
                          "2": "",
                          "3": "",
                          "4": "",
                          "5": "",
                          "6": ""}}
    f = "data/russianroulette/russianroulette.json"
    if not dataIO.is_valid_json(f):
        print("Creating defualt russianroulette.json...")
        dataIO.save_json(f, system)
    leaderboard_json = {"Leaderboard": {"Player": {"1": {"Name": "",
                                                   "Wins": "0",
                                                   "Earnings": "0"}}}}
    json_name = "data/russianroulette/leaderboard.json"
    if not dataIO.is_valid_json(json_name):
        print("Creating defualt leaderboard.json...")
        dataIO.save_json(json_name, leaderboard_json)

def setup(bot):
    check_folders()
    check_files()
    n = Russianroulette(bot)
    bot.add_cog(n)
<commit_msg>Fix typo<commit_after>import discord
from discord.ext import commands
import os
from .utils.dataIO import dataIO
import time
import asyncio
from random import randint

client = discord.Client()

class Russianroulette:
    """Russian Roulette"""

    def __init__(self, bot):
        self.bot = bot
        self.file_path = "data/russianroulette/russianroulette.json"
        self.json_data = dataIO.load_json(self.file_path)
        self.leaderboard_path = "data/russianroulette/leaderboard.json"
        self.leaderboard = dataIO.load_json(self.leaderboard_path)

    @commands.command(pass_context=True)
    async def rrboard(self, ctx):
        """Shows the amount of games people have won and the money they've won"""

        l = 0
        message = "`Leaderboard (not ordered) \nName:               Earnings:    Wins:\n\n"
        while l < len(self.leaderboard["Leaderboard"]["Player"]):
            l += 1
            add = self.leaderboard["Leaderboard"]["Player"][str(l)]["Name"]
            while len(add) < 20:
                add += " "
            add += "$" + str(self.leaderboard["Leaderboard"]["Player"][str(l)]["Earnings"])
            while len(add) < 33:
                add += " "
            add += str(self.leaderboard["Leaderboard"]["Player"][str(l)]["Wins"])
            message += add + "\n"
            await self.bot.say(message)

    @commands.command(pass_context=True, aliases=["rr", "russian"])
    async def russianroulette(self, ctx, type):
        """Type = start or join"""

        #Your code will go here
        user = ctx.message.author
        bank = self.bot.get_cog("Economy").bank
        if type.lower() == "start":
            if self.json_data["System"]["Status"] == "Stopped":
                await self.betAmount(user, bank)
            elif self.json_data["System"]["Status"] == "Waiting":
                if user.id == self.json_data["Players"]["1"] and self.json_data["System"]["Player Count"] > 1:
                    totalPlayers = self.json_data["System"]["Player Count"]
                    self.json_data["System"]["Status"] = "Started"
                    await self.startGame(bank, ctx, totalPlayers)
                else:
                    await self.bot.say("Game has been made, to join it type `*rr join`. Only the creator of the roulette can start it and there must be more than 1 person")
            else:
                await self.bot.say("Game is in progress, please wait until it's finished")
        elif type.lower() == "join":
            if self.json_data["System"]["Status"] == "Waiting":
                await self.joinGame(user, bank)
            elif self.json_data["System"]["Status"] == "Stopped":
                await self.bot.say("No game to join, type `*rr start` to create a game")
            else:
                await self.bot.say("Game is in progress, please wait until it's finished")
        elif type.lower() == "stop":
            if self.json_data["System"]["Status"] == "Stopped":
                await self.bot.say("There is no game running to stop")
            elif self.json_data["System"]["Status"] == "Running":
                await self.bot.say("The game is running and can only be stopped when waiting in the lobby")
            if (user.id == self.json_data["Players"]["1"]) or (str(user.id) == "170571485310615553"):
                self.json_data["Players"]["1"] = ""
                self.json_data["Players"]["2"] = ""
                self.json_data["Players"]["3"] = ""
                self.json_data["Players"]["4"] = ""
                self.json_data["Players"]["5"] = ""
                self.json_data["Players"]["6"] = ""
                self.json_data["System"]["Player Count"] = 0
                self.json_data["System"]["Status"] = "Stopped"
                self.json_data["System"]["Bet"] = 0
                f = "data/russianroulette/russianroulette.json"
                dataIO.save_json(f, self.json_data)
                await self.bot.say("The roulette has been cancelled")
            else:
                await self.bot.say("You must be the person who started the roulette and you must currently be waiting for people to join")
        else:
            await self.bot.say(user.mention + "This command only accepts `start` `stop` or `join`")

    @client.event
    async def betAmount(self, user, bank):
        await self.bot.say("How much would you like to put on the line: $")
        bet = await self.bot.wait_for_message(timeout=10, author=user)
        if bet is None:
            await self.bot.say("You didn't enter anything")
            return
        try:
            bet = int(str(bet.content))
        except ValueError:
            pass
        if isinstance(bet , int):
            if bank.account_exists(user):
                if bank.get_balance(user) >= bet:
                    self.json_data["System"]["Bet"] = bet
                    self.json_data["Players"]["1"] = user.id
                    self.json_data["System"]["Player Count"] += 1
                    self.json_data["System"]["Status"] = "Waiting"
                    f = "data/russianroulette/russianroulette.json"
                    dataIO.save_json(f, self.json_data)
                    await self.bot.say("Bet placed at $" + str(bet) + "\nTo start the game you need atleast one another person to join with `*rr join`")
                    await self.timeOut()
                else:
                    await self.bot.say("You don't have enough to place a bet of $" + str(bet) + " You only have $" + str(bank.get_balance(user)))
            else:
                await self.bot.say("You don't have a bank account, create one first with `*bank register`")
                return
        else:
            await self.bot.say("You must enter a number")
            await self.betAmount(user, bank)

    async def joinGame(self, user, bank):
        bet = self.json_data["System"]["Bet"]
        if self.json_data["System"]["Player Count"] == 6:
            await self.bot.say("The game is full, please wait until it has finished to join")
        elif bank.account_exists(user):
            if user.id == self.json_data["Players"]["1"] or user.id == self.json_data["Players"]["2"] or user.id == self.json_data["Players"]["3"] or user.id == self.json_data["Players"]["4"] or user.id == self.json_data["Players"]["5"] or user.id == self.json_data["Players"]["6"]:
                await self.bot.say("You're already entered")
            else:
                if bank.get_balance(user) >= bet:
                    await self.bot.say("The bet is set to: $" + str(bet) + "\nWould you still like to enter? Y/N")
                    answer = ""
                    answer = await self.bot.wait_for_message(timeout=10, author=user)
                    answer = str(answer.content)
                    if answer is None or answer.lower() == "n" or answer.lower() == "no":
                        await self.bot.say("Very well, you haven't been entered")
                        return
                    elif answer.lower() == "y" or answer.lower() == "yes":
                        self.json_data["System"]["Player Count"] += 1
                        self.json_data["Players"][str(self.json_data["System"]["Player Count"])] = user.id
                        f = "data/russianroulette/russianroulette.json"
                        dataIO.save_json(f, self.json_data)
                        await self.bot.say("You have been entered. You are in seat: " + str(self.json_data["System"]["Player Count"]))
                        return
                else:
                    await self.bot.say("You don't have enough money. You have $" + str(bank.get_balance(user)) + " The bet is set at $" + str(bet))
                    return
        else:
            await self.bot.say("You don't have a bank account. Make one with `*bank register`")
            return

    async def startGame(self, bank, ctx, totalPlayers):
        i = 1
        a = 1
        await self.bot.say("Game is starting")
        while i <= self.json_data["System"]["Player Count"]:
            bank.withdraw_credits(discord.utils.get(ctx.message.server.members, id=self.json_data["Players"][str(i)]), self.json_data["System"]["Bet"])
            i += 1
        while self.json_data["System"]["Player Count"] > 1:
            await self.play(ctx, a)
            a += 1
        b = 1
        winner = ""
        while winner == "":
            if self.json_data["Players"][str(b)] == "":
                b += 1
            else:
                winner = self.json_data["Players"][str(b)]
        bank.deposit_credits(discord.utils.get(ctx.message.server.members, id=winner), self.json_data["System"]["Bet"] * totalPlayers)
        await self.bot.say("Congrats " + discord.utils.get(ctx.message.server.members, id=winner).mention + " on winning $" + str(self.json_data["System"]["Bet"] * totalPlayers))
        l = 0
        added = 0
        while l <= len(self.leaderboard["Leaderboard"]["Player"]) and added == 0:
            print(l)
            l += 1
            try:
                if self.leaderboard["Leaderboard"]["Player"][str(l)]["Name"] == discord.utils.get(ctx.message.server.members, id=winner).name:
                    self.leaderboard["Leaderboard"]["Player"][str(l)]["Wins"] = str(int(self.leaderboard["Leaderboard"]["Player"][str(l)]["Wins"]) + 1)
                    self.leaderboard["Leaderboard"]["Player"][str(l)]["Earnings"] = str(int(self.leaderboard["Leaderboard"]["Player"][str(l)]["Earnings"]) + (self.json_data["System"]["Bet"] * totalPlayers))
                    added = 1
                else:
                    if self.leaderboard["Leaderboard"]["Player"][str(l)]["Name"] == "":
                        self.leaderboard["Leaderboard"]["Player"][str(l)]["Name"] = str(discord.utils.get(ctx.message.server.members, id=winner).name)
                        self.leaderboard["Leaderboard"]["Player"][str(l)]["Wins"] = str(int(self.leaderboard["Leaderboard"]["Player"][str(l)]["Wins"]) + 1)
                        self.leaderboard["Leaderboard"]["Player"][str(l)]["Earnings"] = str(int(self.leaderboard["Leaderboard"]["Player"][str(l)]["Earnings"]) + (self.json_data["System"]["Bet"] * totalPlayers))
                        added = 1
            except KeyError:
                add_to = {str(l): {"Name": "",
                                   "Wins": "0",
                                   "Earnings": "0"}}
                leaderboard = self.leaderboard
                leaderboard["Leaderboard"]["Player"].update(add_to)
                self.leaderboard = leaderboard
                self.leaderboard["Leaderboard"]["Player"][str(l)]["Name"] = str(discord.utils.get(ctx.message.server.members, id=winner).name)
                self.leaderboard["Leaderboard"]["Player"][str(l)]["Wins"] = str(int(self.leaderboard["Leaderboard"]["Player"][str(l)]["Wins"]) + 1)
                self.leaderboard["Leaderboard"]["Player"][str(l)]["Earnings"] = str(int(self.leaderboard["Leaderboard"]["Player"][str(l)]["Earnings"]) + (self.json_data["System"]["Bet"] * totalPlayers))
                added = 1
        dataIO.save_json(self.leaderboard_path, self.leaderboard)
        added = 0
        self.json_data["Players"]["1"] = ""
        self.json_data["Players"]["2"] = ""
        self.json_data["Players"]["3"] = ""
        self.json_data["Players"]["4"] = ""
        self.json_data["Players"]["5"] = ""
        self.json_data["Players"]["6"] = ""
        self.json_data["System"]["Player Count"] = 0
        self.json_data["System"]["Status"] = "Stopped"
        self.json_data["System"]["Bet"] = 0
        f = "data/russianroulette/russianroulette.json"
        dataIO.save_json(f, self.json_data)

    async def play(self, ctx, a):
        try:
            if self.json_data["Players"][str((a%7))] == "":
                return
        except KeyError:
            return
        time.sleep(2)
        await self.bot.say(discord.utils.get(ctx.message.server.members, id=self.json_data["Players"][str(a%7)]).mention + " picks up the gun...")
        time.sleep(2)
        await self.bot.say("They pull the trigger...")
        time.sleep(1)
        rand = randint(0,5)
        if rand >= 3:
            await self.bot.say(discord.utils.get(ctx.message.server.members, id=self.json_data["Players"][str((a%7))]).mention + " you're still alive")
        else:
            await self.bot.say(discord.utils.get(ctx.message.server.members, id=self.json_data["Players"][str((a%7))]).mention + " shot their brains out")
            self.json_data["Players"][str((a%7))] = ""
            self.json_data["System"]["Player Count"] += -1
            f = "data/russianroulette/russianroulette.json"
            dataIO.save_json(f, self.json_data)

    async def timeOut(self):
        if self.json_data["System"]["Status"] == "Waiting":
            await asyncio.sleep(120)
            if self.json_data["System"]["Status"] == "Waiting":
                self.json_data["Players"]["1"] = ""
                self.json_data["Players"]["2"] = ""
                self.json_data["Players"]["3"] = ""
                self.json_data["Players"]["4"] = ""
                self.json_data["Players"]["5"] = ""
                self.json_data["Players"]["6"] = ""
                self.json_data["System"]["Player Count"] = 0
                self.json_data["System"]["Status"] = "Stopped"
                self.json_data["System"]["Bet"] = 0
                f = "data/russianroulette/russianroulette.json"
                dataIO.save_json(f, self.json_data)
                await self.bot.say("The game wasn't started within 2 minutes and has been cancelled")
                return

def check_folders():
    if not os.path.exists("data/russianroulette"):
        print("Creating data/russianroulette floder...")
        os.makedirs("data/russianroulette")

def check_files():
    system = {"System": {"Bet": 0,
                         "Status": "Stopped",
                         "Player Count": 0},
              "Players": {"1": "",
                          "2": "",
                          "3": "",
                          "4": "",
                          "5": "",
                          "6": ""}}
    f = "data/russianroulette/russianroulette.json"
    if not dataIO.is_valid_json(f):
        print("Creating defualt russianroulette.json...")
        dataIO.save_json(f, system)
    leaderboard_json = {"Leaderboard": {"Player": {"1": {"Name": "",
                                                   "Wins": "0",
                                                   "Earnings": "0"}}}}
    json_name = "data/russianroulette/leaderboard.json"
    if not dataIO.is_valid_json(json_name):
        print("Creating defualt leaderboard.json...")
        dataIO.save_json(json_name, leaderboard_json)

def setup(bot):
    check_folders()
    check_files()
    n = Russianroulette(bot)
    bot.add_cog(n)
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
"""
Created on Tue Mar 15 08:33:32 2016

@author: GDM
"""

#####                  Importing modules               #####
import HTSeq
import cPickle as pickle
import pandas as pd
from collections import Counter
import os
from HaSAPPY_time import *
############################################################
#1) Defining the Class Library
class Library():
    """...defintion..."""
    def __init__(self,exp,input_):
        self.name = exp
        self.input = input_
        self.informations = {'Total':'nd','Aligned':'nd','Unique_reads':'nd','Insertions':'nd','I.I.':'nd'}
        self.row = pd.Series()

#2) Function library_gneration
def library_generation (exp, Info):
    #Generation of the Class Library specific for "exp"
    library = Library(exp,Info.IIDefinition.input_files[Info.IIDefinition.lib_names.index(exp)])
    print library.name
    string ='\n\n***\tInedependent Insertions (I.I.) definition\t***\n\n- Input file: %s\n- Pair ends: %s\n- Alignment cutoff: %s\n- Remove duplicates: %s\n- Insertion cutoff: %i' %(library.input, Info.General.pair_ends,Info.IIDefinition.fidelity_limit,Info.IIDefinition.reads_duplicate,Info.IIDefinition.ins_iv)
    Info.print_save(exp,string)

    startTime = getCurrTime()
    string = '\tSelection of Insertions (I.): %s' %startTime
    Info.print_save(exp,string)
    aligned_file = HTSeq.SAM_Reader(library.input)
    insertions_counts = Counter()

    if not Info.IIDefinition.reads_duplicate: # single_end sequencing!!!!
        count_aligned = 0
        count_GoodQualityAllignment = 0
        count_total = 0
        for algnt in aligned_file:
            if algnt.aligned:
                if algnt.aQual >= Info.IIDefinition.fidelity_limit:
		    ins = HTSeq.GenomicPosition(algnt.iv.chrom,algnt.iv.start_d,algnt.iv.strand)
#                    ins = HTSeq.GenomicPosition('chr%s' %str(algnt.iv.chrom),algnt.iv.start_d,algnt.iv.strand)
                    insertions_counts[ins] +=1
                    count_GoodQualityAllignment +=1
                count_aligned +=1
            count_total +=1

        string = '\t-Total reads: %i\n\t-Alligned reads: %i\n\t-Alligned Reads trusted: %i\n\t-Insertions identified: %i' %(count_total,count_aligned,count_GoodQualityAllignment, len(insertions_counts.keys()))
        Info.print_save(exp,string)

    else: # pair_end sequencing = Allow analysis of number of reads
        insertions = {}
        count_total = 0
        count_aligned = 0
        count_position = 0
        count_duplicates = 0
        count_GoodQualityAllignment = 0

        for algnt in aligned_file:
            count_total +=1 #all the read in file

            if algnt.pe_which == "first" and algnt.proper_pair:#just consider sequenced 1)alligned, 2)for which a paired_end has been identified, 3) coming from the "first" file (in theory p5 strand)
                if algnt.aQual >= Info.IIDefinition.fidelity_limit:
                    count_GoodQualityAllignment +=1
                    i_p5 = HTSeq.GenomicPosition('chr%s'%str(algnt.iv.chrom),algnt.iv.start_d,algnt.iv.strand) # Viral insertion genomic position
                    if insertions.has_key(i_p5):
                        if algnt.inferred_insert_size in insertions[i_p5]:#where algnt.mate_start is the starting genomic position of the reverse paired read (that for us..is the LAM_PCR end)
                            count_duplicates +=1 # Discard sequence (PCR artifact)
                        else:
                            insertions[i_p5].add(algnt.inferred_insert_size) #Add a new element to the insertion's list (=no redoundant read)
                    else: #Identification of a new insertion
                        count_position +=1
                        insertions[i_p5] = set() #Creation of a list were to store length of different reads
                        insertions[i_p5].add(algnt.inferred_insert_size)

                count_aligned +=1 #all the reads with pair_end alignment and coming from the p5 file

        count_reads = 0
        for ins in insertions:
            length = len(insertions[ins])
            insertions_counts[ins] = length
            count_reads += length

        string = '\t-Total reads: %i\n\t-Alligned reads: %i\n\t-Alligned Reads trusted: %i\n\t-Detected duplicates: %i\n\tInsertions identified: %i' %(count_total,count_aligned,count_GoodQualityAllignment,count_duplicates,len(insertions_counts.keys()))
        Info.print_save(exp,string)

    string = '\tRunTime: %s' % computeRunTime(startTime, getCurrTime())
    Info.print_save(exp,string)

    ### To collapse insertions in insertion array that are in the same interval (4bps)

    startTime = getCurrTime()
    string = 'Define Independent Insertions\n\tStarted: %s' %startTime
    Info.print_save(exp,string)
    insertions_series = pd.Series(insertions_counts, index = insertions_counts.keys())
    insertions_series = insertions_series.order(ascending = False)
    insertions_genomicarray = HTSeq.GenomicArray("auto",stranded = True)

    count_indipendent_insertions = 0
    count_indipendent_insertions_aborted = 0

    for ins in insertions_series.index:
        insertions_genomicarray[ins] = insertions_series[ins]

    insertions_collapsed = {}

    for i in insertions_series.index:

        if insertions_genomicarray[i]>0:
            counted = 0
            iv_i = HTSeq.GenomicInterval(i.chrom,i.start-2,i.start+2,i.strand)
            for i_2 in iv_i.xrange(step=1):
                try:
                    counted += insertions_genomicarray[i_2]
                    insertions_genomicarray[i_2] = 0
                except IndexError:
                    string =  "\t!!!Skipped from analysis: %s" % i_2
                    Info.print_save(exp,string)
                    continue

            if counted >= Info.IIDefinition.ins_iv:
                if insertions_collapsed.has_key(i):
                    insertions_collapsed[i] += counted
                else:
                    insertions_collapsed[i] = counted
                count_indipendent_insertions +=1
            else:
                count_indipendent_insertions_aborted +=1

    string = '\t-Total insertions: %i\n\t-Independent Insertions (I.I.): %i' % ((count_indipendent_insertions + count_indipendent_insertions_aborted), count_indipendent_insertions)
    Info.print_save(exp,string)

    string = '\tRunTime: %s' % computeRunTime(startTime, getCurrTime())
    Info.print_save(exp,string)

    ###Storing data in library class that will be returned modifed as result of the function

    library.informations['Total'] = count_total
    library.informations['Aligned'] = count_aligned
    library.informations['Insertions'] = count_indipendent_insertions
    library.informations['II'] = count_indipendent_insertions
    if Info.IIDefinition.reads_duplicate:
        library.informations['Unique_reads'] = count_reads

    library.row = pd.Series(insertions_collapsed, index = insertions_collapsed.keys())

    #####Store the class!!!!!#####
    location = os.path.join(Info.General.storing_loc,exp + '_' +Info.General.date,'row',exp + '_IIRowdata.pkl')
    with open (location,'wb') as saving:
            pickle.dump(library,saving)
    #####END the program#####
    string = 'Informations stored in %s\n***\tEND of Inedependent Insertions (I.I.) definition\t***' % location
    Info.print_save(exp,string)

    return library

def load(Info):
    for exp in Info.IIDefinition.lib_names:
        library_generation(exp,Info)
<commit_msg>Delete IIDefinition.py<commit_after><|endoftext|>