Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sourcery refactored main branch #1

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 7 additions & 3 deletions disgames/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,16 @@
VersionInfo = disgames.VersionInfo

def version() -> None:
entries = []
entries = [
'- Python v{0.major}.{0.minor}.{0.micro}-{0.releaselevel}'.format(
sys.version_info
)
]


entries.append('- Python v{0.major}.{0.minor}.{0.micro}-{0.releaselevel}'.format(sys.version_info))
version_info: VersionInfo = VersionInfo(major=2, minor=0, micro=1)
entries.append('- Disgames v{0.major}.{0.minor}.{0.micro}'.format(version_info))
entries.append(f'- aiohttp v{aiohttp.__version__}')
entries.append(f'- aiohttp v{aiohttp.__version__}')
Comment on lines -12 to +21
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function version refactored with the following changes:

entries.append(f'- Chess v{chess.__version__}')

uname = platform.uname()
Expand Down
11 changes: 6 additions & 5 deletions disgames/mixins/battleship.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,11 @@ async def on_reaction_add(self, reaction, userr):
def format_battleships_board(self, board):
"""Format the battleship board"""
lst = ["⏹1️⃣2️⃣3️⃣4️⃣5️⃣6️⃣7️⃣8️⃣"]
dct = {}
for i in range(1, 10):
dct[i] = f"{i}\N{variation selector-16}\N{combining enclosing keycap}"
dct = {
i: f"{i}\N{variation selector-16}\N{combining enclosing keycap}"
for i in range(1, 10)
}

Comment on lines -45 to +49
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Battleships.format_battleships_board refactored with the following changes:

for num, row in enumerate(board, start=1):
scn_lst = [dct[num]]
for column in row:
Expand All @@ -56,8 +58,7 @@ def has_won_battleship(self, board):
"""Checks if either players died"""
for x in board:
for y in x:
if y != "🌊" or y != "🔥":
return False
return False
Comment on lines -59 to +61
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Battleships.has_won_battleship refactored with the following changes:

return True

@commands.command()
Expand Down
16 changes: 9 additions & 7 deletions disgames/mixins/checkers.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ def format_checkers_board(self, board):
lst = ["⏹️" + "".join([dct[str(i + 1)] for i in range(len(board[0]))])]
for x, row in enumerate(board):
scn_lst = [dct[str(x + 1)]]
for y, column in enumerate(row):
for column in row:
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Checkers.format_checkers_board refactored with the following changes:

scn_lst.append(dct[column])
lst.append("".join(scn_lst))
return "\n".join(lst)
Expand Down Expand Up @@ -80,15 +80,17 @@ async def checkers(self, ctx, member: discord.Member):
continue
if direction not in opts:
await ctx.send(
f"Invalid syntax: Correct directions ul (up left), dl (down left), ur (up right), dr (down right)",
'Invalid syntax: Correct directions ul (up left), dl (down left), ur (up right), dr (down right)',
delete_after=5,
)

continue
elif not len(coors) == 2:
elif len(coors) != 2:
await ctx.send(
f"Invalid syntax: The coordinates entered are invalid",
'Invalid syntax: The coordinates entered are invalid',
delete_after=5,
)

Comment on lines -83 to +93
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Checkers.checkers refactored with the following changes:

  • Replace f-string with no interpolated values with string (remove-redundant-fstring)
  • Simplify logical expression using De Morgan identities (de-morgan)
  • Simplify conditional into switch-like form (switch)

continue
try:
await inp.delete()
Expand All @@ -97,11 +99,11 @@ async def checkers(self, ctx, member: discord.Member):
direction = opts[direction]
if direction == 1:
inc = (-1, -1)
if direction == 2:
elif direction == 2:
inc = (1, -1)
if direction == 3:
elif direction == 3:
inc = (-1, 1)
if direction == 4:
elif direction == 4:
inc = (1, 1)
try:
x, y = int(coors[0]) - 1, int(coors[1]) - 1
Expand Down
30 changes: 15 additions & 15 deletions disgames/mixins/chess.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,10 +51,11 @@ def create_chess_board(self, board, turn, member):
)
e.add_field(name="Turn", value=turn.mention, inline=False)
e.add_field(
name=f"Legal moves",
value=", ".join([f"`{str(i)}`" for i in board.legal_moves]),
name='Legal moves',
value=", ".join([f'`{i}`' for i in board.legal_moves]),
inline=False,
)

