Python blackjack game suggestions

I have this blackjack game made in python. Would be nice to have somone look it through and suggest changes to make it better:

from random import shuffle as rsh  values = {'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9,'10':10,'J':10,'Q':10,'K':10,'A':11}  class Player: ''' Class Player ======= Input: Name, Balance Output(print): Player Info ======= Methods: Win/Lose Input: Amount Output: Balance  ''' def __init__(self,name,money):     self.name = name     self.balance = money     self.bet=0  def __str__(self):     return 'Player Info\n---------\nName: {}\nBalance: DKK  {}'.format(self.name,self.balance)  def win(self):     self.balance+=self.bet  def lose(self):     self.balance-=self.bet   class Deck: ''' Class Deck ======= Input: nothing Output(print): deck, number of cards ======= Methods: Create/Show/Shuffle Input: nothing Output: deck  ''' def __init__(self,):     #start with an empty list     self.deck = []  def __str__(self):     return ''  def create(self):     for suit in ['D','C','H','S']:         for rank in [2,3,4,5,6,7,8,9,10,'J','Q','K','A']:             deck=self.deck             deck.append(suit+str(rank))  def showme(self):     return 'Cards: {} , Total: {}'.format(self.deck,len(self.deck))      def shuffle(self):     rsh(self.deck)  def deal(self):     card = self.deck.pop()     return card    class Hand: ''' Class Hand '''  def __init__(self,name):     self.hand = []     self.value = 0     self.aces = 0     self.name = name   """ def showme(self):     if len(self.hand) == 0:         return '{} has the following cards: 0'.format(self.name)     else:         return '{} has the following cards:  {}'.format(self.name,self.hand) """  def add_card(self,newcard):     self.hand.append(newcard)     self.value+=values[newcard[1:]]     if newcard[1:]=='A':         self.aces+=1  def adjust_for_ace(self):     while self.value >21 and self.aces:         self.value-=10         self.aces-=1    #function for take bet def take_bet(player): while True:     try:         chips=int(input('How many chips do you want to bet? :'))            if player.balance < chips:             print('Sorry you dont have the amount! Your balance is  {}'.format(player.balance))         else:             player.bet = chips             break     except:         print('Only integer allowed')    #function hit def hit(deck,hand): hand.add_card(deck.deal()) hand.adjust_for_ace()   playing = True #function hit or stand def hit_or_stand(deck,hand): global playing while playing:     x = input("Would you like to Hit or Stand? Enter 'h' or 's' : ")     if x[0].lower() == 's':         print('\nPlayer stands. Dealer is playing')         playing = False     elif x[0].lower() == 'h':         hit(deck,hand)     else:         print('Please, try again!')         continue     break   #show functions def show_some(playerhand,dealerhand): print("Dealer's hand:") print('<hidden>') print(dealerhand.hand[1]) print("\nPlayer's hand:", *playerhand.hand, sep='\n')  def show_all(playerhand,dealerhand): print("\nDealers's hand:", *dealerhand.hand, sep='\n') #print("Total:" + sum()) print("\nPlayer's hand:", *playerhand.hand, sep='\n')  #scenarios def player_busts(player): print('{} busts!'.format(player.name)) player.lose()  def player_blackjack(player): print("{} got blackjack!".format(player.name)) player.win()  def dealer_blackjack(player,dealer): print("{} got blackjack!".format(dealer.name)) player.lose()  def player_wins(player): print('{} wins!'.format(player.name)) player.win()  def dealer_busts(player,dealer): print('{} busts'.format(dealer.name)) player.win()  def dealer_wins(player,dealer): print('{} wins'.format(dealer.name)) player.lose()  def tie_game(): print('Dealer and Player tie!')  def insert_money(): while True:     try:         ampl = int(input('Insert the amount of DKK for converting  chips!\n1 DKK = 1 chip : '))         if ampl > 0:             return ampl         else:             print('Only positive Integer!')      except:         print('Please input integer number!')  #starting with 2 card on hand def starting_cards(playerhand,dealerhand): for i in range(2):     playerhand.add_card(deck.deal())     dealerhand.add_card(deck.deal())   #Game is Starting namepl = input("What's your name: ") if namepl =='' or namepl == ' ': namepl = 'Anonymus'  #creating players player = Player(namepl,insert_money()) dealer = Player('Dealer',1000000) while True: print('\nWelcome to BlackJack! Get as close to 21 as you can without  going over!\nDealer stops when reaching 17. Aces count as 1 or 11.') #creating deck deck = Deck() deck.create() for i in range(0,3):     deck.shuffle() print('\nYour name is: {}'.format(namepl))    # creating player's hand player_hand = Hand(namepl) dealer_hand = Hand('Dealer')   starting_cards(player_hand,dealer_hand) take_bet(player) show_some(player_hand,dealer_hand)  while playing:     hit_or_stand(deck,player_hand)     show_some(player_hand,dealer_hand)      if player_hand.value > 21:         show_all(player_hand,dealer_hand)         player_busts(player)         break  if player_hand.value == 21:     player_blackjack(player)  if dealer_hand.value == 21:     dealer_blackjack(player,dealer)      if player_hand.value < 21:      while dealer_hand.value < 17:         hit(deck,dealer_hand)      show_all(player_hand,dealer_hand)      if dealer_hand.value > 21:         dealer_busts(player,dealer)      elif dealer_hand.value > player_hand.value:         dealer_wins(player,dealer)      elif dealer_hand.value < player_hand.value:         player_wins(player)      else:         tie_game()  print("\nTotal money {} DKK!".format(player.balance))  # Ask to play again new_game = input("Would you like to play another hand? Enter 'y' or 'n'  ")  if new_game[0].lower()=='y':     playing=True     continue else:     print("Thanks for playing!")     break 

Python Chess Game

I’m developing chess in python, and I’ve decided to make everything text-based before creating a GUI because it’d be my first time doing the latter. I haven’t got around to the actual gameplay, but I’ve modeled the possible movement of any piece.

Note that I cannot implement En Passant and castling without turn data.

from time import sleep  class Config:     DEMTIME = .8  # seconds     types = {'min': 1, 'miniature': 3, 'small': 5, 'default': 8, 'extended': 11, 'large': 15, 'massive': 20, 'max': 26}     letters = tuple('abcdefghijklmnopqrstuvwxyz')     white_pieces = {'Pawn' : "♙", 'Rook' : "♖", 'Knight' : "♘", 'Bishop' : "♗", 'King' : "♔", 'Queen' : "♕" }     black_pieces = {'Pawn' : "♟", 'Rook' : "♜", 'Knight' : "♞", 'Bishop' : "♝", 'King' : "♚", 'Queen' : "♛" }     board = 'UNINITIALIZED'     b_len = 'UNINITIALIZED'      @classmethod     def new_board(cls, btype='default'):         def size(x):             return [['___' for _ in range(x)] for _ in range(x)], x          s = False          if btype is not None:             btype = btype.lower()              if 'custom' in btype:                 btype = int(btype.replace('custom', '').strip())                 if 1 <= btype <= 26:                     cls.board, cls.b_len = size(btype)                     s = True                 else:                     btype = None                     cls.new_board(btype)             elif btype in cls.types:                 cls.board, cls.b_len = size(cls.types[btype])                 s = True             else:                 print(f'Unable to initialize board of unknown type {btype}')          else:             print('Unable to initalize board with a size lower than 1 or greater than 26')          if s: cls.print_board()      @classmethod     def print_board(cls):         if Config.b_len != 'UNINITIALIZED':             def printl():                 if len(str(cls.b_len)) == 2:                     print(' ', end='')                 for x in range(cls.b_len):                     print(' '*6 + f'{cls.letters[x]}', end='')                 print('\n')              print('\n'*2)             printl()             for x in range(cls.b_len):                 print(f'{cls.b_len-x:0{len(str(cls.b_len))}}  {cls.board[x]}  {cls.b_len-x:0{len(str(cls.b_len))}}\n')             printl()             print('\n'*4)          else:             print('Unable to print board of uninitialized type')      @classmethod     def tile_convert(cls, x, display_tile=False):         if not display_tile:             if isinstance(x, str):                 return cls.letters.index(x)             else:                 return cls.letters[x]         else:  # display_tile converts the letter in {letter}{number} to a number             return cls.b_len - int(x)      @classmethod     def l_num_to_coord(cls, pos):         return Config.b_len - int(pos[1]), int(Config.tile_convert(pos[0]))      @classmethod     def coord_to_tile(cls, x, y):         return f'{Config.tile_convert(x)}{Config.tile_convert(y, True)}'      @classmethod     def c_convert(cls, color):         if color == 'White':             return 'b'         if color == "Black":             return 'w'  class ChessPiece:     def __init__(self, pos, color, num, piece):         self.x = int(Config.tile_convert(pos[0]))         self.y = Config.b_len - int(pos[1])         self.color = color         self.piece = piece         self.pieceid = num         self.moves = 0         self.captured = []         self.erased = False         self.set_id()         self.create()         Config.print_board()      def __str__(self):         return self.piece      def __repr__(self):         return self.pieceid      def set_id(self):         if self.__class__.__name__ != "Knight":             self.pieceid = f'{self.piece[0]}{self.pieceid}'         else:             self.pieceid = f'N{self.pieceid}'          if self.color is not None:             if self.color.lower() in ('black', 'white', 'b', 'w'):                 self.pieceid = self.color.lower()[0] + self.pieceid                 if self.color.lower() == 'b':                     self.color = 'Black'                 elif self.color.lower() == 'w':                     self.color = 'White'             else:                 self.color = None                 print("Invalid color input. Color not set.")                 self.set_id()         else:              self.pieceid = '_' + self.pieceid       def create(self):         if Config.board[self.y][self.x] != '___':             po = Config.board[self.y][self.x]             print(f'Piece {po} erased to make room for {self.pieceid}')          Config.board[self.y][self.x] = self.pieceid      def teleport(self, pos, record=False):         Config.board[self.y][self.x] = '___'          if record:             self.moves += 1             coord = Config.l_num_to_coord(pos)             if Config.board[coord[0]][coord[1]] != '___':                 self.captured.append(Config.board[coord[0]][coord[1]])                 print(f'{self.pieceid} has captured {Config.board[coord[0]][coord[1]]}!')          self.x = Config.tile_convert(pos[0])         self.y = Config.tile_convert(pos[1], True)          Config.board[self.y][self.x] = self.pieceid          Config.print_board()      def move(self, pos):         if pos in self.possible_moves():             coord = Config.l_num_to_coord(pos)             if Config.board[coord[0]][coord[1]] != '___':                 self.captured.append(Config.board[coord[0]][coord[1]])                 print(f'{self.pieceid} has captured {Config.board[coord[0]][coord[1]]}!')                 # Erase piece              if self.__class__ == Pawn:                 if abs(int(pos[1]) - Config.tile_convert(self.y, True)) == 2:                     self.two_move = True              self.teleport(pos)             self.moves += 1          else:             print(f'Unable to move to {pos}')       def get_info(self):         print(f'{self.__class__.__name__}:\n')         print('ID: ', self.pieceid)         print('Position: ', Config.tile_convert(self.x), Config.tile_convert(self.y, True), sep='')         print('Color: ', self.color)      def erase(self):  # Doesn't delete the piece. It can be brought back by moving it to a square         Config.board[self.y][self.x] = '___'         self.erased = True      def demo(self, rec=True):  # default board         for pos in self.demo_moves:             self.teleport(pos, rec)             sleep(Config.DEMTIME)          if self.__class__ == Pawn:             self.promote2(Queen)      @staticmethod     def castle(king, rook):         if not king.moves and not rook.moves:             if not king.in_check:                 pass   class Pawn(ChessPiece):     def __init__(self, pos='a1', color=None, num='_'):         ChessPiece.__init__(self, pos, color, num, self.__class__.__name__)         self.demo_moves = ('e1', 'e2', 'e3', 'e4', 'e5', 'e6', 'e7', 'e8')         self.two_move = False      def possible_moves(self):         pos_moves = []          x, y = self.x, self.y          # Forward         if not self.moves: # Starting Position             if self.color != 'White':                 for new_y in (y+1, y+2):                     try:                         if Config.board[new_y][x] == '___':                             pos_moves.append(Config.coord_to_tile(x, new_y))                         else: break                     except IndexError: pass              if self.color != 'Black':                 for new_y in (y-1, y-2):                     try:                         if Config.board[new_y][x] == '___':                             pos_moves.append(Config.coord_to_tile(x, new_y))                         else: break                     except IndexError: pass          else:  # Post-Start             if self.color != 'White':                 try:                     if Config.board[y+1][x] == '___':                         pos_moves.append(Config.coord_to_tile(x, y+1))                 except IndexError: pass              if self.color != 'Black':                 try:                     if Config.board[y-1][x] == '___':                         pos_moves.append(Config.coord_to_tile(x, y-1))                 except IndexError: pass          # Capturing         if self.color != 'White':             if self.color is not None:                 try:                     if Config.c_convert(self.color) in Config.board[y+1][x+1]:                         pos_moves.append(Config.coord_to_tile(x+1, y+1))                 except IndexError: pass             else:                 try:                     if Config.board[y+1][x+1] != '___':                         pos_moves.append(Config.coord_to_tile(x+1, y+1))                 except IndexError: pass          if self.color != 'Black':             if self.color is not None:                 try:                     if Config.c_convert(self.color) in Config.board[y-1][x-1]:                         pos_moves.append(Config.coord_to_tile(x-1, y-1))                 except IndexError: pass             else:                 try:                     if Config.board[y+1][x+1] != '___':                         pos_moves.append(Config.coord_to_tile(x-1, y-1))                 except IndexError: pass          # En Passant           return sorted(pos_moves)      def promote(self, piece):  # oringal_piece = original_piece.promote(new_piece)         pos = f'{Config.tile_convert(self.x)}{Config.tile_convert(self.y, True)}'          return piece(pos, color=self.color, num='p')      def promote2(self, piece):         pos = f'{Config.tile_convert(self.x)}{Config.tile_convert(self.y, True)}'          self.__class__ = piece         self.__init__(pos, self.color, 'p')   class Knight(ChessPiece):     def __init__(self, pos='a1', color=None, num='_'):         ChessPiece.__init__(self, pos, color, num, self.__class__.__name__)         self.demo_moves = ('e1', 'f3', 'g5', 'h7', 'f8', 'e6', 'c5', 'd3', 'e1')      def possible_moves(self):         pos_moves = []         for x_off, y_off in ( (1, 2), (-1, 2), (1, -2), (-1, -2), (2, 1), (-2, 1), (2, -1), (-2, -1) ):             new_x = self.x + x_off             new_y = self.y + y_off             if 0 <= new_x < Config.b_len and 0 <= new_y < Config.b_len:                 if self.color is not None:                     if self.color[0].lower() not in Config.board[new_y][new_x]:                         pos_moves.append(Config.coord_to_tile(new_x, new_y))                 else:                     pos_moves.append(Config.coord_to_tile(new_x, new_y))          return sorted(pos_moves)   class Bishop(ChessPiece):     def __init__(self, pos='a1', color=None, num='_'):         ChessPiece.__init__(self, pos, color, num, self.__class__.__name__)         self.demo_moves = ('a1', 'e5', 'b8', 'h2', 'e5', 'a1')      def possible_moves(self):         pos_moves = []          x, y = self.x, self.y          right_up = zip(range(x + 1, Config.b_len), range(y - 1, -1, -1))         right_down = zip(range(x + 1, Config.b_len), range(y + 1, Config.b_len))          left_up = zip(range(x - 1, -1, -1), range(y - 1, -1, -1))         left_down = zip(range(x - 1, -1, -1), range(y + 1, Config.b_len))          for r in (right_up, right_down, left_up, left_down):             for new_x, new_y in r:                 if self.color is not None:                     if self.color[0].lower() not in Config.board[new_y][new_x]:                         pos_moves.append(Config.coord_to_tile(new_x, new_y))                         if Config.board[new_y][new_x] != '___': break                     else: break                 else:                     pos_moves.append(Config.coord_to_tile(new_x, new_y))          return sorted(pos_moves)   class Rook(ChessPiece):     def __init__(self, pos='a1', color=None, num='_'):         ChessPiece.__init__(self, pos, color, num, self.__class__.__name__)         self.demo_moves = ('a1', 'a8', 'h8', 'h1', 'a1')      def possible_moves(self):         pos_moves = []          x, y = self.x, self.y          # Horizontal         for r in (range(x+1, Config.b_len), reversed(range(x))):             for new_x in r:                 if self.color is not None:                     if self.color[0].lower() not in Config.board[y][new_x]:                         pos_moves.append(Config.coord_to_tile(new_x, y))                         if Config.board[y][new_x] != '___': break                     else: break                 else:                     pos_moves.append(Config.coord_to_tile(new_x, y))                     if Config.board[new_y][new_x] != '___': break          # Vertical         for r in (range(y+1, Config.b_len), reversed(range(y))):             for new_y in r:                 if self.color is not None:                     if self.color[0].lower() not in Config.board[new_y][x]:                         pos_moves.append(Config.coord_to_tile(x, new_y))                         if Config.board[new_y][x] != '___': break                     else: break                 else:                     pos_moves.append(Config.coord_to_tile(x, new_y))                     if Config.board[new_y][new_x] != '___': break          return sorted(pos_moves)   class Queen(ChessPiece):     def __init__(self, pos='a1', color=None, num='_'):         ChessPiece.__init__(self, pos, color, num, self.__class__.__name__)         self.demo_moves = ('a1', 'h8', 'a8', 'h1', 'a1')      def possible_moves(self):         pos_moves = []          x, y = self.x, self.y          # Horizontal         for r in (range(x+1, Config.b_len), reversed(range(x))):             for new_x in r:                 if self.color is not None:                     if self.color[0].lower() not in Config.board[y][new_x]:                         pos_moves.append(Config.coord_to_tile(new_x, y))                         if Config.board[y][new_x] != '___': break                     else: break                 else:                     pos_moves.append(f'{Config.tile_convert(new_x)}{Config.tile_convert(y, True)}')                     if Config.board[new_y][new_x] != '___': break          # Vertical         for r in (range(y+1, Config.b_len), reversed(range(y))):             for new_y in r:                 if self.color is not None:                     if self.color[0].lower() not in Config.board[new_y][x]:                         pos_moves.append(Config.coord_to_tile(x, new_y))                         if Config.board[new_y][x] != '___': break                     else: break                 else:                     pos_moves.append(f'{Config.tile_convert(x)}{Config.tile_convert(new_y, True)}')                     if Config.board[new_y][new_x] != '___': break          #Diagonal         right_up = zip(range(x + 1, Config.b_len), range(y - 1, -1, -1))         right_down = zip(range(x + 1, Config.b_len), range(y + 1, Config.b_len))          left_up = zip(range(x - 1, -1, -1), range(y - 1, -1, -1))         left_down = zip(range(x - 1, -1, -1), range(y + 1, Config.b_len))          for r in (right_up, right_down, left_up, left_down):             for new_x, new_y in r:                 if self.color is not None:                     if self.color[0].lower() not in Config.board[new_y][new_x]:                         pos_moves.append(Config.coord_to_tile(new_x, new_y))                         if Config.board[new_y][new_x] != '___': break                     else: break                 else:                     pos_moves.append(Config.coord_to_tile(new_x, new_y))          return sorted(pos_moves)   class King(ChessPiece):     def __init__(self, pos='a1', color=None, num='_'):         ChessPiece.__init__(self, pos, color, num, self.__class__.__name__)         self.demo_moves = ('e4', 'd5', 'c4', 'c5', 'd6', 'e5', 'e4')         self.in_check = False      def possible_moves(self):         pos_moves = []          x, y = self.x, self.y          for x_off, y_off in ( (0, 1), (0, -1), (1, 0), (-1, 0), (1, 1), (-1, 1), (-1, -1), (1, -1) ):             new_x = self.x + x_off             new_y = self.y + y_off             if 0 <= new_x < Config.b_len and 0 <= new_y < Config.b_len:                 if self.color is not None:                     if self.color[0].lower() not in Config.board[new_y][new_x]:                         pos_moves.append(Config.coord_to_tile(new_x, new_y))                 else:                     pos_moves.append(Config.coord_to_tile(new_x, new_y))           return sorted(pos_moves)   # Some commands to start out with  Config.new_board('default')  r1 = Rook(color='w') n1 = Knight('a5', color='b') p1 = Pawn('e1', color='w') p2 = Pawn('e8', color='b') p3 = Pawn('f7', color='w') r1.teleport('b3') 

I plan to use the IDs in order to dictate piece images on the GUI.

Stacker game with three blocks

I am pretty new to C# and so i would like to ask you, how i could improve my code. I am currently coding a Visual Studio C# Console Game where you have to stack blocks. Currently you can only Stack 3 blocks because my code is getting really long and i am really losing my orientation.

The voids “Reihe1()”, “Reihe2()” and “Reihe3()” are for the different rows. Is there any way i can improve my code? To completly understand my game pls just try it in Visual Studio.

I hope that you can help me. And please keep in mind, that i am a beginner!

Here is the code:

//(c) DomeGamer14  using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Threading; using static System.Console; using System.IO;  namespace Test1 {     class Program     {         public static string[] field = new string[70];         public static int counter = 0;          static void Main(string[] args)         {             for (int i = 0; i < field.Length; i++)             {                 field[i] = "O";                 Write(field[i]);                 if (i == 6 || i == 13 || i == 20 || i == 27 || i == 34 || i == 41 || i == 48 || i == 55 || i == 62 || i == 69)                 {                     WriteLine();                 }             }             ReadLine();              Reihe1();             ReadKey();             Clear();             Reihe2();             ReadKey();             ReadKey();             Clear();             Reihe3();             ReadKey();             ReadKey();         }          static void Show()         {             for (int i = 0; i < field.Length; i++)             {                 Write(field[i]);                 if (i == 6 || i == 13 || i == 20 || i == 27 || i == 34 || i == 41 || i == 48 || i == 55 || i == 62 || i == 69)                 {                     WriteLine();                 }             }         }          static void Reihe1()         {             do             {                 Clear();                 field[63] = "X";                 field[64] = "X";                 field[65] = "X";                 Show();                 if (Console.KeyAvailable == true)                     break;                 Thread.Sleep(200);                 Clear();                 field[63] = "O";                 field[66] = "X";                 Show();                 if (Console.KeyAvailable == true)                     break;                 Thread.Sleep(200);                 Clear();                 field[64] = "O";                 field[67] = "X";                 Show();                 if (Console.KeyAvailable == true)                     break;                 Thread.Sleep(200);                 Clear();                 field[65] = "O";                 field[68] = "X";                 Show();                 if (Console.KeyAvailable == true)                     break;                 Thread.Sleep(200);                 Clear();                 field[66] = "O";                 field[69] = "X";                 Show();                 if (Console.KeyAvailable == true)                     break;                 Thread.Sleep(200);                 Clear();                 field[69] = "O";                 field[66] = "X";                 Show();                 if (Console.KeyAvailable == true)                     break;                 Thread.Sleep(200);                 Clear();                 field[68] = "O";                 field[65] = "X";                 Show();                 if (Console.KeyAvailable == true)                     break;                 Thread.Sleep(200);                 Clear();                 field[67] = "O";                 field[64] = "X";                 Show();                 if (Console.KeyAvailable == true)                     break;                 Thread.Sleep(200);                 Clear();                 field[66] = "O";                 field[63] = "X";                 Show();                 if (Console.KeyAvailable == true)                     break;             } while (true);         }          static void Reihe2()         {              do             {                 Clear();                 field[56] = "X";                 field[57] = "X";                 field[58] = "X";                 Show();                 if (Console.KeyAvailable == true)                     break;                 Thread.Sleep(200);                 Clear();                 field[56] = "O";                 field[59] = "X";                 Show();                 if (Console.KeyAvailable == true)                     break;                 Thread.Sleep(200);                 Clear();                 field[57] = "O";                 field[60] = "X";                 Show();                 if (Console.KeyAvailable == true)                     break;                 Thread.Sleep(200);                 Clear();                 field[58] = "O";                 field[61] = "X";                 Show();                 if (Console.KeyAvailable == true)                     break;                 Thread.Sleep(200);                 Clear();                 field[59] = "O";                 field[62] = "X";                 Show();                 if (Console.KeyAvailable == true)                     break;                 Thread.Sleep(200);                 Clear();                 field[62] = "O";                 field[59] = "X";                 Show();                 if (Console.KeyAvailable == true)                     break;                 Thread.Sleep(200);                 Clear();                 field[61] = "O";                 field[58] = "X";                 Show();                 if (Console.KeyAvailable == true)                     break;                 Thread.Sleep(200);                 Clear();                 field[60] = "O";                 field[57] = "X";                 Show();                 if (Console.KeyAvailable == true)                     break;                 Thread.Sleep(200);                 Clear();                 field[59] = "O";                 field[56] = "X";                 Show();                 if (Console.KeyAvailable == true)                     break;             } while (true);               for (int i = 0; i < 63; i++)             {                 if (field[i] == "X" && field[i + 7] != "X")                 {                     Thread.Sleep(2000);                     field[i] = "O";                     Clear();                     Show();                     counter += 1;                     if (counter == 3)                     {                         Clear();                         WriteLine("Game Over!");                         WriteLine("Press a Key to end the program!");                         ReadKey();                         ReadKey();                         Environment.Exit(0);                     }                 }             }         }          static void Reihe3()         {             if (counter == 2)             {                 do                 {                     Clear();                     field[49] = "X";                     Show();                     if (Console.KeyAvailable == true)                         break;                     Thread.Sleep(200);                     Clear();                     field[49] = "O";                     field[50] = "X";                     Show();                     if (Console.KeyAvailable == true)                         break;                     Thread.Sleep(200);                     Clear();                     field[50] = "O";                     field[51] = "X";                     Show();                     if (Console.KeyAvailable == true)                         break;                     Thread.Sleep(200);                     Clear();                     field[51] = "O";                     field[52] = "X";                     Show();                     if (Console.KeyAvailable == true)                         break;                     Thread.Sleep(200);                     Clear();                     field[52] = "O";                     field[53] = "X";                     Show();                     if (Console.KeyAvailable == true)                         break;                     Thread.Sleep(200);                     Clear();                     field[53] = "O";                     field[54] = "X";                     Show();                     if (Console.KeyAvailable == true)                         break;                     Thread.Sleep(200);                     Clear();                     field[54] = "O";                     field[55] = "X";                     Show();                     if (Console.KeyAvailable == true)                         break;                     Thread.Sleep(200);                     Clear();                     field[55] = "O";                     field[54] = "X";                     Show();                     if (Console.KeyAvailable == true)                         break;                     Thread.Sleep(200);                     Clear();                     field[54] = "O";                     field[53] = "X";                     Show();                     if (Console.KeyAvailable == true)                         break;                     Thread.Sleep(200);                     Clear();                     field[53] = "O";                     field[52] = "X";                     Show();                     if (Console.KeyAvailable == true)                         break;                     Thread.Sleep(200);                     Clear();                     field[52] = "O";                     field[51] = "X";                     Show();                     if (Console.KeyAvailable == true)                         break;                     Thread.Sleep(200);                     Clear();                     field[51] = "O";                     field[50] = "X";                     Show();                     if (Console.KeyAvailable == true)                         break;                     Thread.Sleep(200);                     Clear();                     field[50] = "O";                     field[49] = "X";                     Show();                     if (Console.KeyAvailable == true)                         break;                 } while (true);                 counter = 0;                  for (int i = 0; i < 63; i++)                 {                     if (field[i] == "X" && field[i + 7] != "X")                     {                         Thread.Sleep(2000);                         field[i] = "O";                         Clear();                         Show();                         counter += 1;                         if (counter == 3)                         {                             Clear();                             WriteLine("Game Over!");                             WriteLine("Press a Key to end the program!");                             ReadKey();                             ReadKey();                             Environment.Exit(0);                         }                     }                 }             }             else if (counter == 1)             {                 do                 {                     Clear();                     field[49] = "X";                     field[50] = "X";                     Show();                     if (Console.KeyAvailable == true)                         break;                     Thread.Sleep(200);                     Clear();                     field[49] = "O";                     field[51] = "X";                     Show();                     if (Console.KeyAvailable == true)                         break;                     Thread.Sleep(200);                     Clear();                     field[50] = "O";                     field[52] = "X";                     Show();                     if (Console.KeyAvailable == true)                         break;                     Thread.Sleep(200);                     Clear();                     field[51] = "O";                     field[53] = "X";                     Show();                     if (Console.KeyAvailable == true)                         break;                     Thread.Sleep(200);                     Clear();                     field[52] = "O";                     field[54] = "X";                     Show();                     if (Console.KeyAvailable == true)                         break;                     Thread.Sleep(200);                     Clear();                     field[53] = "O";                     field[55] = "X";                     Show();                     if (Console.KeyAvailable == true)                         break;                     Thread.Sleep(200);                     Clear();                     field[55] = "O";                     field[53] = "X";                     Show();                     if (Console.KeyAvailable == true)                         break;                     Thread.Sleep(200);                     Clear();                     field[54] = "O";                     field[52] = "X";                     Show();                     if (Console.KeyAvailable == true)                         break;                     Thread.Sleep(200);                     Clear();                     field[53] = "O";                     field[51] = "X";                     Show();                     if (Console.KeyAvailable == true)                         break;                     Thread.Sleep(200);                     Clear();                     field[52] = "O";                     field[50] = "X";                     Show();                     if (Console.KeyAvailable == true)                         break;                     Thread.Sleep(200);                     Clear();                     field[51] = "O";                     field[49] = "X";                     Show();                     if (Console.KeyAvailable == true)                         break;                  } while (true);                  counter = 0;                  for (int i = 0; i < 63; i++)                 {                     if (field[i] == "X" && field[i + 7] != "X")                     {                         Thread.Sleep(2000);                         field[i] = "O";                         Clear();                         Show();                         counter += 1;                         if (counter == 3)                         {                             Clear();                             WriteLine("Game Over!");                             WriteLine("Press a Key to end the program!");                             ReadKey();                             ReadKey();                             Environment.Exit(0);                         }                     }                 }             }             else             {                 do                 {                     Clear();                     field[49] = "X";                     field[50] = "X";                     field[51] = "X";                     Show();                     if (Console.KeyAvailable == true)                         break;                     Thread.Sleep(200);                     Clear();                     field[49] = "O";                     field[52] = "X";                     Show();                     if (Console.KeyAvailable == true)                         break;                     Thread.Sleep(200);                     Clear();                     field[50] = "O";                     field[53] = "X";                     Show();                     if (Console.KeyAvailable == true)                         break;                     Thread.Sleep(200);                     Clear();                     field[51] = "O";                     field[54] = "X";                     Show();                     if (Console.KeyAvailable == true)                         break;                     Thread.Sleep(200);                     Clear();                     field[52] = "O";                     field[55] = "X";                     Show();                     if (Console.KeyAvailable == true)                         break;                     Thread.Sleep(200);                     Clear();                     field[55] = "O";                     field[52] = "X";                     Show();                     if (Console.KeyAvailable == true)                         break;                     Thread.Sleep(200);                     Clear();                     field[54] = "O";                     field[51] = "X";                     Show();                     if (Console.KeyAvailable == true)                         break;                     Thread.Sleep(200);                     Clear();                     field[53] = "O";                     field[50] = "X";                     Show();                     if (Console.KeyAvailable == true)                         break;                     Thread.Sleep(200);                     Clear();                     field[52] = "O";                     field[49] = "X";                     Show();                     if (Console.KeyAvailable == true)                         break;                   } while (true);                  counter = 0;                  for (int i = 0; i < 63; i++)                 {                     if (field[i] == "X" && field[i + 7] != "X")                     {                         Thread.Sleep(2000);                         field[i] = "O";                         Clear();                         Show();                         counter += 1;                         if (counter == 3)                         {                             Clear();                             WriteLine("Game Over!");                             WriteLine("Press a Key to end the program!");                             ReadKey();                             ReadKey();                             Environment.Exit(0);                         }                     }                 }             }         }     } } ``` 

Python program to know who wins a tic-tac-toe game

Given an input where we have two players: “X” and “O”, and empty cells marked with a “.” like:

check_winner([ “X.O”, “XX.”, “XOO”])

the program outputs if there are three “X” or “O” in horizontal, vertical or diagonal. If there is a draw it outputs “D”.

expected results

def check_winner(game_result: List[str]) -> str:      for i, row in enumerate(game_result):         if game_result[i][0] == game_result[i][1] == game_result[i][2]:             if game_result[i][0] != ".":                 return game_result[i][0]         if game_result[0][i] == game_result[1][i] == game_result[2][i]:             if game_result[0][i] != ".":                 return game_result[0][i]      if game_result[0][0] == game_result[1][1] == game_result[2][2]:         if game_result[1][1] != ".":             return game_result[1][1]      if game_result[0][2] == game_result[1][1] == game_result[2][0]:         if game_result[1][1] != ".":             return game_result[1][1]      return "D" 

How could we improve this code?

Python program for Jump game II

This is a Leetcode problem:

Given an array of non-negative integers, you are initially positioned at the first index of the array.

Each element in the array represents your maximum jump length at that position.

Your goal is to reach the last index in the minimum number of jumps.

Note:

You can assume that you can always reach the last index.

Here is my first solution to this problem:

def jump(nums):     n = len(nums)     curr_far = min(nums[0], n - 1)     next_far = 0     step = 0     for i in range(n):         if i <= curr_far:             if next_far < i + nums[i]:                 next_far = min(i + nums[i], n - 1)             if i == curr_far and curr_far != 0:                 curr_far = next_far                 step += 1      return step  nums = #Enter a list.        print(jump(nums)) 

Here is an example of an input/output:

nums = [2,3,1,1,4] >>> 2 

The minimum number of jumps to reach the last index is 2.

Jump 1 step from index 0 to 1, then 3 steps to the last index.

Here is my second solution to this problem:

class Solution:      def __init__(self, nums):         self.nums = nums      def jump(self, nums):         if not nums or len(nums) == 1:             return 0          curr = 0         count = 0         while(curr < len(nums)):             maxReach = -1             index = 0             for i in range(1, nums[curr] + 1):                 if curr + i >= len(nums) - 1:                     return count + 1                 else:                     if nums[curr + i] + i > maxReach:                         maxReach = nums[curr + i] + i                         index = curr + i             curr = index             count += 1  nums = #Enter a list.            game = Solution(nums) print(game.jump(nums)) 

Input/output – Same as above.

So, I would like to have a code review for the efficiency of both the programs.

Any help would be highly appreciated.