[Python] - How to create a simple 6-men morris game with AI | SheCodes

[Python] - How to create a simple 6-men morris game with AI opponent in Python

Learn how to create a simple 6-men morris game with AI or computer as an opponent in Python using basic programming concepts and logic.

👩‍💻 Python Code instructions

Asked 2 years ago in Python by Clarence

create a simple 6-men morris game with AI or Computer as an opponent

🤖 SheCodes Athena says:

Answered in 11.7 seconds
python
Copy code
# Python code for a simple 6-men morris game with AI import random # Initializing the board with empty spaces board = [[' ', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' ']] player = 'X' computer = 'O' game_over = False # Function to print the current state of the board def print_board(): for line in board: print(line) # Function to check if a player has won def check_win(char): # Check horizontal lines for row in board: if row.count(char) == 3: return True # Check vertical lines for i in range(3): column = [board[j][i] for j in range(3)] if column.count(char) == 3: return True # Check diagonals diagonal1 = [board[i][i] for i in range(3)] diagonal2 = [board[i][2-i] for i in range(3)] if diagonal1.count(char) == 3 or diagonal2.count(char) == 3: return True return False # Function to place a piece on the board def place_piece(char): valid_move = False while not valid_move: row = int(input("Enter row (0-2): ")) col = int(input("Enter col (0-2): ")) if board[row][col] == ' ': board[row][col] = char valid_move = True else: print("Invalid move, try again.") if check_win(char): print(char + " wins!") global game_over game_over = True # Function for the computer's turn def computer_move(): valid_move = False while not valid_move: # Generate a random move row = random.randint(0, 2) col = random.randint(0, 2) if board[row][col] == ' ': board[row][col] = computer valid_move = True if check_win(computer): print(computer + " wins!") global game_over game_over = True # Game loop print_board() while not game_over: place_piece(player) print_board() if not game_over: computer_move() print_board()

Explanation:

  • We first import the random module to generate pseudo-random moves for the computer.
  • We initialize the board as a 2D list of size 3x3 with all spaces as empty strings (' ').
  • We define the player's character as 'X', the computer's character as 'O', and set game_over as False to initiate the game.
  • The print_board() function simply prints the current state of the board. It does not return anything.
  • The check_win(char) function takes a character char as input (either 'X' or 'O') and checks if the player corresponding to that character has won. We check for all possible combinations of three in a row - horizontally, vertically and diagonally.
  • The place_piece(char) function allows the player to place their piece on the board. It prompts the user to enter the row and column indices of where they want to place their piece. If the indices are valid (i.e. the corresponding space on the board is empty), the piece is placed and the function exits. If the indices are invalid, the player is asked to try again.
  • The computer_move() function generates a random move for the computer. It keeps generating a random move until it finds an empty space on the board. Once it finds a valid move, it places the computer's piece on the board. If the computer wins after making its move, the function exits.
  • Finally, we have the main game loop which alternates between the player's turn and the computer's turn. If either player wins, the corresponding message is printed and the game_over variable is set to True, which causes the loop to exit.

More coding questions about Python

👩‍💻 Technical question

What if CTR+C doesn't end the process in terminal?

🤖 SheCodes Athena says:

Answered in 3.99 seconds