Comment on lines -54 to +58
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Chess.create_chess_board refactored with the following changes:

e.add_field(name="Check", value=board.is_check(), inline=False)
if board.halfmove_clock >= 45:
e.add_field(name="Half move clock", value=board.halfmove_clock)
Expand Down Expand Up @@ -82,7 +83,7 @@ def get_best_chess_move(self, board, smort_level):
@commands.command("chess")
async def chess(self, ctx, member: discord.Member = None):
"""a board game of strategic skill for two players, played on a chequered board on which each playing piece is moved according to precise rules. The object is to put the opponent's king under a direct attack from which escape is impossible"""
if member == None:
if member is None:
Comment on lines -85 to +86
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Chess.chess refactored with the following changes:

if not self.stockfish_path:
raise PathNotFound
await ctx.send("Please enter a a difficulty level from 0-20")
Expand Down Expand Up @@ -174,19 +175,18 @@ async def chess(self, ctx, member: discord.Member = None):
await ctx.send("Can't go back", delete_after=5)
continue
else:
if inp.author == turn:
try:
move = chess.Move.from_uci(inp.content.lower())
board.push(move)
except ValueError:
await ctx.send("Invalid move", delete_after=5)
continue
try:
await inp.delete()
except discord.Forbidden:
pass
else:
if inp.author != turn:
continue
try:
move = chess.Move.from_uci(inp.content.lower())
board.push(move)
except ValueError:
await ctx.send("Invalid move", delete_after=5)
continue
try:
await inp.delete()
except discord.Forbidden:
pass
turn = member if turn == ctx.author else ctx.author
won = self.has_won_chess(
board, member if turn == ctx.author else ctx.author
Expand Down
16 changes: 8 additions & 8 deletions disgames/mixins/connect4.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,6 @@ def minimax_connect4(self, board, depth, isMaximizing):
board[x][y] = " "
if score > bestScore:
bestScore = score
return bestScore
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Connect4.minimax_connect4 refactored with the following changes:

else:
bestScore = 800
for x, y in self.get_empty_connect4(board):
Expand All @@ -150,14 +149,14 @@ def minimax_connect4(self, board, depth, isMaximizing):
board[x][y] = " "
if score < bestScore:
bestScore = score
return bestScore

return bestScore

def make_bot_move_connect4(self, board, difficulty):
"""Returns the best move the bot can take"""
if difficulty == 1:
x, y = random.choice([move for move in self.get_empty_connect4(board)])
x, y = random.choice(list(self.get_empty_connect4(board)))
board[x][y] = 'b'
return board
Comment on lines -158 to -160
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Connect4.make_bot_move_connect4 refactored with the following changes:

else:
bestScore = -800
bestMove = 0
Expand All @@ -169,7 +168,8 @@ def make_bot_move_connect4(self, board, difficulty):
bestScore = score
bestMove = x, y
board[bestMove[0]][bestMove[1]] = 'b'
return board

return board

@commands.command()
async def connect4(self, ctx, member: discord.Member = None):
Expand Down Expand Up @@ -205,14 +205,14 @@ async def connect4(self, ctx, member: discord.Member = None):
)
if inp.content.lower() in ["stop", "end", "cancel"]:
return await ctx.send("Ended the game")
if not len(inp.content) == 1:
if len(inp.content) != 1:
continue
try:
x = int(inp.content) - 1
except ValueError:
await ctx.send(f"Invalid Syntax: {inp.content} is not a number")
continue
if not x in range(7):
if x not in range(7):
Comment on lines -208 to +215
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Connect4.connect4 refactored with the following changes:

  • Simplify logical expression using De Morgan identities (de-morgan)

await ctx.send(
f"Invalid syntax: {inp.content} isnt a valid place on the board"
)
Expand Down Expand Up @@ -276,7 +276,7 @@ async def connect4(self, ctx, member: discord.Member = None):
)
if inp.content.lower() in ["stop", "end", "cancel"]:
return await ctx.send("Ended the game")
if not len(inp.content) == 1:
if len(inp.content) != 1:
continue
try:
x = int(inp.content) - 1
Expand Down
2 changes: 1 addition & 1 deletion disgames/mixins/madlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,4 +47,4 @@ async def madlib(self, ctx, min: int = 5, max: int = 25):

