├── .DS_Store ├── Base64 ├── Makefile ├── README.md ├── decoder.cpp └── encoder.cpp ├── Conway's Game Of Life ├── .DS_Store ├── ConwaysGameOfLife.py ├── README.md └── requirements.txt ├── Sorting Algorithms ├── .DS_Store ├── BubbleSort.py ├── CountingSort.py ├── DatasetGenerator.py ├── HeapSort.py ├── InsertionSort.py ├── MergeSort.py ├── QuickSort.py ├── README.md ├── SelectionSort.py └── requirements.txt ├── Tetris ├── .DS_Store ├── README.md ├── __pycache__ │ └── shapes.cpython-37.pyc ├── main.py ├── requirements.txt ├── requiries │ ├── .DS_Store │ ├── FFF Phantom 01.ttf │ └── Tetris.mp3 └── shapes.py ├── Tic-Tac-Toe ├── .DS_Store ├── README.md ├── __pycache__ │ └── logic.cpython-37.pyc ├── graphics.py ├── logic.py └── requirements.txt └── x86 Assembly Playground └── README.md /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/2arian3/Cool-Programming-Challenges/9455aee7adfdd1f8eddf8c6243f8c6837edbda5d/.DS_Store -------------------------------------------------------------------------------- /Base64/Makefile: -------------------------------------------------------------------------------- 1 | all : encoder decoder 2 | encoder : encoder.cpp 3 | g++ -o encode encoder.cpp 4 | decoder : decoder.cpp 5 | g++ -o decode decoder.cpp -------------------------------------------------------------------------------- /Base64/README.md: -------------------------------------------------------------------------------- 1 | # Base64 2 | In computer science, Base64 is a group of binary-to-text encoding schemes that represent binary data in an ASCII string format by translating it into a radix-64 representation. The term Base64 originates from a specific MIME content transfer encoding. Each Base64 digit represents exactly 6 bits of data. Three 8-bit bytes (i.e., a total of 24 bits) can therefore be represented by four 6-bit Base64 digits. 3 | Common to all binary-to-text encoding schemes, Base64 is designed to carry data stored in binary formats across channels that only reliably support text content. Base64 is particularly prevalent on the World Wide Web where its uses include the ability to embed image files or other binary assets inside textual assets such as HTML and CSS files.[wikipedia]
4 | ## How to use? 5 | **In order to use this simple program you should git clone this repository to your PC and enter the following commands in your terminal.** 6 | ### Compiling 7 | Enter ```make``` command in the current directory to compile the codes. 8 | ### Encoder 9 | If you have a file and you want it to be converted to base64 enter this command. 10 | ``` 11 | ./encode fileName 12 | ``` 13 | The result will be stored in **encoded_input** file in the same directory. 14 | 15 | ### Decoder 16 | If you want to decode a base64 file enter the following command. 17 | ``` 18 | ./decode base64FileName 19 | ``` 20 | The result will be stored in **decoded_input** file in the same directory. -------------------------------------------------------------------------------- /Base64/decoder.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | int base64_mapping(char character){ 6 | int result = character >= 'A' && character <= 'Z' ? int(character) - int('A'): 7 | character >= 'a' && character <= 'z' ? int(character) - int('a') + 26: 8 | character >= '0' && character <= '9' ? int(character) - int('0') + 52: 9 | character == '+' ? 62 : 63; 10 | return result; 11 | } 12 | 13 | std::string base64_decoding(std::string text){ 14 | std::string converted; 15 | converted += char ((base64_mapping(text[0]) << 2) | (base64_mapping(text[1]) >> 4)); 16 | converted += char (((base64_mapping(text[1]) & 0b1111) << 4) | ((base64_mapping(text[2]) & 0b111100) >> 2)); 17 | converted += char (((base64_mapping(text[2]) & 0b11) << 6) | (base64_mapping(text[3]))); 18 | return converted; 19 | } 20 | 21 | int main(int argc, char **argv) { 22 | if(argc != 2){ 23 | std::cout << "Illegal input..." << std::endl; 24 | return -1; 25 | } 26 | 27 | std::string read, decoded; 28 | std::ifstream input_file (argv[1], std::ios::ate | std::ios::binary); 29 | if(input_file.is_open()) { 30 | 31 | std::streampos size = input_file.tellg(); 32 | char *buffer = new char[size]; 33 | input_file.seekg(0, std::ios::beg); 34 | input_file.read(buffer, size); 35 | 36 | for (int i = 0; i < size; i++) { 37 | read += buffer[i]; 38 | if (read.size() == 4) { 39 | decoded += base64_decoding(read); 40 | read = ""; 41 | } 42 | } 43 | 44 | int padding = std::count(buffer, buffer + size, '='); 45 | while (padding) { 46 | padding--; 47 | decoded.pop_back(); 48 | } 49 | 50 | delete[] buffer; 51 | std::ofstream output_file("decoded_input", std::ios::out | std::ios::binary); 52 | output_file << decoded; 53 | input_file.close(); 54 | output_file.close(); 55 | } else{ 56 | std::cout << "Cannot open the given file :/" << std::endl; 57 | return -1; 58 | } 59 | return 0; 60 | } -------------------------------------------------------------------------------- /Base64/encoder.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | char base64_mapping(char binary){ 6 | char result = binary < 26 ? binary + 'A' : 7 | binary < 52 ? binary + 'a' - 26 : 8 | binary < 62 ? binary + '0' - 52 : 9 | binary == 62 ? '+' : '/'; 10 | return result; 11 | } 12 | 13 | std::string base64_encoding(unsigned char* text){ 14 | std::string converted; 15 | converted += base64_mapping(text[0] >> 2); 16 | converted += base64_mapping((text[1] >> 4) | ((text[0] & 0b11) << 4)); 17 | converted += base64_mapping((text[2] >> 6) | ((text[1] & 0b1111) << 2)); 18 | converted += base64_mapping(text[2] & 0b111111); 19 | return converted; 20 | } 21 | 22 | int main(int argc, char **argv) { 23 | if (argc != 2){ 24 | std::cout << "Illegal input..." << std::endl; 25 | return -1; 26 | } 27 | 28 | std::string encoded; 29 | std::ifstream input_file (argv[1], std::ios::ate | std::ios::binary); 30 | if (input_file.is_open()){ 31 | 32 | std::streampos size = input_file.tellg(); 33 | char *buffer = new char[size]; 34 | unsigned char *temp = new unsigned char[3]; 35 | input_file.seekg(0, std::ios::beg); 36 | input_file.read(buffer, size); 37 | 38 | int j = 0; 39 | for (int i = 0; i < size; i++){ 40 | temp[j++] = buffer[i] & 0xFF; 41 | if (j == 3){ 42 | j = 0; 43 | encoded += base64_encoding(temp); 44 | temp = new unsigned char[3]; 45 | } 46 | } 47 | 48 | if (int(size)%3) { 49 | for (int i = 0; i < 3 - int(size)%3; i++) 50 | temp[3-i] = 0; 51 | encoded += base64_encoding(temp); 52 | for (int i = 0; i < 3 - int(size)%3; i++) 53 | encoded += '='; 54 | } 55 | 56 | delete[] buffer; 57 | std::ofstream output_file ("encoded_input"); 58 | output_file << encoded; 59 | input_file.close(); 60 | output_file.close(); 61 | } else{ 62 | std::cout << "Cannot open the given file :/" << std::endl; 63 | return -1; 64 | } 65 | return 0; 66 | } -------------------------------------------------------------------------------- /Conway's Game Of Life/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/2arian3/Cool-Programming-Challenges/9455aee7adfdd1f8eddf8c6243f8c6837edbda5d/Conway's Game Of Life/.DS_Store -------------------------------------------------------------------------------- /Conway's Game Of Life/ConwaysGameOfLife.py: -------------------------------------------------------------------------------- 1 | ''' Conway's game of life simply visualized by python. ''' 2 | 3 | import numpy as np 4 | import matplotlib.pyplot as plt 5 | import matplotlib.cm as cm 6 | 7 | class World: 8 | def __init__(self, size): 9 | self.board = np.random.randint(2, size = (size, size)) 10 | ''' Animating the board.''' 11 | def start(self): 12 | image = None 13 | started = False 14 | plt.title("Conway's Game Of Life") 15 | while self.board.max(): 16 | if not started: 17 | plt.ion() 18 | image = plt.imshow(self.board, cm.gray) 19 | started = True 20 | else: 21 | image.set_data(self.board) 22 | self.board = rules(self.board) 23 | plt.pause(0.1) 24 | 25 | ''' Counting the neighboirs of each cell. 26 | returns an array containing the number of neighbors of each cell.''' 27 | def countingNeighbors(board): 28 | return (board[:-2, :-2] + board[:-2, 1:-1] + board[:-2, 2:] 29 | + board[1:-1, :-2] + board[1:-1, 2:] + board[2:, :-2] + board[2:, 1:-1] + board[2:, 2:]) 30 | 31 | ''' Applying the rules on the cells.''' 32 | def rules(board): 33 | newBoard = np.zeros(board.shape) 34 | neighbors = countingNeighbors(board) 35 | survivors = ((neighbors == 2) | (neighbors == 3)) & (board[1:-1, 1:-1] == 1) 36 | births = (neighbors == 3) & (board[1:-1, 1:-1] == 0) 37 | newBoard[1:-1,1:-1][births | survivors] = 1 38 | return newBoard 39 | 40 | def main(): 41 | SIZE = 64 42 | world = World(SIZE) 43 | world.start() 44 | 45 | if __name__ == '__main__': 46 | main() -------------------------------------------------------------------------------- /Conway's Game Of Life/README.md: -------------------------------------------------------------------------------- 1 | ## Conway's game of life 2 | Game of life is a cellular automation created by mathematician John Horton Conway in 1970. 3 | This life simulates the life of some cells based on three simple rules: 4 | - Any live cell with two or three live neighbours survives. 5 | - Any dead cell with three live neighbours becomes a live cell. 6 | - All other live cells die in the next generation. Similarly, all other dead cells stay dead. 7 | 8 | 9 | A sample for the simulation on a 64 by 64 board. 10 | 11 | ![example](https://user-images.githubusercontent.com/49697930/88404160-be771680-cde2-11ea-8c29-7e8c64f55925.gif) 12 | -------------------------------------------------------------------------------- /Conway's Game Of Life/requirements.txt: -------------------------------------------------------------------------------- 1 | numpy 2 | matplotlib -------------------------------------------------------------------------------- /Sorting Algorithms/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/2arian3/Cool-Programming-Challenges/9455aee7adfdd1f8eddf8c6243f8c6837edbda5d/Sorting Algorithms/.DS_Store -------------------------------------------------------------------------------- /Sorting Algorithms/BubbleSort.py: -------------------------------------------------------------------------------- 1 | import matplotlib.pyplot as plt 2 | import matplotlib.animation as an 3 | from DatasetGenerator import get_dataset 4 | 5 | swaps = 0 6 | fig, ax = plt.subplots() 7 | ax.set_title('Bubble Sort') 8 | numberOfSwaps = ax.text(0.01, 0.95, "", transform=ax.transAxes) 9 | array = get_dataset() 10 | bars = ax.bar(range(len(array)), array, color='black') 11 | 12 | def bubbleSort(array): 13 | for i in range(len(array)-1): 14 | for j in range(i+1, len(array)): 15 | if array[i] > array[j]: 16 | array[i], array[j] = array[j], array[i] 17 | yield array 18 | 19 | def update(array, bars): 20 | global swaps 21 | for bar, val in zip(bars, array): 22 | bar.set_height(val) 23 | swaps += 1 24 | numberOfSwaps.set_text("Swaps: {}".format(swaps)) 25 | 26 | anim = an.FuncAnimation(fig, func=update, 27 | fargs=(bars, ), frames=bubbleSort(array), interval=1, 28 | repeat=False) 29 | plt.show() 30 | -------------------------------------------------------------------------------- /Sorting Algorithms/CountingSort.py: -------------------------------------------------------------------------------- 1 | import matplotlib.pyplot as plt 2 | import matplotlib.animation as an 3 | from DatasetGenerator import get_dataset 4 | 5 | swaps = 0 6 | fig, ax = plt.subplots() 7 | ax.set_title('Counting Sort') 8 | numberOfSwaps = ax.text(0.01, 0.95, "", transform=ax.transAxes) 9 | array = get_dataset() 10 | bars = ax.bar(range(len(array)), array, color='black') 11 | 12 | def countingSort(array): 13 | temp = array.copy() 14 | counter = [0] * (max(array) + 1) 15 | for number in array: 16 | counter[number] += 1 17 | for i in range(1, len(counter)): 18 | counter[i] += counter[i-1] 19 | for number in temp: 20 | array[counter[number]-1] = number 21 | counter[number] -= 1 22 | yield array 23 | 24 | def update(array, bars): 25 | global swaps 26 | for bar, val in zip(bars, array): 27 | bar.set_height(val) 28 | swaps += 1 29 | numberOfSwaps.set_text("Swaps: {}".format(swaps)) 30 | 31 | anim = an.FuncAnimation(fig, func=update, 32 | fargs=(bars, ), frames=countingSort(array), interval=1, 33 | repeat=False) 34 | plt.show() 35 | -------------------------------------------------------------------------------- /Sorting Algorithms/DatasetGenerator.py: -------------------------------------------------------------------------------- 1 | import os 2 | import pickle 3 | import numpy as np 4 | 5 | 6 | def get_dataset(size=100, max_value=100): 7 | dataset = None 8 | dataset_dir = f'{os.getcwd()}/dataset' 9 | 10 | if not os.path.isfile(dataset_dir): 11 | with open(dataset_dir, 'wb') as file: 12 | dataset = np.random.randint(max_value, size=(size)) 13 | pickle.dump(dataset, file) 14 | print('Dataset generated.') 15 | else: 16 | with open(dataset_dir, 'rb') as file: 17 | dataset = pickle.load(file) 18 | print('Dataset loaded.') 19 | 20 | return dataset 21 | -------------------------------------------------------------------------------- /Sorting Algorithms/HeapSort.py: -------------------------------------------------------------------------------- 1 | import matplotlib.pyplot as plt 2 | import matplotlib.animation as an 3 | from DatasetGenerator import get_dataset 4 | 5 | swaps = 0 6 | fig, ax = plt.subplots() 7 | ax.set_title('Heap Sort') 8 | numberOfSwaps = ax.text(0.01, 0.95, "", transform=ax.transAxes) 9 | array = get_dataset() 10 | bars = ax.bar(range(len(array)), array, color='black') 11 | 12 | def max_heapify(array, i, size): 13 | left, right = 2 * (i+1) - 1, 2 * (i+1) 14 | largest = i 15 | if left < size and array[i] < array[left]: 16 | largest = left 17 | if right < size and array[largest] < array[right]: 18 | largest = right 19 | if largest != i: 20 | array[largest], array[i] = array[i], array[largest] 21 | max_heapify(array, largest, size) 22 | 23 | def build_max_heap(array): 24 | n = len(array) 25 | for i in range(n // 2, -1, -1): 26 | max_heapify(array, i, n) 27 | 28 | def heap_sort(array): 29 | n = len(array) 30 | build_max_heap(array) 31 | for i in range(n, 1, -1): 32 | n -= 1 33 | array[i-1], array[0] = array[0], array[i-1] 34 | yield array 35 | max_heapify(array, 0, n) 36 | 37 | def update(array, bars): 38 | global swaps 39 | for bar, val in zip(bars, array): 40 | bar.set_height(val) 41 | swaps += 1 42 | numberOfSwaps.set_text("Swaps: {}".format(swaps)) 43 | 44 | anim = an.FuncAnimation(fig, func=update, 45 | fargs=(bars, ), frames=heap_sort(array), interval=1, 46 | repeat=False) 47 | plt.show() 48 | -------------------------------------------------------------------------------- /Sorting Algorithms/InsertionSort.py: -------------------------------------------------------------------------------- 1 | import matplotlib.pyplot as plt 2 | import matplotlib.animation as an 3 | from DatasetGenerator import get_dataset 4 | 5 | swaps = 0 6 | fig, ax = plt.subplots() 7 | ax.set_title('Insertion Sort') 8 | numberOfSwaps = ax.text(0.01, 0.95, "", transform=ax.transAxes) 9 | array = get_dataset() 10 | bars = ax.bar(range(len(array)), array, color='black') 11 | 12 | def insertionSort(array): 13 | for i in range(1, len(array)): 14 | key = array[i] 15 | j = i-1 16 | while j >= 0 and array[j] > key: 17 | array[j+1] = array[j] 18 | j -= 1 19 | yield array 20 | array[j+1] = key 21 | 22 | def update(array, bars): 23 | global swaps 24 | for bar, val in zip(bars, array): 25 | bar.set_height(val) 26 | swaps += 1 27 | numberOfSwaps.set_text("Swaps: {}".format(swaps)) 28 | 29 | anim = an.FuncAnimation(fig, func=update, 30 | fargs=(bars, ), frames=insertionSort(array), interval=1, 31 | repeat=False) 32 | plt.show() 33 | -------------------------------------------------------------------------------- /Sorting Algorithms/MergeSort.py: -------------------------------------------------------------------------------- 1 | import matplotlib.pyplot as plt 2 | import matplotlib.animation as an 3 | from DatasetGenerator import get_dataset 4 | 5 | swaps = 0 6 | fig, ax = plt.subplots() 7 | ax.set_title('Merge Sort') 8 | numberOfSwaps = ax.text(0.01, 0.95, "", transform=ax.transAxes) 9 | array = get_dataset() 10 | bars = ax.bar(range(len(array)), array, color='black') 11 | 12 | def merge(A, start, mid, end): 13 | merged = [] 14 | left = start 15 | right = mid + 1 16 | 17 | while left <= mid and right <= end: 18 | if array[left] < array[right]: 19 | merged.append(array[left]) 20 | left += 1 21 | else: 22 | merged.append(array[right]) 23 | right += 1 24 | 25 | while left <= mid: 26 | merged.append(array[left]) 27 | left += 1 28 | 29 | while right <= end: 30 | merged.append(array[right]) 31 | right += 1 32 | 33 | for i, num in enumerate(merged): 34 | array[start + i] = num 35 | yield array 36 | 37 | def mergeSort(array, start, end): 38 | if end <= start: 39 | return 40 | mid = start + ((end - start + 1) // 2) - 1 41 | yield from mergeSort(array, start, mid) 42 | yield from mergeSort(array, mid + 1, end) 43 | yield from merge(array, start, mid, end) 44 | yield array 45 | 46 | def update(array, bars): 47 | global swaps 48 | for bar, val in zip(bars, array): 49 | bar.set_height(val) 50 | swaps += 1 51 | numberOfSwaps.set_text("Swaps: {}".format(swaps)) 52 | 53 | anim = an.FuncAnimation(fig, func=update, 54 | fargs=(bars, ), frames=mergeSort(array, 0, len(array)-1), interval=1, 55 | repeat=False) 56 | plt.show() 57 | -------------------------------------------------------------------------------- /Sorting Algorithms/QuickSort.py: -------------------------------------------------------------------------------- 1 | import matplotlib.pyplot as plt 2 | import matplotlib.animation as an 3 | from DatasetGenerator import get_dataset 4 | 5 | swaps = 0 6 | fig, ax = plt.subplots() 7 | ax.set_title('Quick Sort') 8 | numberOfSwaps = ax.text(0.01, 0.95, "", transform=ax.transAxes) 9 | array = get_dataset() 10 | bars = ax.bar(range(len(array)), array, color='black') 11 | 12 | def quickSort(array, start, end): 13 | if end <= start: 14 | yield array 15 | return 16 | pivot = array[end] 17 | i = start - 1 18 | for j in range(start, end): 19 | if array[j] < pivot: 20 | i += 1 21 | array[i], array[j] = array[j], array[i] 22 | yield array 23 | i += 1 24 | array[i], array[end] = array[end], array[i] 25 | yield from quickSort(array, start, i - 1) 26 | yield from quickSort(array, i + 1, end) 27 | 28 | def update(array, bars): 29 | global swaps 30 | for bar, val in zip(bars, array): 31 | bar.set_height(val) 32 | swaps += 1 33 | numberOfSwaps.set_text("Swaps: {}".format(swaps)) 34 | 35 | anim = an.FuncAnimation(fig, func=update, 36 | fargs=(bars, ), frames=quickSort(array, 0, len(array)-1), interval=1, 37 | repeat=False) 38 | plt.show() 39 | -------------------------------------------------------------------------------- /Sorting Algorithms/README.md: -------------------------------------------------------------------------------- 1 | ## Different Sorting Algorithms 2 | Just tried to visualize the most common sorting algorithms using python.
3 | Here are the results on a specific array with 100 elements.
4 | ### Bubble Sort 5 | ![Bubble Sort](https://user-images.githubusercontent.com/49697930/90292033-5920bd80-de96-11ea-81cf-4ead3980e190.gif) 6 | 7 | ### Insertion Sort 8 | ![Insertion Sort](https://user-images.githubusercontent.com/49697930/90292085-76558c00-de96-11ea-83be-8c2f25be4329.gif) 9 | 10 | ### Selection Sort 11 | ![Selection Sort](https://user-images.githubusercontent.com/49697930/90292142-99803b80-de96-11ea-9a48-e6a74368af3f.gif) 12 | 13 | ### Merge Sort 14 | ![Merge Sort](https://user-images.githubusercontent.com/49697930/90292174-abfa7500-de96-11ea-83a3-adb0c74a2aa8.gif) 15 | 16 | ### Quick Sort 17 | ![Quick Sort](https://user-images.githubusercontent.com/49697930/90292193-b452b000-de96-11ea-9cc5-a8af96894057.gif) 18 | 19 | 20 | -------------------------------------------------------------------------------- /Sorting Algorithms/SelectionSort.py: -------------------------------------------------------------------------------- 1 | import matplotlib.pyplot as plt 2 | import matplotlib.animation as an 3 | from DatasetGenerator import get_dataset 4 | 5 | swaps = 0 6 | fig, ax = plt.subplots() 7 | ax.set_title('Selection Sort') 8 | numberOfSwaps = ax.text(0.01, 0.95, "", transform=ax.transAxes) 9 | array = get_dataset() 10 | bars = ax.bar(range(len(array)), array, color='black') 11 | 12 | def selectionSort(array): 13 | for i in range(len(array)): 14 | for j in range(i+1, len(array)): 15 | if array[i] > array[j]: 16 | array[i], array[j] = array[j], array[i] 17 | yield array 18 | 19 | def update(array, bars): 20 | global swaps 21 | for bar, val in zip(bars, array): 22 | bar.set_height(val) 23 | swaps += 1 24 | numberOfSwaps.set_text("Swaps: {}".format(swaps)) 25 | 26 | anim = an.FuncAnimation(fig, func=update, 27 | fargs=(bars, ), frames=selectionSort(array), interval=1, 28 | repeat=False) 29 | plt.show() 30 | -------------------------------------------------------------------------------- /Sorting Algorithms/requirements.txt: -------------------------------------------------------------------------------- 1 | numpy 2 | matplotlib 3 | -------------------------------------------------------------------------------- /Tetris/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/2arian3/Cool-Programming-Challenges/9455aee7adfdd1f8eddf8c6243f8c6837edbda5d/Tetris/.DS_Store -------------------------------------------------------------------------------- /Tetris/README.md: -------------------------------------------------------------------------------- 1 | # Tetris 2 | Tetris (Russian: Тетрис [ˈtɛtrʲɪs]) is a tile-matching video game created by Russian software engineer Alexey Pajitnov in 1984. It has been published by several companies, most prominently during a dispute over the appropriation of the game's rights in the late 1980s. After a significant period of publication by Nintendo, the rights reverted to Pajitnov in 1996, who co-founded The Tetris Company with Henk Rogers to manage Tetris licensing.[wikipedia] 3 | This is my second project using pygame and it was so fun to do :) 4 | You can easily play this one in your computer if you have pygame installed on your device. 5 | If your are a mac user, due to MacOS incompatibilities with pygame, you should try the pygame 2.0.0.dev8 version or higher on your laptop. 6 | I also recommend you to visit this [link](https://www.dailydot.com/parsec/tetris-game-facts/) and check out 25 interesting facts about this popular and simple game. 7 | HOPE YOU ENJOY! 8 | 9 | ![Tetris](https://user-images.githubusercontent.com/49697930/93031409-c06d9100-f63f-11ea-841f-3b6629d6d3af.gif) 10 | -------------------------------------------------------------------------------- /Tetris/__pycache__/shapes.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/2arian3/Cool-Programming-Challenges/9455aee7adfdd1f8eddf8c6243f8c6837edbda5d/Tetris/__pycache__/shapes.cpython-37.pyc -------------------------------------------------------------------------------- /Tetris/main.py: -------------------------------------------------------------------------------- 1 | import pygame 2 | from shapes import shapes, colors 3 | 4 | pygame.init() 5 | screen_info = pygame.display.Info() 6 | 7 | #Constants 8 | FPS = 120 9 | WIDTH = 800 10 | HEIGHT = 800 if screen_info.current_h > 1080 else 600 11 | BLOCK_SIZE = 30 if screen_info.current_h > 1080 else 20 12 | BOARD_WIDTH = 10 * BLOCK_SIZE 13 | BOARD_HEIGHT = 20 * BLOCK_SIZE 14 | BACKGROUND_COLOR = (0, 0, 0) 15 | BORDER_COLOR = (128, 128, 128) 16 | TEXT_COLOR = (255, 0, 0) 17 | FONT1 = pygame.font.Font('requiries/FFF phantom 01.ttf', 20) 18 | FONT2 = pygame.font.Font('requiries/FFF phantom 01.ttf', 15) 19 | FONT3 = pygame.font.Font('requiries/FFF phantom 01.ttf', 10) 20 | 21 | 22 | #Texts used in the game 23 | tetris = FONT1.render('Tetris', True, TEXT_COLOR) 24 | next_shape = FONT2.render('next shape', True, TEXT_COLOR) 25 | first_menu_text = FONT1.render('To start the game, press any button', True, TEXT_COLOR) 26 | play_again = FONT2.render('press any button to play again', True, TEXT_COLOR) 27 | producer = FONT3.render('produced by arian boukani', True, TEXT_COLOR) 28 | version = FONT3.render('version 1.0', True, TEXT_COLOR) 29 | you_lost = FONT2.render('you lost :(', True, TEXT_COLOR) 30 | score_text = FONT2.render('score', True, TEXT_COLOR) 31 | tip = FONT2.render('TIP : to rotate the shape, press up key', True, TEXT_COLOR) 32 | 33 | score = 0 34 | start_x = (WIDTH - BOARD_WIDTH) // 2 35 | start_y = (HEIGHT - BOARD_HEIGHT) // 2 36 | 37 | #Class for each shape used in the game containing their attributes 38 | class Shape: 39 | 40 | def __init__(self, column, row, shape): 41 | self.x = column 42 | self.y = row 43 | self.shape = shape 44 | self.color = colors[shapes.index(shape)] 45 | self.rotation = 0 46 | 47 | #After each next shape checks the losing condition 48 | def lost(locked_positions): 49 | for locked_position in locked_positions: 50 | if locked_position[1] <= 0: 51 | return True 52 | return False 53 | 54 | #Creates each shape based on the shapes list in shapes.py module 55 | def shape_handling(shape): 56 | block_positions = [] 57 | s = shape.shape[shape.rotation % len(shape.shape)] 58 | for i, line in enumerate(s): 59 | row = list(line) 60 | for j, column in enumerate(row): 61 | if column == '*': 62 | block_positions.append((shape.x + j - 2, shape.y + i - 4)) 63 | return block_positions 64 | 65 | #Checks whether the next move is legal or not 66 | def valid_move(shape, cell_colors, locked_positions): 67 | valid_positions = [[(j, i) for j in range(10) if cell_colors[i][j] == BACKGROUND_COLOR] for i in range(20)] 68 | shape_positions = shape_handling(shape) 69 | for pos in shape_positions: 70 | if pos not in valid_positions : 71 | if pos[0] < 0 or pos[0] >= 10 or pos[1] >= 20 or pos in locked_positions: 72 | return False 73 | return True 74 | 75 | #Draws the first menu using pygame modules 76 | def draw_first_menu(): 77 | window.blit(tetris, (start_x + 5*BLOCK_SIZE - tetris.get_width() // 2, 10)) 78 | window.blit(first_menu_text, (WIDTH // 2 - first_menu_text.get_width() // 2, HEIGHT // 2 - first_menu_text.get_height() // 2)) 79 | window.blit(tip, (WIDTH // 2 - tip.get_width() // 2, HEIGHT // 2 - first_menu_text.get_height() // 2 + tip.get_height() + 10)) 80 | window.blit(producer, (WIDTH // 2 - producer.get_width() // 2, HEIGHT - 2 * producer.get_height())) 81 | window.blit(version, (WIDTH // 2 - version.get_width() // 2, HEIGHT - version.get_height())) 82 | pygame.display.update() 83 | 84 | # draws each frame of the game 85 | def draw_game_menu(cell_colors): 86 | window.fill(BACKGROUND_COLOR) 87 | window.blit(tetris, (start_x + 5*BLOCK_SIZE - tetris.get_width() // 2, 10)) 88 | for i in range(20): 89 | for j in range(10): 90 | pygame.draw.rect(window, cell_colors[i][j], (start_x + j*BLOCK_SIZE, start_y + i*BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE), 0) 91 | pygame.draw.rect(window, TEXT_COLOR, (start_x, start_y, 10*BLOCK_SIZE, 20*BLOCK_SIZE), 3) 92 | for i in range(1, 20): 93 | pygame.draw.line(window, BORDER_COLOR, (start_x, start_y + i*BLOCK_SIZE), (start_x + 10*BLOCK_SIZE, start_y + i*BLOCK_SIZE)) 94 | for i in range(1, 10): 95 | pygame.draw.line(window, BORDER_COLOR, (start_x + i*BLOCK_SIZE, start_y), (start_x + i*BLOCK_SIZE, start_y + 20*BLOCK_SIZE)) 96 | window.blit(producer, (WIDTH // 2 - producer.get_width() // 2, HEIGHT - 2 * producer.get_height())) 97 | window.blit(version, (WIDTH // 2 - version.get_width() // 2, HEIGHT - version.get_height())) 98 | #Returns a random shape 99 | def get_shape(): 100 | import random 101 | return Shape(5, 0, random.choice(shapes)) 102 | 103 | #Handling the next shape panel 104 | def draw_next_shape(shape): 105 | window.blit(next_shape, (BOARD_WIDTH + ((WIDTH - BOARD_WIDTH + start_x)//2 - next_shape.get_width()//2), start_y)) 106 | x = start_x + 11*BLOCK_SIZE 107 | y = start_y + BLOCK_SIZE 108 | for i, line in enumerate(shape.shape[0]): 109 | row = list(line) 110 | for j, column in enumerate(row): 111 | if column is '*': 112 | pygame.draw.rect(window, shape.color, (x + j*BLOCK_SIZE, y + i*BLOCK_SIZE, BLOCK_SIZE-1, BLOCK_SIZE-1), 0) 113 | 114 | #Handling the score board panel 115 | def draw_score_panel(): 116 | window.blit(score_text, (start_x // 2 - score_text.get_width() // 2, start_y)) 117 | s = FONT2.render(str(score), True, TEXT_COLOR) 118 | window.blit(s, (start_x // 2 - s.get_width() // 2, start_y + BLOCK_SIZE)) 119 | 120 | #Generates each cell color after each frame of the game based on locked positions 121 | def generate_cell_colors(locked_positions): 122 | cell_colors = [[BACKGROUND_COLOR for _ in range(10)] for _ in range(20)] 123 | for i in range(20): 124 | for j in range(10): 125 | if (j, i) in locked_positions: 126 | cell_colors[i][j] = locked_positions[(j, i)] 127 | return cell_colors 128 | 129 | #Checks each row of the board. if it is full, returns the indices of the full rows 130 | def full_rows(cell_colors): 131 | full_rows_indices = [] 132 | for line in cell_colors: 133 | if BACKGROUND_COLOR not in line: 134 | full_rows_indices.append(cell_colors.index(line)) 135 | return full_rows_indices 136 | 137 | #Cleans the full row and shifts the upper rows down 138 | def clean_row(cell_colors, index, locked_positions): 139 | global score 140 | score += 10 141 | updated = dict(((pos[0], pos[1]+1), color) for (pos, color) in locked_positions.items() if pos[1] < index) 142 | to_be_removed = [cell for cell in locked_positions if cell[1] <= index] 143 | cell_colors.pop(index) 144 | new_cells = [BACKGROUND_COLOR for _ in range(10)] 145 | cell_colors.reverse() 146 | cell_colors.append(new_cells) 147 | cell_colors.reverse() 148 | for cell in to_be_removed: 149 | try: 150 | del locked_positions[cell] 151 | except: 152 | pass 153 | locked_positions.update(updated) 154 | 155 | #Main menu 156 | def main(): 157 | global score 158 | score = 0 159 | done = False 160 | #locked_positions contains the colors and the positions of the not moving shapes 161 | locked_positions = dict() 162 | cell_colors = generate_cell_colors(locked_positions) 163 | running = True 164 | next_move = False 165 | current_shape = get_shape() 166 | next_shape = get_shape() 167 | clock = pygame.time.Clock() 168 | fall_time = 0 169 | level_time = 0 170 | fall_speed = 0.3 171 | draw_game_menu(cell_colors) 172 | 173 | while running: 174 | 175 | cell_colors = generate_cell_colors(locked_positions) 176 | fall_time += clock.get_rawtime() 177 | level_time += clock.get_rawtime() 178 | clock.tick(FPS) 179 | #increasing the speed of shape falling to make the game more realistic 180 | if level_time / 1000 > 4: 181 | level_time = 0 182 | if fall_speed > 0.15: 183 | fall_speed -= 0.005 184 | 185 | if fall_time / 500 >= fall_speed: 186 | fall_time = 0 187 | current_shape.y += 1 188 | if not (valid_move(current_shape, cell_colors, locked_positions)) and current_shape.y > 0: 189 | current_shape.y -= 1 190 | next_move = True 191 | for event in pygame.event.get(): 192 | #Handling the pressed key 193 | if event.type == pygame.QUIT: 194 | running = False 195 | done = True 196 | elif event.type == pygame.KEYDOWN: 197 | if event.key == pygame.K_LEFT: 198 | current_shape.x -= 1 199 | if not valid_move(current_shape, cell_colors, locked_positions): 200 | current_shape.x += 1 201 | 202 | elif event.key == pygame.K_RIGHT: 203 | current_shape.x += 1 204 | if not valid_move(current_shape, cell_colors, locked_positions): 205 | current_shape.x -= 1 206 | 207 | elif event.key == pygame.K_DOWN: 208 | current_shape.y += 1 209 | if not valid_move(current_shape, cell_colors, locked_positions): 210 | current_shape.y -= 1 211 | 212 | elif event.key == pygame.K_UP: 213 | current_shape.rotation = current_shape.rotation + 1 % len(current_shape.shape) 214 | if not valid_move(current_shape, cell_colors, locked_positions): 215 | current_shape.rotation = current_shape.rotation - 1 % len(current_shape.shape) 216 | shape_positions = shape_handling(current_shape) 217 | for x, y in shape_positions: 218 | if y >= 0: 219 | cell_colors[y][x] = current_shape.color 220 | if next_move: 221 | for pos in shape_positions: 222 | locked_positions[pos] = current_shape.color 223 | current_shape = next_shape 224 | next_shape = get_shape() 225 | next_move = False 226 | full_rows_indices = full_rows(cell_colors) 227 | if len(full_rows_indices): 228 | for row in full_rows_indices: 229 | clean_row(cell_colors, row, locked_positions) 230 | if lost(locked_positions): 231 | running = False 232 | draw_game_menu(cell_colors) 233 | draw_next_shape(next_shape) 234 | draw_score_panel() 235 | pygame.display.update() 236 | if not done: 237 | window.blit(you_lost, (start_x // 2 - you_lost.get_width() // 2, start_y + BOARD_HEIGHT // 2 - you_lost.get_height())) 238 | window.blit(you_lost, (BOARD_WIDTH + ((WIDTH - BOARD_WIDTH + start_x)//2 - you_lost.get_width()//2), start_y + BOARD_HEIGHT // 2 - you_lost.get_height())) 239 | window.blit(play_again, (WIDTH // 2 - play_again.get_width() // 2, start_y + 21 * BLOCK_SIZE)) 240 | pygame.display.update() 241 | return done 242 | 243 | #First menu graphics 244 | def first_menu(): 245 | draw_first_menu() 246 | running = True 247 | done = False 248 | while running: 249 | if done: 250 | return 251 | for event in pygame.event.get(): 252 | if event.type == pygame.QUIT: 253 | running = False 254 | elif event.type == pygame.KEYDOWN: 255 | done = main() 256 | 257 | window = pygame.display.set_mode((WIDTH, HEIGHT)) 258 | window.fill(BACKGROUND_COLOR) 259 | pygame.display.set_caption('TETRIS') 260 | 261 | if __name__ == '__main__': 262 | pygame.mixer.music.load('requiries/Tetris.mp3') 263 | pygame.mixer.music.play(-1) 264 | first_menu() 265 | 266 | pygame.display.quit() 267 | quit() -------------------------------------------------------------------------------- /Tetris/requirements.txt: -------------------------------------------------------------------------------- 1 | pygame -------------------------------------------------------------------------------- /Tetris/requiries/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/2arian3/Cool-Programming-Challenges/9455aee7adfdd1f8eddf8c6243f8c6837edbda5d/Tetris/requiries/.DS_Store -------------------------------------------------------------------------------- /Tetris/requiries/FFF Phantom 01.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/2arian3/Cool-Programming-Challenges/9455aee7adfdd1f8eddf8c6243f8c6837edbda5d/Tetris/requiries/FFF Phantom 01.ttf -------------------------------------------------------------------------------- /Tetris/requiries/Tetris.mp3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/2arian3/Cool-Programming-Challenges/9455aee7adfdd1f8eddf8c6243f8c6837edbda5d/Tetris/requiries/Tetris.mp3 -------------------------------------------------------------------------------- /Tetris/shapes.py: -------------------------------------------------------------------------------- 1 | #Shapes 2 | L = [['.....', 3 | '...*.', 4 | '.***.', 5 | '.....', 6 | '.....'], 7 | ['.....', 8 | '.*...', 9 | '.*...', 10 | '.**..', 11 | '.....'], 12 | ['.....', 13 | '.***.', 14 | '.*...', 15 | '.....', 16 | '.....'], 17 | ['.....', 18 | '..**.', 19 | '...*.', 20 | '...*.', 21 | '.....']] 22 | S = [['.....', 23 | '..**.', 24 | '.**..', 25 | '.....', 26 | '.....'], 27 | ['.....', 28 | '.*...', 29 | '.**..', 30 | '..*..', 31 | '.....']] 32 | I = [['.....', 33 | '..*..', 34 | '..*..', 35 | '..*..', 36 | '..*..'], 37 | ['.....', 38 | '****.', 39 | '.....', 40 | '.....', 41 | '.....']] 42 | J = [['.....', 43 | '..*..', 44 | '..*..', 45 | '.**..', 46 | '.....'], 47 | ['.....', 48 | '.*...', 49 | '.***.', 50 | '.....', 51 | '.....'], 52 | ['.....', 53 | '.**..', 54 | '.*...', 55 | '.*...'], 56 | ['.....', 57 | '.***.', 58 | '...*.', 59 | '.....', 60 | '.....']] 61 | T = [['.....', 62 | '.***.', 63 | '..*..', 64 | '.....', 65 | '.....'], 66 | ['.....', 67 | '..*..', 68 | '.**..', 69 | '..*..', 70 | '.....'], 71 | ['.....', 72 | '..*..', 73 | '.***.', 74 | '.....', 75 | '.....'], 76 | ['.....', 77 | '.*...', 78 | '.**..', 79 | '.*...', 80 | '.....']] 81 | O = [['.....', 82 | '.**..', 83 | '.**..', 84 | '.....', 85 | '.....']] 86 | Z = [['.....', 87 | '.**..', 88 | '..**.', 89 | '.....', 90 | '.....'], 91 | ['.....', 92 | '..*..', 93 | '.**..', 94 | '.*...', 95 | '.....']] 96 | shapes = [S, Z, I, O, J, L, T] 97 | # Green Red Light Blue Yello Orange Blue Violet 98 | colors = [(110, 234, 71), (221, 46, 33), (108, 236, 238), (241, 238, 79), (229, 163, 57), (0, 30, 230), (145, 43, 231)] -------------------------------------------------------------------------------- /Tic-Tac-Toe/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/2arian3/Cool-Programming-Challenges/9455aee7adfdd1f8eddf8c6243f8c6837edbda5d/Tic-Tac-Toe/.DS_Store -------------------------------------------------------------------------------- /Tic-Tac-Toe/README.md: -------------------------------------------------------------------------------- 1 | ## TIC-TAC-TOE 2 | Popular tic tac toe game with simple AI developed with pygame and pygame_widgets. 3 | This is my first try in using pygame. 4 | Maybe i would add the multiplaying feature in the future. 5 | 6 | The rules of the game are simple and clear so there is no need to mention them ;) 7 | 8 | Hope you would enjoy playing this one. 9 | 10 | ![tic tac toe](https://user-images.githubusercontent.com/49697930/89136346-783f5700-d548-11ea-9265-d463d1057a6d.gif) 11 | -------------------------------------------------------------------------------- /Tic-Tac-Toe/__pycache__/logic.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/2arian3/Cool-Programming-Challenges/9455aee7adfdd1f8eddf8c6243f8c6837edbda5d/Tic-Tac-Toe/__pycache__/logic.cpython-37.pyc -------------------------------------------------------------------------------- /Tic-Tac-Toe/graphics.py: -------------------------------------------------------------------------------- 1 | import time 2 | import logic 3 | import pygame 4 | from pygame_widgets import Button 5 | pygame.init() 6 | 7 | '''colors''' 8 | # R G B 9 | BLACK = ( 0, 0, 0) 10 | RED = (255, 0, 0) 11 | GREEN = (124, 209, 65) 12 | DARK_BLUE = ( 16, 34, 60) 13 | PINK = (255, 20, 147) 14 | BLUE = (152, 244, 245) 15 | YELLOW = (248, 241, 87) 16 | 17 | '''constants''' 18 | USER = '' 19 | CPU = '' 20 | SCREEN_WIDTH = 1000 21 | SCREEN_HEIGHT = 1000 22 | BLOCK_SIZE = 200 23 | START_X = (SCREEN_WIDTH - 3 * BLOCK_SIZE) // 2 24 | START_Y = (SCREEN_HEIGHT - 3 * BLOCK_SIZE) // 2 25 | BOARD_CORNERS = [(START_X, START_Y), (START_X + 3*BLOCK_SIZE, START_Y + 3*BLOCK_SIZE)] 26 | BACKGROUND_COLOR = DARK_BLUE 27 | X_COLOR = BLUE 28 | O_COLOR = PINK 29 | BOARD_COLOR = YELLOW 30 | GAME_FONT_40 = pygame.font.SysFont('Debussy.ttf', 40) 31 | GAME_FONT_30 = pygame.font.SysFont('Debussy.ttf', 30) 32 | 33 | '''texts''' 34 | header = GAME_FONT_40.render('TIC TAC TOE', True, BLUE, BACKGROUND_COLOR) 35 | choice = GAME_FONT_30.render('Choose between x and o !', True, PINK, BACKGROUND_COLOR) 36 | hint = GAME_FONT_30.render('HINT : In order to reset the board in the game press return.', True, PINK, BACKGROUND_COLOR) 37 | userTurn = GAME_FONT_30.render('It is your turn to move', True, BLUE, BACKGROUND_COLOR) 38 | cpuTurn = GAME_FONT_30.render('It is cpu\'s turn to move', True, BLUE, BACKGROUND_COLOR) 39 | youWon = GAME_FONT_30.render('YOU WON!', True, BLUE, BACKGROUND_COLOR) 40 | youLost = GAME_FONT_30.render('YOU LOST:(', True, BLUE, BACKGROUND_COLOR) 41 | tie = GAME_FONT_30.render('TIE...', True, BLUE, BACKGROUND_COLOR) 42 | restart = GAME_FONT_30.render('Wanna play? press return.', True, BLUE, BACKGROUND_COLOR) 43 | 44 | '''returns true if the given position is in the board.''' 45 | def inTheBoard(position): 46 | top_left, bottom_right = BOARD_CORNERS 47 | return top_left[0] <= position[0] <= bottom_right[0] and top_left[1] <= position[1] <= bottom_right[1] 48 | 49 | '''drawing the board based on the constants.''' 50 | def drawBoard(): 51 | pygame.draw.line(screen, BOARD_COLOR, (START_X, START_Y), (START_X + 3*BLOCK_SIZE, START_Y), 3) 52 | pygame.draw.line(screen, BOARD_COLOR, (START_X, START_Y), (START_X, START_Y + 3*BLOCK_SIZE), 3) 53 | pygame.draw.line(screen, BOARD_COLOR, (START_X + 3*BLOCK_SIZE, START_Y), (START_X + 3*BLOCK_SIZE, START_Y + 3*BLOCK_SIZE), 3) 54 | pygame.draw.line(screen, BOARD_COLOR, (START_X, START_Y + BLOCK_SIZE), (START_X + 3*BLOCK_SIZE, START_Y + BLOCK_SIZE), 3) 55 | pygame.draw.line(screen, BOARD_COLOR, (START_X, START_Y + 2*BLOCK_SIZE), (START_X + 3*BLOCK_SIZE, START_Y + 2*BLOCK_SIZE), 3) 56 | pygame.draw.line(screen, BOARD_COLOR, (START_X + BLOCK_SIZE, START_Y), (START_X + BLOCK_SIZE, START_Y + 3*BLOCK_SIZE), 3) 57 | pygame.draw.line(screen, BOARD_COLOR, (START_X + 2*BLOCK_SIZE, START_Y), (START_X + 2*BLOCK_SIZE, START_Y + 3*BLOCK_SIZE), 3) 58 | pygame.draw.line(screen, BOARD_COLOR, (START_X, START_Y + 3*BLOCK_SIZE), (START_X + 3*BLOCK_SIZE, START_Y + 3*BLOCK_SIZE), 3) 59 | 60 | '''clearing the screen.''' 61 | def clearTheScreen(): 62 | blank = pygame.Surface((SCREEN_WIDTH, SCREEN_HEIGHT - 100)) 63 | blank.fill(BACKGROUND_COLOR) 64 | screen.blit(blank, (0, 75)) 65 | pygame.display.update() 66 | 67 | '''clears the board on the screen.''' 68 | def resetTheBoard(): 69 | logic.board = [''] * 9 70 | blank = pygame.Surface((BLOCK_SIZE-5, BLOCK_SIZE-5)) 71 | blank.fill(BACKGROUND_COLOR) 72 | for i in range(3): 73 | for j in range(3): 74 | screen.blit(blank, (START_X + i*BLOCK_SIZE + 2, START_Y + j*BLOCK_SIZE + 2)) 75 | 76 | '''creating the players icons.''' 77 | def creatingTheIcons(): 78 | x, o = pygame.Surface((BLOCK_SIZE-5, BLOCK_SIZE-5)), pygame.Surface((BLOCK_SIZE-5, BLOCK_SIZE-5)) 79 | x.fill(BACKGROUND_COLOR) 80 | o.fill(BACKGROUND_COLOR) 81 | pygame.draw.circle(o, O_COLOR, (BLOCK_SIZE // 2, BLOCK_SIZE // 2), BLOCK_SIZE // 2 - 5, 3) 82 | pygame.draw.aaline(x, X_COLOR, (5, 5), (BLOCK_SIZE - 5, BLOCK_SIZE - 5), 3) 83 | pygame.draw.aaline(x, X_COLOR, (5, BLOCK_SIZE - 5), (BLOCK_SIZE - 5, 5), 3) 84 | return x, o 85 | 86 | '''visualizing player's move.''' 87 | def playerMove(position): 88 | legal = False 89 | playerIcon = x if USER == 'X' else o 90 | posX, posY = position 91 | posX = ((posX - START_X) // BLOCK_SIZE) * BLOCK_SIZE + START_X 92 | posY = ((posY - START_Y) // BLOCK_SIZE) * BLOCK_SIZE + START_Y 93 | j, i = (posX - START_X) // BLOCK_SIZE, (posY - START_Y) // BLOCK_SIZE 94 | if logic.placeIsFree(3*i + j): 95 | logic.board[3*i + j] = USER 96 | screen.blit(playerIcon, (posX + 2, posY + 2)) 97 | legal = True 98 | pygame.display.update() 99 | return legal 100 | 101 | '''cpu's move appears on the board.''' 102 | def cpuMove(): 103 | move = logic.cpuMove(logic.board, CPU, USER) 104 | cpuIcon = x if CPU == 'X' else o 105 | posY = move // 3 106 | posX = move % 3 107 | screen.blit(cpuIcon, (START_X + posX*BLOCK_SIZE + 2, START_Y + posY*BLOCK_SIZE + 2)) 108 | pygame.display.update() 109 | 110 | def chooseIcon(icon): 111 | global USER 112 | global CPU 113 | USER = icon 114 | CPU = 'O' if icon == 'X' else 'X' 115 | 116 | '''the intro screen.''' 117 | def intro(): 118 | choiceRect = choice.get_rect() 119 | choiceRect.center = ((SCREEN_WIDTH // 2, SCREEN_WIDTH // 2 - 100)) 120 | hintRect = hint.get_rect() 121 | hintRect.center = ((SCREEN_WIDTH // 2, SCREEN_HEIGHT - 100)) 122 | xButton = Button( 123 | screen, (SCREEN_WIDTH-50)//2-50, (SCREEN_HEIGHT-50)//2, 50, 50, text='X', 124 | fontSize=30, margin=20, 125 | font=GAME_FONT_30, 126 | textColour=PINK, 127 | inactiveColour=BACKGROUND_COLOR, 128 | pressedColour=PINK, radius=5, 129 | onClick=lambda: chooseIcon('X') 130 | ) 131 | oButton = Button( 132 | screen, (SCREEN_WIDTH-50)//2+50, (SCREEN_HEIGHT-50)//2, 50, 50, text='O', 133 | fontSize=30, margin=20, 134 | font=GAME_FONT_30, 135 | textColour=PINK, 136 | inactiveColour=BACKGROUND_COLOR, 137 | pressedColour=PINK, radius=5, 138 | onClick=lambda: chooseIcon('O') 139 | ) 140 | screen.blit(choice, choiceRect) 141 | screen.blit(hint, hintRect) 142 | while USER is '': 143 | events = pygame.event.get() 144 | for event in events: 145 | if event.type == pygame.QUIT: 146 | pygame.quit() 147 | oButton.listen(events) 148 | xButton.listen(events) 149 | oButton.draw() 150 | xButton.draw() 151 | pygame.display.update() 152 | clearTheScreen() 153 | 154 | def showTurn(player): 155 | turn = userTurn if player == USER else cpuTurn 156 | turnRect = turn.get_rect() 157 | turnRect.center = ((SCREEN_WIDTH // 2, 100)) 158 | screen.blit(turn, turnRect) 159 | pygame.display.update() 160 | 161 | def eraseTurn(): 162 | blank = pygame.Surface((SCREEN_WIDTH, 50)) 163 | blank.fill(BACKGROUND_COLOR) 164 | blankRect = blank.get_rect() 165 | blankRect.center = ((SCREEN_WIDTH // 2, 100)) 166 | screen.blit(blank, blankRect) 167 | pygame.display.update() 168 | def winningLine(winner): 169 | scenarios = { 170 | (0, 1, 2) : [(START_X, START_Y+BLOCK_SIZE//2), (START_X+3*BLOCK_SIZE, START_Y+BLOCK_SIZE//2)], 171 | (3, 4, 5) : [(START_X, START_Y+BLOCK_SIZE+BLOCK_SIZE//2), (START_X+3*BLOCK_SIZE, START_Y+BLOCK_SIZE+BLOCK_SIZE//2)], 172 | (6, 7, 8) : [(START_X, START_Y+2*BLOCK_SIZE+BLOCK_SIZE//2), (START_X+3*BLOCK_SIZE, START_Y+2*BLOCK_SIZE+BLOCK_SIZE//2)], 173 | (0, 3, 6) : [(START_X+BLOCK_SIZE//2, START_Y), (START_X+BLOCK_SIZE//2, START_Y+3*BLOCK_SIZE)], 174 | (1, 4, 7) : [(START_X+BLOCK_SIZE+BLOCK_SIZE//2, START_Y), (START_X+BLOCK_SIZE+BLOCK_SIZE//2, START_Y+3*BLOCK_SIZE)], 175 | (2, 5, 8) : [(START_X+2*BLOCK_SIZE+BLOCK_SIZE//2, START_Y), (START_X+2*BLOCK_SIZE+BLOCK_SIZE//2, START_Y+3*BLOCK_SIZE)], 176 | (0, 4, 8) : [(START_X, START_Y), (START_X+3*BLOCK_SIZE, START_Y+3*BLOCK_SIZE)], 177 | (2, 4, 6) : [(START_X+3*BLOCK_SIZE, START_Y), (START_X, 3*START_Y+BLOCK_SIZE)] 178 | } 179 | scenario = '' 180 | for i in [0, 3, 6]: 181 | if logic.board[i] == logic.board[i+1] == logic.board[i+2] == winner: 182 | scenario = (i, i+1, i+2) 183 | break 184 | for i in [0, 1, 2]: 185 | if logic.board[i] == logic.board[i+3] == logic.board[i+6] == winner: 186 | scenario = (i, i+3, i+6) 187 | break 188 | if logic.board[0] == logic.board[4] == logic.board[8] == winner: 189 | scenario = (0, 4, 8) 190 | if logic.board[2] == logic.board[4] == logic.board[6] == winner: 191 | scenario = (2, 4, 6) 192 | scenario = scenarios.get(scenario) 193 | pygame.draw.line(screen, RED, scenario[0], scenario[1], 3) 194 | pygame.display.update() 195 | 196 | def roundFinished(winner=None): 197 | restartRect = restart.get_rect() 198 | restartRect.center = ((SCREEN_WIDTH // 2, SCREEN_WIDTH - 100)) 199 | screen.blit(restart, restartRect) 200 | textToBeShown = youWon if winner == USER else (youLost if winner == CPU else tie) 201 | if winner is not None: 202 | winningLine(winner) 203 | textRect = textToBeShown.get_rect() 204 | textRect.center = ((SCREEN_WIDTH // 2, 100)) 205 | screen.blit(textToBeShown, textRect) 206 | running = True 207 | pygame.display.update() 208 | while running: 209 | event = pygame.event.wait() 210 | if event.type == pygame.QUIT: 211 | pygame.quit() 212 | if event.type == pygame.KEYDOWN and event.key == pygame.K_RETURN: 213 | running = False 214 | pygame.display.update() 215 | clearTheScreen() 216 | time.sleep(1) 217 | drawBoard() 218 | resetTheBoard() 219 | 220 | screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_WIDTH)) 221 | screen.fill(BACKGROUND_COLOR) 222 | pygame.display.set_caption('Tic-Tac-Toe') 223 | x, o = creatingTheIcons() 224 | 225 | def main(): 226 | headerRect = header.get_rect() 227 | headerRect.center = ((SCREEN_WIDTH // 2, 50)) 228 | screen.blit(header, headerRect) 229 | intro() 230 | drawBoard() 231 | pygame.display.update() 232 | 233 | '''game loop''' 234 | running = True 235 | while running: 236 | event = pygame.event.wait() 237 | if event.type == pygame.QUIT: 238 | running = False 239 | showTurn(USER) 240 | if event.type == pygame.MOUSEBUTTONDOWN: 241 | posX, posY = event.pos 242 | if inTheBoard((posX, posY)): 243 | if playerMove((posX, posY)): 244 | if logic.playerIsWinner(logic.board, USER): 245 | eraseTurn() 246 | roundFinished(USER) 247 | elif logic.boardIsFull(): 248 | eraseTurn() 249 | roundFinished() 250 | else: 251 | eraseTurn() 252 | showTurn(CPU) 253 | time.sleep(1.5) 254 | cpuMove() 255 | if logic.playerIsWinner(logic.board, CPU): 256 | eraseTurn() 257 | roundFinished(CPU) 258 | else: 259 | eraseTurn() 260 | if event.type == pygame.KEYDOWN and event.key == pygame.K_RETURN: 261 | resetTheBoard() 262 | pygame.display.update() 263 | 264 | if __name__ == '__main__': 265 | main() 266 | 267 | pygame.quit() -------------------------------------------------------------------------------- /Tic-Tac-Toe/logic.py: -------------------------------------------------------------------------------- 1 | '''returns true if the given position in the board is free.''' 2 | def placeIsFree(position): 3 | return board[position] == '' 4 | 5 | '''returns true if the board is full.''' 6 | def boardIsFull(): 7 | return board.count('') == 0 8 | 9 | '''checks all the possibilities of the winning and returns true if one of the conditions is satisfied.''' 10 | def playerIsWinner(board, player): 11 | startingPositions = [0, 3, 6] 12 | for start in startingPositions: 13 | if board[start] == board[start+1] == board[start+2] == player: 14 | return True 15 | startingPositions = [0, 1, 2] 16 | for start in startingPositions: 17 | if board[start] == board[start+3] == board[start+6] == player: 18 | return True 19 | return (board[0] == board[4] == board[8] == player) or (board[2] == board[4] == board[6] == player) 20 | 21 | '''cpu moves based on some simple rules. don't worry it's not unbeatable:))''' 22 | def cpuMove(board, cpu, user): 23 | import random 24 | corners = [0, 2, 6, 8] 25 | legalMoves = [x for x in range(9) if board[x] is ''] 26 | legalCorners = [x for x in corners if x in legalMoves] 27 | for move in legalMoves: 28 | tempBoard = board.copy() 29 | tempBoard[move] = cpu 30 | if playerIsWinner(tempBoard, cpu): 31 | board[move] = cpu 32 | return move 33 | for move in legalMoves: 34 | tempBoard = board.copy() 35 | tempBoard[move] = user 36 | if playerIsWinner(tempBoard, user): 37 | board[move] = cpu 38 | return move 39 | if board[4] == '': 40 | board[4] = cpu 41 | return 4 42 | move = -1 43 | if len(legalCorners): 44 | move = random.choice(legalCorners) 45 | else: 46 | move = random.choice(legalMoves) 47 | board[move] = cpu 48 | return move 49 | 50 | board = [''] * 9 -------------------------------------------------------------------------------- /Tic-Tac-Toe/requirements.txt: -------------------------------------------------------------------------------- 1 | pygame 2 | pygame_widgets -------------------------------------------------------------------------------- /x86 Assembly Playground/README.md: -------------------------------------------------------------------------------- 1 | ## X86 Assembly 2 | Understanding assembly and getting to know how computers work is a must to learn for every computer engineering student. 3 | 4 | In this directory, I will share my journey for learning x86 assembly! 5 | 6 |
7 | ### Preparing the environment 8 | 9 |
--------------------------------------------------------------------------------