Showing posts with label Python Projects. Show all posts
Showing posts with label Python Projects. Show all posts

Monday, July 26, 2021

Tic-Tac-Toe Game Design Using Python



And here comes some fun in the time when we all are locked inside our homes because of this COVID-19 pandemic ( 05/25/2020) . I am going to guide you on how you can build your own Tic_Tac_Toe Game using Python scripts in just few minutes and can enjoy playing with your loved once.


How to play Tic_Tac_Toe Game , Please watch the video here.


Tic_Tac_Toe Game : - Tic-tac-toe or noughts and crosses, or Xs and Os is a paper and pencil game for two players, X and O, who take turns marking the spaces in a 3×3 grid. The player who succeeds in placing three of their marks in a horizontal, vertical, or diagonal row is the winner. Here , instead of using paper and pencil we will use our computer/laptop to play this game.


The following example game is won by the first player, X:







Lets get started -
Below are the steps to create a Python Script to run Tic_Tac_Toe Game.


Step- 1 - Write a function that can take in the Player names using your keyboard.

def player_name(): Player_1 = input( "Player 1, Please Enter Your Name :").upper() Player_2 = input( "Player 2, Please Enter Your Name :").upper() return (Player_1 , Player_2)


Step- 2 - Write a function that can take in a player input and assign their marker as 'X' or 'O'.

def player_input(Player_1 , Player_2): marker='' while not (marker == 'X' or marker == 'O'): print("" +Player_1+ ": Do you want to be 'X' or 'O' ? ") marker = input().upper() if marker == 'X': return ('X','O') else: return ('O', 'X')




Step - 3- Write a function that can print out a board. Set up your board as a list, where each index 1-9 corresponds with a number on a number pad, so you get a 3 by 3 board representation.

def keypad_display(keypad_values): clear_output() # Remember, this only works in jupyter! print(' | | ') print(' ' + keypad_values[7] + ' | ' + keypad_values[8] + ' | ' + keypad_values[9]) print(' P(7)| P(8)|P(9)') print('------------------') print(' | | ') print(' ' + keypad_values[4] + ' | ' + keypad_values[5] + ' | ' + keypad_values[6]) print(' P(4)| P(5)|P(6)') print('------------------') print(' | | ') print(' ' + keypad_values[1] + ' | ' + keypad_values[2] + ' | ' + keypad_values[3]) print(' P(1)| P(2)|P(3)')


Step -4 - Write a function that uses the random module to randomly decide which player goes first.

def choose_first(): if random.randint(0,1) == 0: return Player_2 else: return Player_1


Step - 5- Write a function that takes in the board list object, a marker ('X' or 'O'), and a desired position (number 1-9) and assigns it to the board.

def place_marker(keypad_values,marker,position): keypad_values[position]=marker




Step -6 - Write a function that takes in a board and checks to see if someone has won.

def win_check(keypad_values,mark): return ((keypad_values[7] == keypad_values[8] == keypad_values[9] == mark) or (keypad_values[4] == keypad_values[5] == keypad_values[6] == mark) or (keypad_values[1] == keypad_values[2] == keypad_values[3] == mark) or (keypad_values[1] == keypad_values[5] == keypad_values[9] == mark) or (keypad_values[3] == keypad_values[5] == keypad_values[7] == mark) or (keypad_values[1] == keypad_values[4] == keypad_values[7] == mark) or (keypad_values[2] == keypad_values[5] == keypad_values[8] == mark) or (keypad_values[3] == keypad_values[6] == keypad_values[9] == mark))




Step -7 - Write a function that returns a boolean indicating whether a space on the board is freely available.

def space_check(keypad_values,position): return keypad_values[position]== ' '


Step -8 - Write a function that checks if the board is full and returns a boolean value.

def full_board_check(keypad_values): for i in range (1,10): if space_check(keypad_values,i): return False return True


Step - 9 - Write a function that asks for a player's next position (as a number 1-9) and then uses the function from step 7 to check if its a free position. If it is, then return the position for later use.