await ctx.send(string)
except KeyError:
return await ctx.send(f"Invalid syntax: invalid arguments entered")
return await ctx.send('Invalid syntax: invalid arguments entered')
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function MadLib.madlib refactored with the following changes:

31 changes: 14 additions & 17 deletions disgames/mixins/minesweeper.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ def get_coors(self, coordinate):
x = int(digit) - 1
y = ord(letter) - ord("a")

if (not x in range(10)) or (not y in range(10)):
if x not in range(10) or y not in range(10):
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Minesweeper.get_coors refactored with the following changes:

  • Simplify logical expression using De Morgan identities (de-morgan)

raise commands.BadArgument(
"Invalid syntax: Entered coordinates aren't on the board"
)
Expand All @@ -64,8 +64,9 @@ def format_minesweeper_board(self, board):
for i in range(1, 10):
dct[str(i)] = f"{i}\N{variation selector-16}\N{combining enclosing keycap}"
lst = [
f":stop_button::regional_indicator_a::regional_indicator_b::regional_indicator_c::regional_indicator_d::regional_indicator_e::regional_indicator_f::regional_indicator_g::regional_indicator_h::regional_indicator_i::regional_indicator_j:"
':stop_button::regional_indicator_a::regional_indicator_b::regional_indicator_c::regional_indicator_d::regional_indicator_e::regional_indicator_f::regional_indicator_g::regional_indicator_h::regional_indicator_i::regional_indicator_j:'
]

Comment on lines -67 to +69
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Minesweeper.format_minesweeper_board refactored with the following changes:

for num, row in enumerate(board, start=1):
lst.append(dct[str(num)]+''.join([dct[str(column)] for column in row]))
return "\n".join(lst)
Expand Down Expand Up @@ -110,18 +111,15 @@ def has_won_minesweeper(self, visible_board, board):
if num == ((len(board) * len(board[0])) - len(bombs)):
return True

for bomb in bombs:
if not visible_board[int(bomb[0])][int(bomb[1])] == "f":
return False
return True
return all(visible_board[int(bomb[0])][int(bomb[1])] == "f" for bomb in bombs)
Comment on lines -113 to +114
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Minesweeper.has_won_minesweeper refactored with the following changes:


def reveal_all(self, visible_board, board):
for x in range(len(visible_board)):
for y in range(len(visible_board[x])):
if visible_board[x][y] == " ":
visible_board[x][y] = board[x][y]
elif visible_board[x][y] == 'f':
if not board[x][y] == 'b':
if board[x][y] != 'b':
Comment on lines -124 to +122
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Minesweeper.reveal_all refactored with the following changes:

  • Simplify logical expression using De Morgan identities (de-morgan)

visible_board[x][y] = 'x'
return visible_board

Expand Down Expand Up @@ -170,16 +168,15 @@ async def minesweeper(self, ctx):
color=discord.Color.blurple(),
),
)
else:
if visible_board[x][y] not in [" ","f"]:
await ctx.send(
f"Invalid Syntax: {coors} is already revealed",
delete_after=5,
)
continue
visible_board[x][y] = str(grid[x][y])
if visible_board[x][y] == "0":
visible_board = self.reveal_zeros(visible_board, grid, x, y)
if visible_board[x][y] not in [" ","f"]:
await ctx.send(
f"Invalid Syntax: {coors} is already revealed",
delete_after=5,
)
continue
visible_board[x][y] = str(grid[x][y])
if visible_board[x][y] == "0":
visible_board = self.reveal_zeros(visible_board, grid, x, y)
Comment on lines -173 to +179
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Minesweeper.minesweeper refactored with the following changes:

