Skip to content

Commit

Permalink
Merge pull request #19 from taKana671/develop_refactoring
Browse files Browse the repository at this point in the history
Develop refactoring
  • Loading branch information
taKana671 authored Dec 4, 2021
2 parents 41d2869 + 9abfbf5 commit dcd8fad
Show file tree
Hide file tree
Showing 6 changed files with 143 additions and 122 deletions.
42 changes: 26 additions & 16 deletions PlayingCards/base.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,32 @@
import os
import pathlib
import random
import tkinter as tk
from collections import namedtuple

from Globals import (BACK, PIN, BOARD_HEIGHT, BOARD_WIDTH, BOARD_COLOR,
IMAGE_ROOT, PIN_OFFSET_X, PIN_OFFSET_y)
IMAGE_ROOT, CARD_ROOT, PIN_OFFSET_X, PIN_OFFSET_y)


CardFace = namedtuple('CardFace', 'image mark value')


class Deck:

def __init__(self):
parent_dir = pathlib.Path(__file__).parent.resolve()
self.cards_dir = parent_dir / CARD_ROOT

def __getitem__(self, position):
return self._deck[position]

def __len__(self):
return len(self._deck)

def shuffle(self):
random.shuffle(self._deck)


class BaseCard:

__slots__ = ('id', 'face', 'x', 'y', 'face_up', 'dele', 'pin')
Expand Down Expand Up @@ -38,14 +56,15 @@ def image(self):
class BaseBoard(tk.Canvas):

def __init__(self, master, status_text, delay, sounds):
super().__init__(
master, width=BOARD_WIDTH, height=BOARD_HEIGHT, bg=BOARD_COLOR)
parent_dir = pathlib.Path(__file__).parent.resolve()
self.images_dir = parent_dir / IMAGE_ROOT
self.status_text = status_text
self.delay = delay
self.deck = [face for face in self.create_card()]
self.back = self.get_image(BACK)
self.pin = self.get_image(PIN)
self.sounds = sounds
super().__init__(
master, width=BOARD_WIDTH, height=BOARD_HEIGHT, bg=BOARD_COLOR)
self.pack(fill=tk.BOTH, expand=True)
# self.new_game()