def player_choice(keypad_values, Player_name): position = 0 while position not in [1,2,3,4,5,6,7,8,9] or not space_check(keypad_values,position): print(""+Player_name+ " , Please Choose Your Next Position (1,9) ?") position = int(input()) return position


Step - 10 - Write a function that asks the player if they want to play again and returns a boolean True if they do want to play again.

def replay(): return input('Do you want to play again ? Enter yes or no ').lower().startswith('y')


Step - 11 - Here comes the REAL JOB !!! Make use of all the functions we have created inside a while loop and run the Game.

#Lets Play the Game !!! while True: keypad_values = [' ']*10 Player_1 , Player_2 = player_name() player1_marker,player2_marker = player_input( Player_1, Player_2) turn = choose_first() print(turn + " Will Go First ") play_game = input ( 'Are you ready to play the game ? Enter y or n : ') if play_game.lower()[0] == 'y': game_on = True else: game_on = False while game_on: if turn == Player_1: keypad_display(keypad_values) position = player_choice(keypad_values , Player_1) place_marker(keypad_values, player1_marker,position) if win_check(keypad_values,player1_marker): keypad_display(keypad_values) print(" Congratulations " +Player_1+"!!! You have Won the Game !!") game_on = False elif full_board_check(keypad_values): keypad_display(keypad_values) print('The Game is Draw!!') break else: turn = Player_2 else: keypad_display(keypad_values) position = player_choice(keypad_values, Player_2) place_marker(keypad_values, player2_marker,position) if win_check(keypad_values,player2_marker): keypad_display(keypad_values) print(" Congratulations " +Player_2+"!!! You have Won the Game !!") game_on = False elif full_board_check(keypad_values): keypad_display(keypad_values) print('The Game is Draw!!') break else: turn = Player_1 if not replay(): print(" Thank You for Playing , Hope You Enjoyed !!!") break




How to RUN the Script?


Well, here I am going to guide you how you can setup your environment and run this game.


Step -1 - Install Python in your computer.
Go to Python.org , Navigate to 'downloads' tab and Click on the latest version of Python available.


Step - 2 - Download the Tic_Tac_Toe_Game.zip file ,unzip it and get the Python Script from below.
Tic_Tac_Toe_Game


Step - 3 - Open the Command Prompt in your computer and Run the below command. ( Make sure you are running the script from correct directory)


python Tic_Tac_Toe_Game.py
Step - 4 - Enter your and your partner name , Choose what you want to pick up from either 'x' or 'o' and the game script will randomly choose which player will go first.






Step - 5 - Keep on playing till the game reaches to Winning position or a Draw.






Step - 6 - Enter 'y' or 'n' if you want to play again or not.




------------------------------------------------------Thank You-----------------------------------------------------


If you face any issues while in understanding the script or running it , please put your query in the below comment section.


Happy Learning, Stay Safe !!!

BlackJack Game Design Using Python



CASINO !!! Yes , You imagined Rightly. Let's see how in couple of minutes you can develop your own Black Jack Game using Python Scripting.


Blackjack : Blackjack, formerly also Black Jack and Vingt-Un, is the American member of a global family of banking games known as "Twenty - One", whose relatives include Pontoon and Vingt-et -Un. It is a comparing card game between one or more players and a dealer, where each player in turn competes against the dealer. Players do not compete against each other. It is played with one or more decks of 52 cards, and is the most widely played casino banking game in the world. (Source : Wikipedia)


To know how to play Blackjack , please watch the video here.


Note: In this Project some of the Object Oriented Programming (OOP) concepts of Python along with basic Python Concepts are used. If you are new to Python , Please visit the Documentation page of www.python.org


Let's get started -