elif type_.lower() in ["flag", "f"]:
if visible_board[x][y] != " ":
await ctx.send(
Expand Down
6 changes: 2 additions & 4 deletions disgames/mixins/snake.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,8 @@ def get_head_position(self):
return self.snake[0]

def point(self, pt):
if self.length > 1 and (pt[0] * -1, pt[1] * -1) == self.direction:
pass
else:
self.direction = pt
if self.length <= 1 or (pt[0] * -1, pt[1] * -1) != self.direction:
self.direction = pt
Comment on lines -24 to +25
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function SnakeGame.point refactored with the following changes:


def move(self):
cur = self.snake[0]
Expand Down
25 changes: 10 additions & 15 deletions disgames/mixins/snl.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,7 @@ def __init__(self, bot):

def format_snl_board(self, board):
dct = {' ':'⬛', 's':'🐍', 'l':'🪜', 'p1':'🔴', 'p2':'🟡', 'p3':'🟢', 'p4':'🔵'}
lst = []
for row in board:
lst.append(''.join([dct[column] for column in row]))
lst = [''.join([dct[column] for column in row]) for row in board]
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function SNL.format_snl_board refactored with the following changes:

return '\n'.join(lst)

def create_board(self):
Expand All @@ -33,11 +31,12 @@ async def snl(self, ctx, players: commands.Greedy[discord.Member]=[]):
if len(players) > 4:
return await ctx.send("Can't have more than 4 people playing")
tokens = {'p1':'🔴', 'p2':'🟡', 'p3':'🟢', 'p4':'🔵'}
indexes = {}
for player in players:
indexes[player] = [9,0]
indexes = {player: [9,0] for player in players}
board = self.create_board()
player_string = f' '.join([f"{player.mention}: {tokens['p'+str(num)]}" for num, player in enumerate(players, start=1)])
player_string = ' '.join([
f"{player.mention}: {tokens['p'+str(num)]}"
for num, player in enumerate(players, start=1)
])
Comment on lines -36 to +39
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function SNL.snl refactored with the following changes:

embed = discord.Embed(title='Snakes and Ladders', description=f"React to '🎲' to roll your dice\n\n{player_string}\n{self.format_snl_board(board)}", color=discord.Color.blurple())
msg = await ctx.send(embed=embed)
await msg.add_reaction('🎲')
Expand All @@ -61,19 +60,15 @@ async def snl(self, ctx, players: commands.Greedy[discord.Member]=[]):
if str(reaction) == '🏳️':
players.remove(user)
await ctx.send(f"{user.mention} leaves")
else:
if user != player:
continue
elif user != player:
continue
await ctx.send(f'{player.mention} rolled a {number}', delete_after=5)
board[index[0]][index[1]] = ' '
past_number = index[1]
if index[0]%2:
index[1] += number
else:
if index[0] == 0 and (index[1] - number) < 0:
pass
else:
index[1] -= number
elif index[0] != 0 or index[1] - number >= 0:
index[1] -= number
if (index[1]) > 9 or (index[1]) < 0 and index[1] != 0:
index[0] -= 1
if index[0]%2:
Expand Down
11 changes: 4 additions & 7 deletions disgames/mixins/soko.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,7 @@ def format_soko_board(self, board):
}
lst = []
for i in board:
scn_lst = []
for thing in i:
scn_lst.append(dct[thing])
scn_lst = [dct[thing] for thing in i]
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Sokoban.format_soko_board refactored with the following changes:

lst.append("".join(scn_lst))
return "\n".join(lst)

Expand All @@ -40,8 +38,7 @@ def create_soko_board(self, difficulty_level):
num1 = random.randint(5, 9)
num2 = random.randint(5, 9)
num3 = 1 + difficulty_level // 5
if num3 > 7:
num3 = 7
num3 = min(num3, 7)
Comment on lines -43 to +41
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Sokoban.create_soko_board refactored with the following changes:

board = [[" " for i in range(num1)] for i in range(num2)]
x, y = random.randint(0, len(board) - 1), random.randint(0, len(board[0]) - 1)
board[x][y] = "p"
Expand Down Expand Up @@ -71,14 +68,14 @@ def get_player(self, board):
"""Returnes the x,y coordinates of the player"""
for x, i in enumerate(board):
for y, thing in enumerate(i):
if thing == "p" or thing == "tp":
if thing in ["p", "tp"]:
Comment on lines -74 to +71
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Sokoban.get_player refactored with the following changes:

return x, y

def has_won_soko(self, board):
"""Checks if there are no more t on the board"""
for x in board:
for y in x:
if y == "t" or y == "tp":
if y in ["t", "tp"]:
Comment on lines -81 to +78
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Sokoban.has_won_soko refactored with the following changes:

return False
return True

Expand Down
Loading