Expand All @@ -56,24 +75,15 @@ def new_game(self):
"""
raise NotImplementedError()

def create_card(self):
"""
Override this method in subclasses to
yield CardFace instance.
"""
raise NotImplementedError()

def is_game_end(self):
"""Override this method in subclasses to sound a fanfare
when winning the game.
"""
pass

def get_image(self, file):
image_path = os.path.join(os.path.dirname(
os.path.realpath(__file__)), IMAGE_ROOT)
return tk.PhotoImage(
file=os.path.join(image_path, '{}.png'.format(file)))
image_path = self.images_dir / f'{file}.png'
return tk.PhotoImage(file=image_path)

def get_tag(self, event):
item_id = self.find_closest(event.x, event.y)[0]
Expand Down Expand Up @@ -113,7 +123,7 @@ def set_pins(self, *cards):
card.x + PIN_OFFSET_X,
card.y - PIN_OFFSET_y,
image=self.pin,
tags='pin{}'.format(card.id)
tags=f'pin{card.id}'
)
card.pin = item_id

Expand Down
43 changes: 23 additions & 20 deletions PlayingCards/couple.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
import os
import random
import tkinter as tk
from collections import namedtuple

from base import BaseBoard, BaseCard, CardFace
from base import BaseBoard, BaseCard, CardFace, Deck
from Globals import BOARD_WIDTH, BOARD_HEIGHT, CARD_ROOT, MOVE_SPEED


Expand All @@ -20,7 +18,21 @@
MoveCard = namedtuple('MoveCard', ['card', 'dest_x', 'dest_y'])


class Card(BaseCard):
class CoupleDeck(Deck):

def __init__(self):
super().__init__()
self._deck = [card for card in self.get_cards()]

def get_cards(self):
for path in self.cards_dir.iterdir():
name = path.stem
mark, value = name.split('_')
if not mark.startswith('jocker'):
yield CardFace(tk.PhotoImage(file=path), mark, int(value))


class CardOnBoard(BaseCard):

__slots__ = ('order')

Expand All @@ -32,19 +44,20 @@ def __init__(self, item_id, face, x, y, face_up=False, order=None):
class Board(BaseBoard):

def __init__(self, master, status_text, sounds, delay=400):
super().__init__(master, status_text, delay, sounds)
self.row_position = 0
self.col_position = 0
self.selected = []
self.now_moving = False
self.ybar = None
self.ybar_pos = 0.0
super().__init__(master, status_text, delay, sounds)
self.deck = CoupleDeck()

def new_game(self):
self.delete('all')
# config() changes attributes after creating object.
self.config(width=BOARD_WIDTH, height=BOARD_HEIGHT)
random.shuffle(self.deck)
self.deck.shuffle()
self.playing_cards = {}
self.setup_cards(self.deck[:12])
self.set_stock_cards(self.deck[12:])
Expand Down Expand Up @@ -76,16 +89,6 @@ def get_tag(self, event):
tag = self.gettags(item_id)[0]
return tag

def create_card(self):
image_path = os.path.join(os.path.dirname(
os.path.realpath(__file__)), CARD_ROOT)
for path in os.listdir(image_path):
name = os.path.splitext(path)[0]
mark, value = name.split('_')
if not mark.startswith('jocker'):
yield CardFace(tk.PhotoImage(
file=os.path.join(image_path, path)), mark, int(value))

def setup_cards(self, cards):
self.col_position, self.row_position = 0, 0
for i, face in enumerate(cards):
Expand All @@ -94,18 +97,18 @@ def setup_cards(self, cards):
self.col_position = CARD_X
else:
self.col_position += SPACE
name = 'card{}'.format(i)
name = f'card{i}'
item_id = self.create_image(
self.col_position, self.row_position, image=face.image, tags=name)
card = Card(item_id, face, self.col_position, self.row_position, True, i)
card = CardOnBoard(item_id, face, self.col_position, self.row_position, True, i)
self.playing_cards[name] = card

def set_stock_cards(self, cards):
x, y = STOCK_X, STOCK_Y
for i, face in enumerate(cards):
name = 'stock{}'.format(i)
name = f'stock{i}'
item_id = self.create_image(x, y, image=self.back, tags=name)
card = Card(item_id, face, x, y, order=i)
card = CardOnBoard(item_id, face, x, y, order=i)
self.playing_cards[name] = card
x += STACK_OFFSET
y -= STACK_OFFSET
Expand Down
45 changes: 24 additions & 21 deletions PlayingCards/fourleafclover.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
import os
import random
import tkinter as tk
from collections import namedtuple

from base import BaseBoard, BaseCard, CardFace
from base import BaseBoard, BaseCard, CardFace, Deck
from Globals import BOARD_WIDTH, BOARD_HEIGHT, CARD_ROOT, MOVE_SPEED


Expand All @@ -16,7 +14,21 @@
STOCK_Y = BOARD_HEIGHT - 100


class Card(BaseCard):
class FourLeafCloverDeck(Deck):

def __init__(self):
super().__init__()
self._deck = [card for card in self.get_cards()]

def get_cards(self):
for path in self.cards_dir.iterdir():
name = path.stem
mark, value = name.split('_')
if not mark.startswith('jocker') and value != '10':
yield CardFace(tk.PhotoImage(file=path), mark, int(value))


class CardOnBoard(BaseCard):

__slots__ = ('order')

Expand All @@ -28,40 +40,31 @@ def __init__(self, item_id, face, x, y, face_up=False, order=None):
class Board(BaseBoard):

def __init__(self, master, status_text, sounds, delay=400, rows=4, columns=4):
super().__init__(master, status_text, delay, sounds)
self.rows = rows
self.columns = columns
self.selected = []
self.now_moving = False
super().__init__(master, status_text, delay, sounds)
self.deck = FourLeafCloverDeck()

def new_game(self):
self.delete('all')
# config() changes attributes after creating object.
self.config(width=BOARD_WIDTH, height=BOARD_HEIGHT)
random.shuffle(self.deck)
self.deck.shuffle()
self.playing_cards = {}
sep = self.rows * self.columns
self.setup_cards(self.deck[:sep])
self.setup_stock(self.deck[sep:])
for name in self.playing_cards.keys():
self.tag_bind(name, '<ButtonPress-1>', self.click)

def create_card(self):
image_path = os.path.join(os.path.dirname(
os.path.realpath(__file__)), CARD_ROOT)
for path in os.listdir(image_path):
name = os.path.splitext(path)[0]
mark, value = name.split('_')
if not mark.startswith('jocker') and value != '10':
yield CardFace(tk.PhotoImage(
file=os.path.join(image_path, path)), mark, int(value))

def setup_cards(self, cards):
x, y = CARD_X, CARD_Y
for i, face in enumerate(cards, 1):
name = 'card{}'.format(i)
name = f'card{i}'
item_id = self.create_image(x, y, image=face.image, tags=name)
card = Card(item_id, face, x, y, True, i)
card = CardOnBoard(item_id, face, x, y, True, i)
self.playing_cards[name] = card
x += SPACE
if i % self.columns == 0:
Expand All @@ -71,9 +74,9 @@ def setup_cards(self, cards):
def setup_stock(self, cards):
x, y = STOCK_X, STOCK_Y
for i, face in enumerate(cards):
name = 'stock{}'.format(i)
name = f'stock{i}'
item_id = self.create_image(x, y, image=self.back, tags=name)
card = Card(item_id, face, x, y)
card = CardOnBoard(item_id, face, x, y)
self.playing_cards[name] = card
x += STACK_OFFSET
y -= STACK_OFFSET
Expand Down Expand Up @@ -154,7 +157,7 @@ def run_move_sequence(self):
self.now_moving = False

def update_status(self):
text = ', '.join(['{} {}'.format(card.mark, card.value) for card in self.selected])
text = ', '.join([f'{card.mark} {card.value}' for card in self.selected])
self.status_text.set(text)

def is_game_end(self):
Expand Down
Loading

0 comments on commit dcd8fad

Please sign in to comment.