If CTRL+C doesn't end the process in your terminal, you can try using a different approach. Here are a couple of options:

  1. Forcefully terminate the process: You can use the kill command followed by the process ID (PID) to terminate it. First, you need to find the PID of the process, which you can do by using:

    bash
    Copy code
    ps aux | grep your_process_name

    Then, use the kill command:

    bash
    Copy code
    kill -9 PID
  2. Using CTRL+Z to suspend the process: If CTRL+C is not working, you can try CTRL+Z. This will suspend the process, and you can then terminate it. To kill the suspended process, use:

    bash
    Copy code
    kill %1

    (if it's the first job suspended, otherwise replace %1 with the appropriate job number).

Remember to replace your_process_name with the actual name of the process you're trying to end.

👩‍💻 Technical question

What does iterable mean in Python? (make use of simple terms pls)

🤖 SheCodes Athena says:

Answered in 1.78 seconds

An iterable in Python is something that you can loop over, like a list or a string. It allows you to go through each item one by one. For example, you can use a for loop to access each element in an iterable.

Here's a simple example using a list:

python
Copy code
my_list = [1, 2, 3, 4] for number in my_list: print(number)

In this example, my_list is an iterable, and the loop prints each number in that list.

👩‍💻 Technical question

How do I round up a float number in python?

🤖 SheCodes Athena says:

Answered in 2.86 seconds

You can round up a float number in Python using the math.ceil() function. This function will round a number up to the nearest integer.

Here’s an example:

python
Copy code
import math number = 3.14 rounded_number = math.ceil(number) print(rounded_number) # Output: 4

In this example, math.ceil(3.14) will round it up to 4. You can use any float number with this function! For more details, you can check the official documentation here: https://docs.python.org/3/library/math.html#math.ceil

👩‍💻 Technical question

what does def mean in python

🤖 SheCodes Athena says:

Answered in 2.17 seconds

In Python, def is a keyword used to define a function. A function is a reusable block of code that can perform a specific task. Here's a simple example:

python
Copy code
def greet(name): return f"Hello, {name}!"

In this example, greet is the name of the function, and it takes one parameter, name. When you call greet("Alice"), it will return the string "Hello, Alice!". Functions help organize code and can be called multiple times with different arguments.

👩‍💻 Technical question

how to comment in python

🤖 SheCodes Athena says:

Answered in 1.49 seconds

In Python, you can add comments by using the # symbol. Anything following the # on that line will be treated as a comment and will not be executed by the program.

Here's an example:

python
Copy code
# This is a single-line comment print("Hello, World!") # This prints a message

For multi-line comments, you can use triple quotes (''' or """):

python
Copy code
""" This is a multi-line comment """ print("Hello again!")

You can read more about comments in Python in the official Python documentation.

👩‍💻 Technical question

<your-api-key>https://m.youtube.com/watch?v=swVGwOqZaXc

🤖 SheCodes Athena says:

Answered in 0.75 seconds

SheCodes Athena AI only answers technical questions.

👩‍💻 https://m.youtube.com/watch?v=swVGwOqZaXc

🤖 SheCodes Athena says:

Answered in 0.74 seconds

SheCodes Athena AI only answers technical questions.

👩‍💻 Technical question

how do I print a csv dictionary in python line by line in a sentence

🤖 SheCodes Athena says:

Answered in 3.39 seconds

To print a CSV dictionary in Python line by line in a sentence, you can use the csv module to read the CSV file and then iterate over the dictionary values. Here's an example code snippet:

python
Copy code
import csv # Open the CSV file with open('your_file.csv') as file: # Create a CSV reader object reader = csv.DictReader(file) # Iterate over each row in the CSV file for row in reader: # Print each row's values in a sentence print(f"Name: {row['Name']}, Age: {row['Age']}, Email: {row['Email']}")

In this code, replace 'your_file.csv' with the path to your actual CSV file. Make sure your CSV file has a header row, so that each column can be accessed by a key in the dictionary. You can specify the appropriate column names in the print statement to access the values from the dictionary.

Note that the csv.DictReader class allows us to work with the CSV data as a dictionary, where the keys are the column names and the values are the corresponding row values.

👩‍💻 Python Code instructions

Write a program that asks the user for word and prints out how many lowercase z's it contains

🤖 SheCodes Athena says:

Answered in 1.03 seconds
python
Copy code
word = input("Enter a word: ") count = 0 for char in word: if char == "z": count += 1 print("The word contains", count, "lowercase z's.")

👩‍💻 Python Code instructions

Write a program that asks the user word and prints the word with the lowercase letter 'a' replaced by the '@' symbol, and the lowercase letter 'o' replaced by a zero '0'. Your program should work like this: Enter a word: Password P@ssw0rd

🤖 SheCodes Athena says:

Answered in 0.8 seconds

Python:

python
Copy code
word = input("Enter a word: ") new_word = word.replace('a', '@').replace('o', '0') print(new_word)

👩‍💻 Python Code instructions

Write a program that asks the user for some text. If the text is all in lowercase, your program should print True. Otherwise it should print False. Your program should work like this: Enter some text: this is all lowercase True

🤖 SheCodes Athena says:

Answered in 0.84 seconds

Python

python
Copy code
text = input("Enter some text: ") if text.islower(): print(True) else: print(False)

👩‍💻 Technical question

explain pow() in python

🤖 SheCodes Athena says:

Answered in 1.92 seconds

The pow() function in Python is used to calculate the exponential value of a number. It takes in two arguments: the base number and the exponent. Here is an example:

python
Copy code
result = pow(2, 3) print(result)

Output: 8

In this example, the pow() function calculates 2 to the power of 3, which is 8. So, result will store the value 8.

👩‍💻 Technical question

string to int in python

🤖 SheCodes Athena says:

Answered in 1.37 seconds

In Python, you can convert a string to an integer using the int() function. This function takes a string as input and returns the equivalent integer value. Here's an example:

python
Copy code
num_str = "123" num_int = int(num_str) print(num_int) # Output: 123

In this example, the string "123" is converted to the integer 123 using the int() function.

👩‍💻 Technical question

what does % mean in python?

🤖 SheCodes Athena says:

Answered in 1.37 seconds

The % symbol in Python is called the modulo operator. It is used to find the remainder when one number is divided by another.

Example:

python
Copy code
a = 10 b = 3 result = a % b print(result) # Output: 1

In the example above, 10 is divided by 3 and the remainder is 1. The modulo operator % is used to obtain that remainder.

👩‍💻 Technical question

What does the == operator do in Python?

🤖 SheCodes Athena says:

Answered in 1.63 seconds

The == operator in Python is used to check if two values are equal. It returns True if the values are equal and False otherwise.

Here is an example:

python
Copy code
x = 5 y = 10 z = 5 print(x == y) # False print(x == z) # True

In the above code, x == y evaluates to False because x and y have different values. On the other hand, x == z evaluates to True because x and z have the same value.

👩‍💻 Technical question

Asked 1 year ago in Python by Cameron

flask code that allows an admin account special privilege's

🤖 SheCodes Athena says:

Answered in 4.5 seconds

Sure! Here's an example of Flask code that allows an admin account special privileges:

python
Copy code
from flask import Flask, request app = Flask(__name__) def is_admin(username): # Check if the username is an admin admins = ['admin1', 'admin2', 'admin3'] return username in admins @app.route('/admin') def admin_page(): username = request.args.get('username') if is_admin(username): # Code to display admin page with special privileges return 'Welcome to the admin page!' else: return 'Sorry, you do not have admin privileges.' if __name__ == '__main__': app.run()

In this example, we define the is_admin function which checks if a given username is an admin. The admins list contains the usernames that have admin privileges.

The /admin route is defined, and when accessed, it checks if the provided username parameter is an admin by calling the is_admin function. If the username is an admin, it displays the admin page with special privileges. Otherwise, it returns a message stating that the user does not have admin privileges.

Please note that this is a basic example and may need modifications based on your specific requirements.

👩‍💻 Technical question

Asked 1 year ago in Python by Michaela

Calculate total profit in a dataframe

🤖 SheCodes Athena says:

Answered in 2.91 seconds

To calculate the total profit in a dataframe, you can use the sum() function in Python.

Assuming you have a dataframe called df with a column named "profit", you can calculate the total profit using the following code:

python
Copy code
total_profit = df['profit'].sum()

This will give you the sum of all the values in the "profit" column of the dataframe.

Here is an example:

code
Copy code
df = pd.DataFrame({ 'year': [2018, 2019, 2020], 'profit': [1000, 2000, 1500] }) total_profit = df['profit'].sum() print(total_profit)

Output:

code
Copy code
4500

This means that the total profit in the dataframe is 4500.

👩‍💻 Technical question

Asked 1 year ago in Python by Michaela

Hide yaxis in px.bar plotly

🤖 SheCodes Athena says:

Answered in 2.91 seconds

To hide the y-axis in a bar chart created with Plotly, you can set the showticklabels attribute of the y-axis to False. Here's an example:

python
Copy code
import plotly.express as px data = {'Category': ['A', 'B', 'C'], 'Value': [10, 20, 15]} fig = px.bar(data, x='Category', y='Value') fig.update_yaxes(showticklabels=False) fig.show()

This code creates a bar chart using px.bar and sets the showticklabels attribute of the y-axis to False using update_yaxes. This will hide the tick labels and effectively hide the y-axis. You can customize other aspects of the chart as needed.

👩‍💻 Technical question

Description Given an n*m matrix, output its absolute matrix. An absolute matrix is defined as a matrix in which each element is the absolute value of the original element in the input matrix. ### Input The first row contains two integers n, m representing the dimensions of the input matrix. In the next N rows, each row has m columns, representing the matrix elements. Each number in the matrix is in the range of -100 to 100. ### Output A matrix whose elements are the absolute value of the original input matrix. This is a so-called absolute matrix.

🤖 SheCodes Athena says:

Answered in 2.96 seconds

To create an absolute matrix, we need to take the absolute value of each element in the input matrix.

Here's how you can do it in Python:

python
Copy code
n, m = map(int, input().split()) matrix = [] for _ in range(n): row = list(map(int, input().split())) matrix.append(row) # Create the absolute matrix absolute_matrix = [] for i in range(n): absolute_row = [] for j in range(m): absolute_element = abs(matrix[i][j]) absolute_row.append(absolute_element) absolute_matrix.append(absolute_row) # Print the absolute matrix for row in absolute_matrix: for element in row: print(element, end=" ") print()

Example input:

code
Copy code
3 3 -1 2 -3 4 0 -5 6 -7 8

Output:

code
Copy code
1 2 3 4 0 5 6 7 8

This code reads the dimensions of the matrix, then reads the matrix elements. It creates a new matrix with the absolute values of each element and prints the absolute matrix.

👩‍💻 when i inputed :5 5 22 62 -39 -15 37 -34 95 -85 26 -57 8 33 -36 69 -4 -36 -55 -92 96 -70 79 -93 -42 -44 66 it said it has a bug

🤖 SheCodes Athena says:

Answered in 2.11 seconds

I apologize for the bug in the code. There was an indexing error in the inner loop while creating the absolute matrix.

Here's the corrected code:

python
Copy code
n, m = map(int, input().split()) matrix = [] for _ in range(n): row = list(map(int, input().split())) matrix.append(row) # Create the absolute matrix absolute_matrix = [] for i in range(n): absolute_row = [] for j in range(m): absolute_element = abs(matrix[i][j]) absolute_row.append(absolute_element) absolute_matrix.append(absolute_row) # Print the absolute matrix for row in absolute_matrix: for element in row: print(element, end=" ") print()

I hope this helps! Let me know if you have any further questions.

👩‍💻 Technical question

Consider the following Python program. fin = open('words.txt') for line in fin: word = line.strip() print(word) What does the program loop over?

🤖 SheCodes Athena says:

Answered in 0.46 seconds

The program loops over each line of the file 'words.txt'.

👩‍💻 Python Code instructions

find sum of digits of input x

🤖 SheCodes Athena says:

Answered in 1.92 seconds
python
Copy code
def sum_of_digits(x): # Convert the number to string x_str = str(x) # Initialize a variable to store the sum digit_sum = 0 # Iterate through each digit in the string for digit in x_str: # Convert the digit back to integer and add it to the sum digit_sum += int(digit) return digit_sum # Prompt the user to enter the input number x = int(input("Enter a number: ")) # Call the function to find the sum of digits result = sum_of_digits(x) print("Sum of digits:", result)

👩‍💻 Technical question

what are arguments in a function?

🤖 SheCodes Athena says:

Answered in 2.78 seconds

In programming, arguments are the values that you can pass to a function when you call it. These values are used by the function to perform actions or calculations. Arguments allow you to customize the behavior of a function, making it more flexible and reusable. They can be variables, literals, or expressions.

For example, consider the following function that adds two numbers together:

python
Copy code
def add_numbers(num1, num2): sum = num1 + num2 return sum

In this function, num1 and num2 are the arguments. When you call this function and provide two numbers as arguments, it will add them together and return the result.

python
Copy code
result = add_numbers(5, 7) print(result)

Output:

code
Copy code
12

In this example, 5 and 7 are the arguments passed to the add_numbers function. They are used as num1 and num2 respectively, and the function returns the sum of these two numbers.

👩‍💻 Technical question

what is getattribute

🤖 SheCodes Athena says:

Answered in 2.73 seconds

__getattriubte__ is a built-in method in Python that is used to access attributes of an object. It is invoked when an attribute is not found in the usual places such as the object's namespace or its classes. Instead of raising an AttributeError, the __getattriubte__ method allows you to customize the behavior of attribute access.

Here's an example:

python
Copy code
class Person: def __getattriubte__(self, name): print(f"{name} attribute does not exist") person = Person() person.age

Output:

code
Copy code
age attribute does not exist

In this example, when trying to access the age attribute of the Person object, since it doesn't exist, the __getattriubte__ method is called and it prints a message indicating that the attribute does not exist.

👩‍💻 Technical question

What is module

👩‍💻 Python Code instructions

function to insert a new order to an orders API

👩‍💻 Technical question

what is the easiest pogramming luanguage to learn

👩‍💻 Python Code instructions

Edit this code to make it that only a certain UUID is able to ping the bot and get the expected result of a gif @bot.event async def on_message(message): if message.author.bot: # Ignore messages from bots return # Check if the bot is mentioned in the message content if bot.user.mentioned_in(message): gif_url = 'https://media.tenor.com/vqMLLEvwM7YAAAAC/hello-eyeball.gif' # Replace with the direct URL of the GIF you want to reply with embed = discord.Embed() embed.set_image(url=gif_url) await message.reply(embed=embed) await bot.process_commands(message) # Process commands after handling other events

👩‍💻 Technical question

Asked over 1 year ago in Python by Marion-Favour

A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 Ă— 99. Find the largest palindrome made from the product of two 3-digit numbers. Save the result in the file 102-result Your file should contain the exact result, no new line, no extra space

👩‍💻 Technical question

what to do if my python turtle is very slow and you don't know what to simplify

👩‍💻 HTML, CSS and JavaScript Code instructions

#fine tune llama for text classification code example

👩‍💻 Technical question

Can you teach me If statements in Python

👩‍💻 Python Code instructions

Develop a catalog for a company. Assume that this company sells three different Items. The seller can sell individual items or a combination of any two items. A gift pack is a special combination that contains all three items. Here are some special considerations: If a customer purchases individual items, he does not receive any discount. If a customer purchases a combo pack with two unique items, he gets a 10% discount. If the customer purchases a gift pack, he gets a 25% discount. Write a function for the above scenario. Perform the calculations in code wherever applicable. Output: Online Store ——————————————— Product(s) Price Item 1 200.0 Item 2 Item 3 Combo 1 (Item 1 + 2) Combo 2 (Item 2 + 3) Combo 3 (Item 1 + 3) Combo 4 (Item 1 + 2 + 3) —————————————— For delivery contact 98764678899

👩‍💻 Technical question

creating a dictionary using a for loop

👩‍💻 Python Code instructions

John R. Stalling's folding method in python

👩‍💻 Technical question

can you explain very shortly what is the purpose of creating instances

👩‍💻 Technical question

what is tr

👩‍💻 Technical question

python how to subtract a string and an integer

👩‍💻 Technical question

What is a string?

👩‍💻 Technical question

How do I create an arg function with a series of strings?

👩‍💻 Technical question

Where can I upload images to get a url for my code?

👩‍💻 Python Code instructions

The code should do the following. 1. The code should ask the user for a web address and business type. It should then go to the web address and find businesses matching the users input and find any email addresses connected to the business, then put the business name and email address in a google spread sheet.

👩‍💻 Technical question

create a code about pet store services

👩‍💻 Technical question

how to check minter is the sender using python?

👩‍💻 Technical question

print("Welcome to my computer quiz!") playing = input("Do you want to play? ") if playing != "yes": quit() print("Okay! Let's play :)") answer = input("What does CPU stand for? ") if answer == "central processing unit": print('Correct!') else: print("Incorrect!") answer = input("What does GPU stand for?") if answer == "graphics processing unit": print('Correct!') else: print("Incorrect!") answer = input("What does RAM stand for?") if answer == "random access memory": print('Correct!') else: print("Incorrect!") please fix indentations

👩‍💻 Python Code instructions

windows photo to text and translate script in python

👩‍💻 Python Code instructions

photo to text and translate script in python

👩‍💻 Technical question

how to change image size

👩‍💻 Technical question

can you teach me every thing about abstraction in oop

👩‍💻 Technical question

donner les techniques de traitment automatique de la langue Arabe

👩‍💻 Technical question

Find the address in memory for the element at 4th row and 5th column in the generated Tri- diagonal matrix using the same parameters (Base address 2700 , W= 4)