I bought "Why can't you do object-oriented development in Java" for object-oriented re-learning, but only in Java / Ruby [Official sample](http://gihyo.jp/book/2005/4- 7741-2222-X / support) wasn't there, so I created it in Python. (Please use it as a reference only. I am also a beginner.)
object_janken.py
from judge import *
from player import *
from tactics import *
#Instance generation of referee (Mr. Saito)
saito = Judge()
#Generation of player 1 (Mr. Murata)
murata_tactics = RandomTactics()
murata = Player("Mr. Murata",murata_tactics)
#Generation of player 2 (Mr. Yamada)
yamada_tactics = StoneOnlyTactics()
yamada = Player("Mr. Yamada",yamada_tactics)
# yamada = Player_STONE("Mr. Yamada")
#Start rock-paper-scissors with Mr. Murata and Mr. Yamada as players
saito.start_janken(murata, yamada)
player.py
class Player:
#Constant representing rock-paper-scissors hand
STONE = 0 #Goo
SCISSORS = 1 #Choki
PAPER = 2 #Par
def __init__(self, name, tactics):
self.name = name
self.win_count = 0
self.tactics = tactics
#Put out the hand of rock-paper-scissors.
def show_hand(self):
hand = self.tactics.read_tactics()
return hand
#Hear the victory or defeat from the referee. If it wins, the argument result is true
def notify_result(self,result):
if (result):
self.win_count += 1
#Answer the number of times you have won.
def get_win_count(self):
return self.win_count
#Answer your name.
def get_name(self):
return self.name
#Inherit child class creation
class Player_STONE(Player):
def show_hand(self):
return self.STONE
judge.py
class Judge:
#Start rock-paper-scissors.
def start_janken(self, player1, player2):
#Declare the start of rock-paper-scissors
print("[Starting rock-paper-scissors]\n")
#Play rock-paper-scissors 3 times
for cnt in range(3):
#Show how many rounds
print("【", (cnt + 1), "Round]")
#Look at the player's hand to determine which one wins.
winner = self.judge_janken(player1, player2)
if (winner != None):
#Show winner
print("\n", winner.get_name(), "Won!\n")
#Communicate results to winning players
winner.notify_result(True)
else:
#In the case of a draw
print("\n It's a draw!\n")
#Declare the end of rock-paper-scissors
print("[End of rock-paper-scissors]\n")
#Determine the final winner
final_winner = self.judge_final_winner(player1, player2)
print(player1.get_win_count(), "versus", player2.get_win_count(), "so")
if (final_winner != None):
print(final_winner.get_name(), "Is the winner!\n")
else:
print("It's a draw!\n")
#Look at the player's hand to determine which one wins.
def judge_janken(self,player1, player2):
winner = None
hand_dict = {0: "STONE",
1: "SCISSORS",
2: "PAPER"}
#Put out the player's hand
player1hand = player1.show_hand()
player2hand = player2.show_hand()
player1hand_name = hand_dict[player1hand]
player2hand_name = hand_dict[player2hand]
#Show each hand
print(f"{player1hand_name} vs. {player2hand_name} \n")
#When player 1 wins
if (player1hand_name == "STONE" and player2hand_name == "SCISSORS") or \
(player1hand_name == "SCISSORS" and player2hand_name == "PAPER") or \
(player1hand_name == "PAPER" and player2hand_name == "STONE") :
winner = player1
#When player 2 wins
if (player1hand_name == "STONE" and player2hand_name == "PAPER") or \
(player1hand_name == "SCISSORS" and player2hand_name == "STONE") or \
(player1hand_name == "PAPER" and player2hand_name == "SCISSORS") :
winner = player2
#If neither is the case, a draw(Returns nil)
return winner
#Determine the final winner.
def judge_final_winner(self,player1, player2):
final_winner = None
#Listen to the number of wins
player1_win_count = player1.get_win_count()
player2_win_count = player2.get_win_count()
#Determine the winner
if (player1_win_count > player2_win_count):
final_winner = player1
elif(player1_win_count < player2_win_count):
final_winner = player2
else:
final_winner = None
return final_winner
tactics.py
class RandomTactics():
def read_tactics(self):
# 0.0 or more 3.Get a random number as a decimal number less than 0
random_num = rm.random()* 3.0
if (random_num < 1.0):
hand = Player.STONE
elif (random_num < 2.0):
hand = Player.SCISSORS
elif (random_num < 3.0):
hand = Player.PAPER
#Return the determined hand as a return value
return hand
#==I love Goo! ”Strategy class.
class StoneOnlyTactics():
def read_tactics(self):
#Be sure to put out a goo
return Player.STONE
card.py
class Card():
#A constant that represents the joker
JOKER = 0
#Constant representing spade
SUIT_SPADE = 1
#Constant representing a diamond
SUIT_DIAMOND = 2
#A constant that represents a club
SUIT_CLUB = 3
#Constant representing the heart
SUIT_HEART = 4
def __init__(self,suit,number):
self.suit = suit
self.number = number
def getNumber(self):
return self.number
#Override toString function
def toString(self):
#In the case of JOKER
if self.suit == 0:
card_code = "JK"
#Cards other than JOKER
else:
suit_dict = {"SUIT_SPADE":"S", "SUIT_DIAMOND":"D",
"SUIT_CLUB":"C","SUIT_HEART":"H"}
number_dict = {1:"A", 2:"2", 3:"3", 4:"4", 5:"5",
6:"6", 7:"7", 8:"8", 9:"9", 10:"T", 11:"J", 12:"Q", 13:"K"}
card_code = suit_dict[self.suit] + number_dict[self.number]
return card_code
hand.py
import random as rm
class Hand():
#Keep the card class as a list
def __init__(self,list):
self.hand = list
#Add a card
def add_card(self,card):
self.hand.append(card)
#Draw a card (top)
def pick_card(self):
picked_card = self.hand.pop(0)
return picked_card
#Return the number of possessions
def getNumberOfCard(self):
return len(self.hand)
#Shuffle your hand
def shuffle(self):
#Randomly remove cards and repeat the last addition
number = self.getNumberOfCard()
for i in range(number):
pos = int(rm.random() * number)
picked_card = self.hand.pop(pos)
self.hand.append(picked_card)
#Find the same number of cards and put them back in an array
def find_same_number_card(self):
same_cards = None
#Get the number of the last added card
last_added_card = self.hand[-1]
last_added_card_num = last_added_card.number
for index in range(len(self.hand)-1):
card = self.hand[index]
if card.number == last_added_card_num:
#If the same card as the last added card is found
#Store the found combination in sameCards and exit the loop
same_cards = [self.hand.pop(-1),self.hand.pop(index)]
break
return same_cards
#Express the card in your hand as a character string.
def toString(self):
hand_cards = ""
for card in self.hand:
hand_cards += card.toString() + " "
return hand_cards
table.py
class Table():
def __init__(self):
self.disposed_cards = []
#Discard the card.
def dispose_card(self,dispose_list):
for card in dispose_list:
print(f"{card.toString()}Abandoned")
self.disposed_cards.append(card)
#Express the discarded card as a character string.
def toString(self):
disposed_cards = ""
for card in self.disposed_cards:
disposed_cards += card.toString() + " "
return disposed_cards
player.py
class Player():
def __init__(self,name,hand,master,table):
self.hand = hand
self.name = name
self.master = master
self.table = table
#Nominate your turn (your turn)
def play(self,next_player):
#Ask the next player to take out his hand
next_hand = next_player.show_hand()
#Draw a card from your opponent's hand
picked_card = next_hand.pick_card()
#Display the result of subtraction
print(self.name, ":", next_player.name, "From", picked_card.toString(),"I pulled\n")
#Add the drawn cards to your hand and discard the same number of cards
self.deal_card(picked_card)
#Find out if your hand is zero
if self.hand.getNumberOfCard() == 0:
#Declare the rise to the facilitator
self.master.declare_win(self)
else:
#Show your current hand
print(self.name, ": The remaining hand",self.hand.getNumberOfCard(), "is\n")
#Shuffle your hand to show
def show_hand(self):
if self.hand.getNumberOfCard() == 1:
self.master.declare_win(self)
self.hand.shuffle()
return self.hand
#Receive the card
def receive_card(self,card):
self.deal_card(card)
#If you have the same card, throw it away
def deal_card(self,card):
#Add a card to your hand
self.hand.add_card(card)
#Find the same card you just added
same_cards = self.hand.find_same_number_card()
#If the same card combination exists
if (same_cards != None):
#Discard the card to the table
self.table.dispose_card(same_cards)
#Returns the player name
def toString(self):
return self.name
master.py
class Master():
def __init__(self,player_list):
self.player_list = player_list
def prepare_game(self,hand):
print("[Distribute cards]\n")
#Shuffle playing cards
hand.shuffle()
#Get the number of playing cards
number_of_cards = hand.getNumberOfCard()
#Get the number of players
number_of_players = len(self.player_list)
for index in range(number_of_cards):
#Draw one from the card
card = hand.pick_card()
#Deal cards to each player in turn
player = self.player_list[index % number_of_players]
player.receive_card(card)
#Start the game.
def start_game(self):
print("\n [Old Maid will start]\n")
#Get the number of players
count = 0
while len(self.player_list) > 1:
player_index = count % len(self.player_list)
next_player_index = (count + 1) % len(self.player_list)
#Acquiring a designated player
player = self.player_list[player_index]
#Get the next player
next_player = self.player_list[next_player_index]
#Nominate a player
print("\n", player.name, "It's your turn--- ({})".format(count), "\n")
player.play(next_player)
count += 1
#Exit the loop when the player goes up and there is only one left
print("[Old Maid finished]\n")
#Declare the rise.
def declare_win(self,winner):
#Player who went up
print(winner.name, "Got up!\n")
#Remove the raised player from the list
self.player_list.remove(winner)
#Show loser when there is only one player left
if len(self.player_list) == 1:
loser = self.player_list[0]
print(loser.name, "Is defeated!\n")
#Register the players who will participate in the game.
def register_player(self,player):
self.player_list.append(player)
old_maid.py
from card import *
from hand import *
from master import *
from player import *
from table import *
#Old Maid program.
#Generate 53 playing cards.
def create_trump():
trump = Hand([])
#Generate 13 cards for each suit
for i in range(13):
number = i + 1
trump.add_card(Card("SUIT_CLUB", number))
trump.add_card(Card("SUIT_DIAMOND", number))
trump.add_card(Card("SUIT_HEART", number))
trump.add_card(Card("SUIT_SPADE", number))
#Creating a joker
trump.add_card(Card(0, 0))
return trump
#Generating facilitators
master = Master([])
#Field generation
field = Table()
#Player generation
murata = Player("Murata", Hand([]), master, field)
yamada = Player("Yamada", Hand([]), master, field)
saito = Player("Saito", Hand([]),master, field)
#Register player as facilitator
master.register_player(murata)
master.register_player(yamada)
master.register_player(saito)
#Generate playing cards
trump = create_trump()
#Get ready for the game
master.prepare_game(trump)
#Start the game
master.start_game()
・ Since it was skipped, it is omitted. There are two points to be aware of:
-When creating an abstract class with python, it is necessary to import ABC (Abstract Base Classes) and inherit the abstract class. → Reference: ABC in Python-Abstract Classes and Duck Typing
· Must be passed by value when the table class returns table information
table.py
class FantanTable(Table):
#Table created with numpy
matrix = np.full((4,13),"..")
def getCard(self):
return self.matrix.copy()
Recommended Posts