Here are the basic steps to play the game -
To play a hand of Blackjack the following steps must be followed-
Create a deck of 52 cards
Shuffle the deck
Ask the Player for their bet
Make sure that the Player's bet does not exceed their available chips
Deal two cards to the Dealer and two cards to the Player
Show only one of the Dealer's cards, the other remains hidden
Show both of the Player's cards
Ask the Player if they wish to Hit, and take another card
If the Player's hand doesn't Bust (go over 21), ask if they'd like to Hit again.
If a Player Stands, play the Dealer's hand. The dealer will always Hit until the Dealer's value meets or exceeds 17
Determine the winner and adjust the Player's chips accordingly
Ask the Player if they'd like to play again


Note: A standard deck of playing cards has four suits (Hearts, Diamonds, Spades and Clubs) and thirteen ranks (2 through 10, then the face cards Jack, Queen, King and Ace) for a total of 52 cards per deck. Jacks, Queens and Kings all have a rank of 10. Aces have a rank of either 11 or 1 as needed to reach 21 without busting.


Steps to Develop the GAME -
Step - 1 - Declare variables to store suits, ranks and values.suits = ('Hearts','Diamonds','Spades','Clubs') ranks = ('Two','Three','Four','Five','Six','Seven','Eight','Nine','Ten','Jack','Queen','King','Ace') values = {'Two':2,'Three':3,'Four':4,'Five':5,'Six':6,'Seven':7,'Eight':8,'Nine':9,'Ten':10,'Jack':10, 'Queen':10,'King':10,'Ace':11}




Step - 2 - Declare a Boolean value to be used to control while loops.playing = True


Step - 3 - Create a 'card' class which hold two attributes suit and rank. Also , In addition to the Card's __init__ method, consider adding a __str__ method ( Special Methods) that, when asked to print a Card, returns a string in the form "Two of Hearts" ( These are special methods for Python class)class Card(): def __init__(self,suit,rank): self.suit = suit self.rank = rank def __str__(self): return self.rank + '_of_' + self.suit


Step -4 - Create a Deck Class, Here we might store 52 card objects in a list that can later be shuffled. First, though, we need to instantiate all 52 unique card objects and add them to our list. So long as the Card class definition appears in our code, we can build Card objects inside our Deck __init__ method. In addition to an __init__ method we'll want to add methods to shuffle our deck, and to deal out cards during game play.

class Deck(): def __init__(self): self.deck = [] for suit in suits: for rank in ranks: self.deck.append(Card(suit,rank)) def __str__(self): deck_comp = '' for card in self.deck: deck_comp +='\n'+card.__str__() return 'The deck has:' + deck_comp def shuffle(self): random.shuffle(self.deck) def deal(self): single_card = self.deck.pop() return single_card


Step - 5 - Create a Hand Class, In addition to holding Card objects dealt from the Deck, the Hand class may be used to calculate the value of those cards using the values dictionary defined above. It may also need to adjust for the value of Aces when appropriate.

class Hand(): def __init__(self): self.cards = [] self.value = 0 self.aces = 0 def add_card(self,card): self.cards.append(card) self.value += values[card.rank] if card.rank == 'Ace': self.aces +=1 def adjust_for_ace(self): if self.value >21 and self.aces: self.value -=10 // Adding one because according to 'Ace' value in dictionary , 11 will be added first. self.aces -=1


Step - 6 - Create a Chips Class, In addition to decks of cards and hands, we need to keep track of a Player's starting chips, bets, and ongoing winnings. This could be done using global variables, but in the spirit of object oriented programming, let's make a Chips class instead!

class Chips(): def __init__(self,total): self.total = total self.bet = 0 def win_bet(self): self.total +=self.bet def lose_bet(self): self.total -= self.bet


Step -7 - Write a function for taking bets , Since we're asking the user for an integer value, this would be a good place to use try/except( Special blocks to handle the Code ). Remember to check that a Player's bet can be covered by their available chips.



def take_bet(chips): while True: try: chips.bet =int(input("How many chips would you like to bet ?")) except valueError: print('Sorry!! A bet must be an integer') else: if chips.bet > chips.total: print("Sorry, Your bet can't exceed", chips.total) else: break


