Best Python code snippet using lisa_python
tic_tac_toe.py
Source:tic_tac_toe.py  
1# TIC-TAC-TOE GAME CLASS2import random3def render_template(table):4    print('\t.____.____.____.')5    print(6        f'\t| {table[0][0]}  | {table[0][1]}  |  {table[0][2]} |')7    print('\t|____|____|____|')8    print(9        f'\t| {table[1][0]}  | {table[1][1]}  |  {table[1][2]} |')10    print('\t|____|____|____|')11    print(12        f'\t| {table[2][0]}  | {table[2][1]}  |  {table[2][2]} |')13    print('\t|____|____|____|')14def winning_check(board):15    # ROW CHECK OPEN16    if board[0][0] == board[0][1] == board[0][2]:17        return True18    elif board[1][0] == board[1][1] == board[1][2]:19        return True20    elif board[2][0] == board[2][1] == board[2][2]:21        return True22    # ROW CHECK CLOSE23    # COLUMN CHECK OPEN24    elif board[0][0] == board[1][0] == board[2][0]:25        return True26    elif board[0][1] == board[1][1] == board[2][1]:27        return True28    elif board[0][2] == board[1][2] == board[2][2]:29        return True30    # COLUMN CHECK CLOSE31    # DIAGONAL CHECK OPEN32    elif board[0][0] == board[1][1] == board[2][2]:33        return True34    elif board[0][2] == board[1][1] == board[2][0]:35        return True36    return False37class T3Game:38    random_set = [{1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {1, 4, 7}, {2, 5, 8}, {3, 6, 9}, {1, 5, 9}, {3, 5, 7}]39    def __init__(self, player_name, moves, board, score, win_check, player_id, my_play_history=None, mode=None):40        self.player_name = player_name41        self.moves = moves42        self.board = board43        self.score = score44        self.my_play_history = my_play_history45        self.win_check = win_check46        self.player_id = player_id47        self.mode = mode48    def movement(self):49        if self.player_name != 'Frontbot':50            while True:51                try:52                    player_number = int(input('Enter No. to play: '))53                    if player_number not in self.moves:54                        print(f"Oops! Enter value among {', '.join(map(lambda num: str(num), self.moves))}")55                        continue56                except ValueError:57                    print(f'Oops: Enter a real number')58                    continue59                else:60                    self.moves.remove(player_number)61                    return self.update_board(player_number, self.board)62        elif self.mode.lower() == 'hard':63            self.hard_mode()64        else:65            self.easy_mode()66    def hard_mode(self):67        random.shuffle(self.random_set)68        for item in self.random_set:69            _intersect = list(item & set(my_list))70            if len(_intersect) == 1:71                x, y = item - set(my_list)72                if x in self.my_play_history and y in self.my_play_history:73                    self.moves.remove(_intersect[0])74                    self.my_play_history.append(_intersect[0])75                    return self.update_board(_intersect[0], self.board)76        for item in self.random_set:77            _intersect = list(item & set(my_list))78            if len(_intersect) == 1:79                x, y = item - set(my_list)80                if x not in self.my_play_history and y not in self.my_play_history:81                    self.moves.remove(_intersect[0])82                    self.my_play_history.append(_intersect[0])83                    return self.update_board(_intersect[0], self.board)84            elif len(_intersect) == 2:85                x = item - set(my_list)86                if x in self.my_play_history:87                    y, z = _intersect88                    if y in my_list and z in my_list:89                        player_number = random.choice(_intersect)90                        self.moves.remove(player_number)91                        self.my_play_history.append(player_number)92                        return self.update_board(player_number, self.board)93            else:94                continue95        self.easy_mode()96    def easy_mode(self):97        player_number = random.choice(self.moves)98        self.moves.remove(player_number)99        self.my_play_history.append(player_number)100        return self.update_board(player_number, self.board)101    def update_board(self, value, board):102        for row in board:103            for item in range(3):104                if row[item] == value:105                    row[item] = self.player_id106                    break107    def check_status(self):108        if self.win_check(self.board):109            print(f'{self.player_name} won!')110            self.score[self.player_name] += 1111            return True112        return False113while True:114    player1_name = input('Enter your name to play against Frontbot: ')115    try:116        if player1_name.lower() == 'frontbot':117            raise ValueError('Oops! Frontbot is my name. Enter your name.')118    except ValueError as err:119        print(err)120        continue121    else:122        break123player2_name = 'Frontbot'124record = {player1_name: 0, player2_name: 0, 'draw': 0}125trial = True126counter = random.choice([1, 0])127while trial:128    template = [129        [1, 2, 3],130        [4, 5, 6],131        [7, 8, 9]132    ]133    turn = 9134    frontbot_play_history = []135    my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]136    player1 = T3Game(player1_name, my_list, template, record, winning_check, player_id='X')137    player2 = T3Game(player2_name, my_list, template, record, winning_check, player_id='O',138                     my_play_history=frontbot_play_history, mode='hard', )139    player = [player1, player2]140    counter += 1141    a = counter % 2142    b = 1 - a143    while turn:144        if turn % 2 == 0:145            render_template(template)146            print(player[a].movement())147            turn -= 1148            if player[a].check_status():149                break150            elif turn == 0:151                record['draw'] += 1152        else:153            render_template(template)154            print(player[b].movement())155            turn -= 1156            if player[b].check_status():157                break158            elif turn == 0:159                record['draw'] += 1160    render_template(template)161    print(record)162    while True:163        play_again = input('do you want to play again?\nEnter Y to continue or N to stop: ')164        if play_again.lower() == 'y' or play_again.lower() == 'yes':165            trial = True166            break167        elif play_again.lower() == 'n' or play_again.lower() == 'no':168            trial = False169            break170        else:171            print('Invalid input!')...print_grid.py
Source:print_grid.py  
1#!/usr/bin/env python32"""3Tim Meese4Au2018-Py210B5Print Grid Exercise6"""7_star = '*'8_line = '-'9_intersect = '+'10_vertline = '|'11_space = ' '12def print_grid(n):13    global _star, _line, _intersect, _vertline, _space14    outlines = []15    cur_row = 016    cur_col = 017    if n < 11:18        n = n * 2 + 119    for j in range(n):20        grid = ''21        cur_col = 022        for i in range(n):23            if (cur_row % (n // 2)) == 0 and (cur_col % (n // 2)) == 0:24                grid += _intersect25            elif (cur_row % (n // 2)) == 0:26                grid += _line27            elif (cur_col % (n // 2) == 0):28                grid += _vertline29            else:30                grid += _space31            cur_col += 132        cur_row += 133        outlines.append(grid)34    for line in outlines:35        print(line)36def print_grid2(num_columns, column_width):37    global _star, _line, _intersect, _vertline, _space38    outlines = []39    cur_row = 040    cur_col = 041    for j in range(num_columns*column_width+1):42        grid = ''43        cur_col = 044        for i in range(num_columns*column_width+1):45            if (cur_row % column_width) == 0 and (cur_col % column_width) == 0:46                grid += _intersect47            elif (cur_row % column_width) == 0:48                grid += _line49            elif (cur_col % column_width) == 0:50                grid += _vertline51            else:52                grid += _space53            cur_col += 154        cur_row += 155        outlines.append(grid)56    for line in outlines:57        print(line)58if __name__ == "__main__":59    print('\n\nprint_grid(15)\n\n')60    print_grid(15)61    print('\n\nprint_grid(13)\n\n')62    print_grid(11)63    print('\n\nprint_grid(3)\n\n')64    print_grid(3)65    print('\n\nprint_grid2(3, 4)\n\n')66    print_grid2(3, 4)67    print('\n\nprint_grid2(5, 3)\n\n')...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