Step - 8 - Write a function for taking hits, Either player can take hits until they bust. This function will be called during game play anytime a Player requests a hit, or a Dealer's hand is less than 17. It should take in Deck and Hand objects as arguments, and deal one card off the deck and add it to the Hand. You may want it to check for aces in the event that a player's hand exceeds 21. def hit(deck,hand): hand.add_card(deck.deal()) hand.adjust_for_ace()


Step - 9 - Write a function prompting the Player to Hit or Stand, This function should accept the deck and the player's hand as arguments, and assign playing as a global variable.
If the Player Hits, employ the hit() function above. If the Player Stands, set the playing variable to False - this will control the behavior of a while loop later on in our code.def hit_or_stand(deck,hand): global playing while True: x = input("Would you like to Hit or Stand? Enter 'H' or 'S' ") if x[0].lower() == 'h': hit(deck,hand) elif x[0].lower() == 's': print('player stands, dealer is playing') playing = False else: print('Sorry, please try again!!') continue break


Step -10 - Write functions to display cards, When the game starts, and after each time Player takes a card, the dealer's first card is hidden and all of Player's cards are visible. At the end of the hand all cards are shown, and you may want to show each hand's total value. Write a function for each of these scenarios.def show_some(player,dealer): print("\n Dealer's hand:") print('<Card Hidden>') print('',dealer.cards[1]) print("\nPlayer's Hand:",*player.cards , sep='\n') def show_all(player,dealer): print("\nDealer's Hnad:",*dealer.cards , sep='\n') print("Dealer's Hand =", dealer.value) print("\nPlayer's Hand:",*player.cards , sep="\n") print("Player's Hand =",player.value)




Step - 11 -Write functions to handle end of game scenarios, Remember to pass player's hand, dealer's hand and chips as needed.

def player_busts(player,dealer,chips): print("Player Busts!!") chips.lose_bet() def player_wins(player,dealer,chips): print("Player Wins!!") chips.win_bet() def dealer_busts(player,dealer,chips): print("Dealer Busts!!") chips.win_bet() def dealer_wins(player,dealer,chips): print("Dealer Wins!!") chips.lose_bet() def push(player,dealer): print("Dealer and Player tie!!It's a PUSH")


Step -12 - Final Game !!while True: print("Welcome to BlackJack!!!") deck = Deck() deck.shuffle() player_hand = Hand() player_hand.add_card(deck.deal()) player_hand.add_card(deck.deal()) dealer_hand = Hand() dealer_hand.add_card(deck.deal()) dealer_hand.add_card(deck.deal()) player_chips = Chips(100) take_bet(player_chips) 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: player_busts(player_hand,dealer_hand,player_chips) break 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_hand,dealer_hand,player_chips) elif dealer_hand.value > player_hand.value: dealer_wins(player_hand,dealer_hand,player_chips) elif dealer_hand.value < player_hand.value: player_wins(player_hand,dealer_hand,player_chips) else: push(player_hand,dealer_hand) print("Player's Winnings Stands At",player_chips.total) new_game = input("Would you like to play again? Say Yes or No ") if new_game[0].lower() == 'y': playing = True continue else: print("Thanks for Playing!!") break




How to RUN the Script?
Well, here I am going to guide you on how you can setup your environment and run this game in your windows system.

Step -1 - Install Python in your computer.
Go to Python.org , Navigate to 'downloads' tab and Click on the latest version of Python available.

Step - 2 - Download the BlackJack.zip file ,unzip it and get the Python Script ready for the Game from below.

BlackJack


Step - 3 - Open the Command Prompt in your computer and Run the below command. ( Make sure you are running the script from correct directory)

python BlackJack.py






Step - 4 - Enjoy the Game !!!




----------------------------------------------------Thank You--------------------------------------------------------


If you face any issues while in understanding the script or running it , please put your query in the below comment section.

Happy Learning, Stay Safe !!!