diff --git a/.coveragerc b/.coveragerc new file mode 100644 index 0000000..c41b23c --- /dev/null +++ b/.coveragerc @@ -0,0 +1,2 @@ +[run] +omit = */tests/* \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..7cebde4 --- /dev/null +++ b/.gitignore @@ -0,0 +1,110 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +.hypothesis/ +.pytest_cache/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# pyenv +.python-version + +# celery beat schedule file +celerybeat-schedule + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ + +# Pycharm project +.idea/ + +# VSCode project +.vscode/ \ No newline at end of file diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..7606407 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,11 @@ +language: python +python: + - "3.6" + +# Command to run tests +install: + - pip3 install -r requirements.txt +script: + - python -m pytest --cov=src +after_success: + - coveralls diff --git a/ExamplePygame/Stars/class_enum.py b/ExamplePygame/Stars/class_enum.py new file mode 100644 index 0000000..362bd2c --- /dev/null +++ b/ExamplePygame/Stars/class_enum.py @@ -0,0 +1,42 @@ +class Enum: + """ + A C++ like enum + + :param args: a list of strings + + :Example: + + enum = Enum( + "splash", + "mainMenu", + "quit" + ) + + state = enum.splash + + if state == enum.splash: + state = enum.mainMenu + else: + state = enum.quit + + enum.print(state) + """ + + def __init__(self, *args): + + self.__i = 0 + self.__names = args + + for name in args: + setattr(self, name, self.__i) + self.__i += 1 + + def print(self, i: int, **kwargs): + """ + Print the name of the enum + + :param i: the value of the Enum + :param kwargs: the common keyword arguments for the print function + """ + + print(self.__names[i], **kwargs) diff --git a/ExamplePygame/Stars/class_star.py b/ExamplePygame/Stars/class_star.py new file mode 100644 index 0000000..b85713f --- /dev/null +++ b/ExamplePygame/Stars/class_star.py @@ -0,0 +1,28 @@ +import pygame + + +class Star(pygame.sprite.Sprite): + """ + A shooting star + + kwargs is used to define where the rect is placed + """ + + speed = 2 + images = list() + screenRect = None + + def __init__(self, **kwargs): + pygame.sprite.Sprite.__init__(self, self.containers) + + self.image = self.images[0] + self.rect = self.image.get_rect(**kwargs) + + def update(self): + """ + Update the star at each iteration + """ + + self.rect.move_ip(self.speed, 0) + if not self.screenRect.contains(self.rect): + self.kill() diff --git a/ExamplePygame/Stars/constants.py b/ExamplePygame/Stars/constants.py new file mode 100644 index 0000000..911f4ba --- /dev/null +++ b/ExamplePygame/Stars/constants.py @@ -0,0 +1,17 @@ +import os + +from class_enum import Enum + + +DIRMAIN = os.path.dirname(__file__) +DIRFILES = os.path.join(DIRMAIN, "files") +DIRIMAGES = os.path.join(DIRMAIN, "images") +DIRSOUNDS = os.path.join(DIRMAIN, "sounds") + + +ENUM = Enum( + "splash", + "mainmenu", + "play", + "quit" +) diff --git a/ExamplePygame/Stars/func_images.py b/ExamplePygame/Stars/func_images.py new file mode 100644 index 0000000..c7e480d --- /dev/null +++ b/ExamplePygame/Stars/func_images.py @@ -0,0 +1,22 @@ +import os + +import pygame + +from constants import DIRIMAGES + + +def load_image(filename: str) -> pygame.Surface: + """ + Loads an image and prepares it + + :param filename: the path to the image + :return: the image converted + """ + + try: + surface = pygame.image.load(os.path.join(DIRIMAGES, filename)) + except pygame.error: + error = "Could not load image \"%s\" %s" % (filename, pygame.get_error()) + raise SystemExit(error) + + return surface.convert() diff --git a/ExamplePygame/Stars/main.py b/ExamplePygame/Stars/main.py new file mode 100644 index 0000000..d28bdb5 --- /dev/null +++ b/ExamplePygame/Stars/main.py @@ -0,0 +1,77 @@ +import os +import json + +import pygame +from pygame.locals import * + +from constants import * +from screen_splash import screen_splash +from screen_mainmenu import screen_mainmenu +from screen_play import screen_play + + +class Main: + """ + The main application + """ + + def __init__(self): + + # Configuration + self.load_config() + + # Init pygame + self.init_pygame() + + # mainloop + self.mainloop() + + def load_config(self): + """ + Load the configuration file + """ + + fileConfig = os.path.join(DIRFILES, "config.json") + with open(fileConfig, "r", encoding="utf-8") as f: + self.config = json.load(f) + + def init_pygame(self): + """ + Intialize the main screen + """ + + size = self.config["screen"]["size"] + self.screenRect = Rect(0, 0, *size) + + pygame.init() + pygame.font.init() + + self.window = pygame.display.set_mode(self.screenRect.size) + + def mainloop(self): + """ + The mainloop the launch the game + """ + + state, param = screen_splash(self.window) + + while state != ENUM.quit: + + ENUM.print(state) + + if state == ENUM.mainmenu: + state, param = screen_mainmenu(self.window, param) + + elif state == ENUM.play: + param["config"] = self.config + param["screenRect"] = self.screenRect + state, param = screen_play(self.window, param) + + else: + state = ENUM.quit + + pygame.quit() + + +if __name__ == '__main__': + Main() diff --git a/ExamplePygame/Stars/screen_mainmenu.py b/ExamplePygame/Stars/screen_mainmenu.py new file mode 100644 index 0000000..8a3f896 --- /dev/null +++ b/ExamplePygame/Stars/screen_mainmenu.py @@ -0,0 +1,37 @@ +import pygame +from pygame.locals import * + +from constants import * + + +def screen_mainmenu(window: pygame.Surface, param: dict = dict()) -> tuple: + """ + The splash screen + + :param window: The main window where to display the game + :param param: Some parameters from another screen + :return: The state of the next screen and a dict with some parameters + """ + + state = ENUM.mainmenu + + font = pygame.font.SysFont('Comic Sans MS', 30) + textSurface = font.render('Main Menu', False, (0, 0, 0)) + + window.fill((0, 127, 127)) + window.blit(textSurface, (0, 0)) + + while state == ENUM.mainmenu: + + # Check for events + for event in pygame.event.get(): + if event.type == QUIT: + state = ENUM.quit + elif (event.type == KEYDOWN and event.key == K_ESCAPE): + state = ENUM.quit + elif (event.type == KEYDOWN and event.key == K_RETURN): + state = ENUM.play + + pygame.display.flip() + + return state, dict() diff --git a/ExamplePygame/Stars/screen_play.py b/ExamplePygame/Stars/screen_play.py new file mode 100644 index 0000000..4a79fc1 --- /dev/null +++ b/ExamplePygame/Stars/screen_play.py @@ -0,0 +1,77 @@ +import pygame +from pygame.locals import * + +from class_star import Star +from func_images import load_image +from constants import * + + +def screen_play(window: pygame.Surface, param: dict = dict()) -> tuple: + """ + The splash screen + + :param window: The main window where to display the game + :param param: Some parameters from another screen + :return: The state of the next screen and a dict with some parameters + """ + + state = ENUM.play + config = param["config"] + screenRect = param["screenRect"] + + # font = pygame.font.SysFont('Comic Sans MS', 30) + # textSurface = font.render('Play', False, (255, 255, 255)) + + # Load images, sounds and init the star object + img = load_image(config["images"]["star"]) + Star.images = [img, pygame.transform.flip(img, 1, 0)] + Star.screenRect = screenRect + star_sound = pygame.mixer.Sound("sounds/boom.wav") + + # Load the background and diisplay it on screen + bgdtile = load_image(config["images"]["background"]) + background = pygame.Surface(screenRect.size) + for x in range(0, screenRect.width, bgdtile.get_width()): # from, to, step + background.blit(bgdtile, (x, 0)) + window.blit(background, (0, 0)) + + pygame.display.flip() + + # Init sprites + star = pygame.sprite.Group() + all_sprites = pygame.sprite.RenderUpdates() + star_last = pygame.sprite.GroupSingle() + + Star.containers = star, all_sprites, star_last + + # Init the loop + clock = pygame.time.Clock() + Star(midleft=screenRect.midleft) + + while state == ENUM.play: + + # clear/erase the last drawn sprites + all_sprites.clear(window, background) + all_sprites.update() + + # Check for events + for event in pygame.event.get(): + if event.type == QUIT: + state = ENUM.quit + elif (event.type == KEYDOWN and event.key == K_ESCAPE): + state = ENUM.quit + elif (event.type == KEYDOWN and event.key == K_RETURN): + state = ENUM.mainmenu + + if event.type == pygame.MOUSEBUTTONUP: + star_sound.play() + pos = pygame.mouse.get_pos() + Star(center=pos) + + # draw the scene + dirty = all_sprites.draw(window) + pygame.display.update(dirty) + + clock.tick(40) + + return state, dict() diff --git a/ExamplePygame/Stars/screen_splash.py b/ExamplePygame/Stars/screen_splash.py new file mode 100644 index 0000000..b2fea1e --- /dev/null +++ b/ExamplePygame/Stars/screen_splash.py @@ -0,0 +1,37 @@ +import pygame +from pygame.locals import * + +from constants import * + + +def screen_splash(window: pygame.Surface, param: dict = dict()) -> tuple: + """ + The splash screen + + :param window: The main window where to display the game + :param param: Some parameters from another screen + :return: The state of the next screen and a dict with some parameters + """ + + state = ENUM.splash + + font = pygame.font.SysFont('Comic Sans MS', 30) + textSurface = font.render('Splash Screen', False, (0, 0, 0)) + + window.fill((0, 0, 255)) + window.blit(textSurface, (0, 0)) + + while state == ENUM.splash: + + # Check for events + for event in pygame.event.get(): + if event.type == QUIT: + state = ENUM.quit + elif (event.type == KEYDOWN and event.key == K_ESCAPE): + state = ENUM.quit + elif (event.type == KEYDOWN and event.key == K_RETURN): + state = ENUM.mainmenu + + pygame.display.flip() + + return state, dict() diff --git a/ExamplePygame/Stars/stars.py b/ExamplePygame/Stars/stars.py index 71dc069..19aeeae 100644 --- a/ExamplePygame/Stars/stars.py +++ b/ExamplePygame/Stars/stars.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - """ This example is based on an official example. It is located on the local directory of pygame: @@ -50,7 +48,7 @@ def load_image(file): class Star(pygame.sprite.Sprite): """ - A shouting star + A shooting star """ speed = 2 diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..94a9ed0 --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/README.md b/README.md index 382d7c3..de979f2 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,26 @@ # BlackJackProject +[![Build Status](https://travis-ci.com/Hackiflette/BlackJackProject.svg?branch=bug_fix)](https://travis-ci.com/Hackiflette/BlackJackProject) +[![License: GPL v3](https://img.shields.io/badge/License-GPL%20v3-blue.svg)](https://www.gnu.org/licenses/gpl-3.0) +[![Coverage Status](https://coveralls.io/repos/github/Hackiflette/BlackJackProject/badge.svg?branch=codecoverage)](https://coveralls.io/github/Hackiflette/BlackJackProject?branch=bug_fix) + This project is the first of the Hackiflette team ! -This game is a Black Jack game, with the possibility to play with multiple player, on the same computer or in differents computer on the same network. +This game is a famous card game, **Black Jack**. It will have the possibility to be played with friends, in a multiplayer mode, on the same computer, or maybe on differents computer on the same network. + +# The Hackiflette team + +We are 8 friends who liked programming, and playing. So we created Hackiflette to develop games and improve our programing skills. +For our first project, we decided to develop a simple card game : Black Jack is our final choice. + +# How to play !? -# For dev team +Our project is a python project, so for now you need to have python (version >= 3.5) installed on your computer to launch it. +You also need the following packages: +* pygame = 1.9.4 +* marshmallow = 2.19.5 +* typing = 3.6.6 +* dataclasses = 0.6 +* ... -To clone this respository, use the command : - git clone https://github.com/Cataboum/BlackJackProject.git \ No newline at end of file +After download the project, you just have to launch the main.py in the src directory. \ No newline at end of file diff --git a/data/config/game_view.cfg.json b/data/config/game_view.cfg.json new file mode 100644 index 0000000..05935b2 --- /dev/null +++ b/data/config/game_view.cfg.json @@ -0,0 +1,88 @@ +{ + "window": { + "x": 0, + "y": 0, + "width": 1200, + "height": 700 + }, + "game_buttons": { + "card": { + "text": "(1) Card", + "pos": [40, 610], + "size": [120, 74], + "bg_normal": [30, 193, 130], + "bg_hover": [40, 200, 150], + "bg_pressed": [30, 135, 90] + }, + "bet": { + "text": "(2) Bet", + "pos": [240, 610], + "size": [120, 74], + "bg_normal": [30, 193, 130], + "bg_hover": [40, 200, 150], + "bg_pressed": [30, 135, 90] + }, + "end_turn": { + "text": "(3) End Turn", + "pos": [440, 610], + "size": [120, 74], + "bg_normal": [30, 193, 130], + "bg_hover": [40, 200, 150], + "bg_pressed": [30, 135, 90] + }, + "split": { + "text": "(4) Split", + "pos": [640, 610], + "size": [120, 74], + "bg_normal": [30, 193, 130], + "bg_hover": [40, 200, 150], + "bg_pressed": [30, 135, 90] + }, + "double": { + "text": "(5) Double", + "pos": [840, 610], + "size": [120, 74], + "bg_normal": [30, 193, 130], + "bg_hover": [40, 200, 150], + "bg_pressed": [30, 135, 90] + }, + "quit": { + "text": "(6) Quit", + "pos": [1040, 610], + "size": [120, 74], + "bg_normal": [193, 130, 30], + "bg_hover": [200, 150, 40], + "bg_pressed": [135, 90, 30] + } + }, + "game_menu_area": { + "x": 0, + "y": 600, + "width": 1200, + "height": 100, + "color": [50, 50, 50] + }, + "card_areas": { + "extra_card_offset": { + "x": 15, + "y": 15 + }, + "dealer": { + "x": 550, + "y": 50 + }, + "player": { + "x": 200, + "y": 450, + "width": 700 + } + }, + "cards": { + "height": 150, + "width": 100 + }, + "tokens": { + "height": 50, + "width": 50 + } +} \ No newline at end of file diff --git a/data/config/menu.cfg.json b/data/config/menu.cfg.json new file mode 100644 index 0000000..623932c --- /dev/null +++ b/data/config/menu.cfg.json @@ -0,0 +1,20 @@ +{ + "window": { + "width": 1200, + "height": 700 + }, + "menu_buttons": { + "play_btn": { + "x": 300, + "y": 200 + }, + "option_btn": { + "x": 300, + "y": 300 + }, + "quit_btn": { + "x": 300, + "y": 400 + } + } +} diff --git a/data/config/path.cfg.json b/data/config/path.cfg.json new file mode 100644 index 0000000..3451f44 --- /dev/null +++ b/data/config/path.cfg.json @@ -0,0 +1,15 @@ +{ + "folders": { + "main": ["."], + "data": ["data"], + "config": ["data", "config"], + "pictures": ["data", "pictures"], + "cards": ["data", "pictures", "cards"], + "cards_svg": ["data", "pictures", "cards_svg"], + "tokens": ["data", "pictures", "tokens"], + "src": ["src"] + }, + "files": { + "tokens": ["config", "tokens.cfg.json"] + } +} diff --git a/data/config/tokens.cfg.json b/data/config/tokens.cfg.json new file mode 100644 index 0000000..ac727cc --- /dev/null +++ b/data/config/tokens.cfg.json @@ -0,0 +1,7 @@ +{ + "1": "token_white.png", + "5": "token_red.png", + "10": "token_blue.png", + "25": "token_green.png", + "100": "token_black.png" +} \ No newline at end of file diff --git a/data/pictures/blackjack_table.png b/data/pictures/blackjack_table.png new file mode 100644 index 0000000..bd129b9 Binary files /dev/null and b/data/pictures/blackjack_table.png differ diff --git a/data/pictures/cards/10_of_clubs.png b/data/pictures/cards/10_of_clubs.png new file mode 100644 index 0000000..18af741 Binary files /dev/null and b/data/pictures/cards/10_of_clubs.png differ diff --git a/data/pictures/cards/10_of_diamonds.png b/data/pictures/cards/10_of_diamonds.png new file mode 100644 index 0000000..3bbc4e0 Binary files /dev/null and b/data/pictures/cards/10_of_diamonds.png differ diff --git a/data/pictures/cards/10_of_hearts.png b/data/pictures/cards/10_of_hearts.png new file mode 100644 index 0000000..3eb83d7 Binary files /dev/null and b/data/pictures/cards/10_of_hearts.png differ diff --git a/data/pictures/cards/10_of_spades.png b/data/pictures/cards/10_of_spades.png new file mode 100644 index 0000000..0b3d294 Binary files /dev/null and b/data/pictures/cards/10_of_spades.png differ diff --git a/data/pictures/cards/2_of_clubs.png b/data/pictures/cards/2_of_clubs.png new file mode 100644 index 0000000..291ed97 Binary files /dev/null and b/data/pictures/cards/2_of_clubs.png differ diff --git a/data/pictures/cards/2_of_diamonds.png b/data/pictures/cards/2_of_diamonds.png new file mode 100644 index 0000000..4deee7c Binary files /dev/null and b/data/pictures/cards/2_of_diamonds.png differ diff --git a/data/pictures/cards/2_of_hearts.png b/data/pictures/cards/2_of_hearts.png new file mode 100644 index 0000000..75a014f Binary files /dev/null and b/data/pictures/cards/2_of_hearts.png differ diff --git a/data/pictures/cards/2_of_spades.png b/data/pictures/cards/2_of_spades.png new file mode 100644 index 0000000..1ce0ffe Binary files /dev/null and b/data/pictures/cards/2_of_spades.png differ diff --git a/data/pictures/cards/3_of_clubs.png b/data/pictures/cards/3_of_clubs.png new file mode 100644 index 0000000..076ab31 Binary files /dev/null and b/data/pictures/cards/3_of_clubs.png differ diff --git a/data/pictures/cards/3_of_diamonds.png b/data/pictures/cards/3_of_diamonds.png new file mode 100644 index 0000000..8ee0b4b Binary files /dev/null and b/data/pictures/cards/3_of_diamonds.png differ diff --git a/data/pictures/cards/3_of_hearts.png b/data/pictures/cards/3_of_hearts.png new file mode 100644 index 0000000..8e74673 Binary files /dev/null and b/data/pictures/cards/3_of_hearts.png differ diff --git a/data/pictures/cards/3_of_spades.png b/data/pictures/cards/3_of_spades.png new file mode 100644 index 0000000..f9e06b4 Binary files /dev/null and b/data/pictures/cards/3_of_spades.png differ diff --git a/data/pictures/cards/4_of_clubs.png b/data/pictures/cards/4_of_clubs.png new file mode 100644 index 0000000..8be9e08 Binary files /dev/null and b/data/pictures/cards/4_of_clubs.png differ diff --git a/data/pictures/cards/4_of_diamonds.png b/data/pictures/cards/4_of_diamonds.png new file mode 100644 index 0000000..70e82e8 Binary files /dev/null and b/data/pictures/cards/4_of_diamonds.png differ diff --git a/data/pictures/cards/4_of_hearts.png b/data/pictures/cards/4_of_hearts.png new file mode 100644 index 0000000..ceecbfe Binary files /dev/null and b/data/pictures/cards/4_of_hearts.png differ diff --git a/data/pictures/cards/4_of_spades.png b/data/pictures/cards/4_of_spades.png new file mode 100644 index 0000000..95abe3e Binary files /dev/null and b/data/pictures/cards/4_of_spades.png differ diff --git a/data/pictures/cards/5_of_clubs.png b/data/pictures/cards/5_of_clubs.png new file mode 100644 index 0000000..bde9777 Binary files /dev/null and b/data/pictures/cards/5_of_clubs.png differ diff --git a/data/pictures/cards/5_of_diamonds.png b/data/pictures/cards/5_of_diamonds.png new file mode 100644 index 0000000..bb92525 Binary files /dev/null and b/data/pictures/cards/5_of_diamonds.png differ diff --git a/data/pictures/cards/5_of_hearts.png b/data/pictures/cards/5_of_hearts.png new file mode 100644 index 0000000..d923456 Binary files /dev/null and b/data/pictures/cards/5_of_hearts.png differ diff --git a/data/pictures/cards/5_of_spades.png b/data/pictures/cards/5_of_spades.png new file mode 100644 index 0000000..53a1aad Binary files /dev/null and b/data/pictures/cards/5_of_spades.png differ diff --git a/data/pictures/cards/6_of_clubs.png b/data/pictures/cards/6_of_clubs.png new file mode 100644 index 0000000..a9660a0 Binary files /dev/null and b/data/pictures/cards/6_of_clubs.png differ diff --git a/data/pictures/cards/6_of_diamonds.png b/data/pictures/cards/6_of_diamonds.png new file mode 100644 index 0000000..78a80ad Binary files /dev/null and b/data/pictures/cards/6_of_diamonds.png differ diff --git a/data/pictures/cards/6_of_hearts.png b/data/pictures/cards/6_of_hearts.png new file mode 100644 index 0000000..361643e Binary files /dev/null and b/data/pictures/cards/6_of_hearts.png differ diff --git a/data/pictures/cards/6_of_spades.png b/data/pictures/cards/6_of_spades.png new file mode 100644 index 0000000..40242a7 Binary files /dev/null and b/data/pictures/cards/6_of_spades.png differ diff --git a/data/pictures/cards/7_of_clubs.png b/data/pictures/cards/7_of_clubs.png new file mode 100644 index 0000000..9d6b545 Binary files /dev/null and b/data/pictures/cards/7_of_clubs.png differ diff --git a/data/pictures/cards/7_of_diamonds.png b/data/pictures/cards/7_of_diamonds.png new file mode 100644 index 0000000..6ad5f15 Binary files /dev/null and b/data/pictures/cards/7_of_diamonds.png differ diff --git a/data/pictures/cards/7_of_hearts.png b/data/pictures/cards/7_of_hearts.png new file mode 100644 index 0000000..19b89a2 Binary files /dev/null and b/data/pictures/cards/7_of_hearts.png differ diff --git a/data/pictures/cards/7_of_spades.png b/data/pictures/cards/7_of_spades.png new file mode 100644 index 0000000..b9f1b93 Binary files /dev/null and b/data/pictures/cards/7_of_spades.png differ diff --git a/data/pictures/cards/8_of_clubs.png b/data/pictures/cards/8_of_clubs.png new file mode 100644 index 0000000..cec743c Binary files /dev/null and b/data/pictures/cards/8_of_clubs.png differ diff --git a/data/pictures/cards/8_of_diamonds.png b/data/pictures/cards/8_of_diamonds.png new file mode 100644 index 0000000..ed12951 Binary files /dev/null and b/data/pictures/cards/8_of_diamonds.png differ diff --git a/data/pictures/cards/8_of_hearts.png b/data/pictures/cards/8_of_hearts.png new file mode 100644 index 0000000..fb39723 Binary files /dev/null and b/data/pictures/cards/8_of_hearts.png differ diff --git a/data/pictures/cards/8_of_spades.png b/data/pictures/cards/8_of_spades.png new file mode 100644 index 0000000..b6b3b38 Binary files /dev/null and b/data/pictures/cards/8_of_spades.png differ diff --git a/data/pictures/cards/9_of_clubs.png b/data/pictures/cards/9_of_clubs.png new file mode 100644 index 0000000..2174db5 Binary files /dev/null and b/data/pictures/cards/9_of_clubs.png differ diff --git a/data/pictures/cards/9_of_diamonds.png b/data/pictures/cards/9_of_diamonds.png new file mode 100644 index 0000000..0b933fb Binary files /dev/null and b/data/pictures/cards/9_of_diamonds.png differ diff --git a/data/pictures/cards/9_of_hearts.png b/data/pictures/cards/9_of_hearts.png new file mode 100644 index 0000000..7b196d6 Binary files /dev/null and b/data/pictures/cards/9_of_hearts.png differ diff --git a/data/pictures/cards/9_of_spades.png b/data/pictures/cards/9_of_spades.png new file mode 100644 index 0000000..3c3b5ff Binary files /dev/null and b/data/pictures/cards/9_of_spades.png differ diff --git a/data/pictures/cards/ace_of_clubs.png b/data/pictures/cards/ace_of_clubs.png new file mode 100644 index 0000000..42bf5ec Binary files /dev/null and b/data/pictures/cards/ace_of_clubs.png differ diff --git a/data/pictures/cards/ace_of_diamonds.png b/data/pictures/cards/ace_of_diamonds.png new file mode 100644 index 0000000..79cd3b8 Binary files /dev/null and b/data/pictures/cards/ace_of_diamonds.png differ diff --git a/data/pictures/cards/ace_of_hearts.png b/data/pictures/cards/ace_of_hearts.png new file mode 100644 index 0000000..b422124 Binary files /dev/null and b/data/pictures/cards/ace_of_hearts.png differ diff --git a/data/pictures/cards/ace_of_spades.png b/data/pictures/cards/ace_of_spades.png new file mode 100644 index 0000000..fbc3a2d Binary files /dev/null and b/data/pictures/cards/ace_of_spades.png differ diff --git a/data/pictures/cards/card_back_black.png b/data/pictures/cards/card_back_black.png new file mode 100644 index 0000000..2a43084 Binary files /dev/null and b/data/pictures/cards/card_back_black.png differ diff --git a/data/pictures/cards/jack_of_clubs.png b/data/pictures/cards/jack_of_clubs.png new file mode 100644 index 0000000..5e003be Binary files /dev/null and b/data/pictures/cards/jack_of_clubs.png differ diff --git a/data/pictures/cards/jack_of_diamonds.png b/data/pictures/cards/jack_of_diamonds.png new file mode 100644 index 0000000..131a977 Binary files /dev/null and b/data/pictures/cards/jack_of_diamonds.png differ diff --git a/data/pictures/cards/jack_of_hearts.png b/data/pictures/cards/jack_of_hearts.png new file mode 100644 index 0000000..bf342bc Binary files /dev/null and b/data/pictures/cards/jack_of_hearts.png differ diff --git a/data/pictures/cards/jack_of_spades.png b/data/pictures/cards/jack_of_spades.png new file mode 100644 index 0000000..f539c19 Binary files /dev/null and b/data/pictures/cards/jack_of_spades.png differ diff --git a/data/pictures/cards/king_of_clubs.png b/data/pictures/cards/king_of_clubs.png new file mode 100644 index 0000000..68e5774 Binary files /dev/null and b/data/pictures/cards/king_of_clubs.png differ diff --git a/data/pictures/cards/king_of_diamonds.png b/data/pictures/cards/king_of_diamonds.png new file mode 100644 index 0000000..e21d6a0 Binary files /dev/null and b/data/pictures/cards/king_of_diamonds.png differ diff --git a/data/pictures/cards/king_of_hearts.png b/data/pictures/cards/king_of_hearts.png new file mode 100644 index 0000000..1d3c468 Binary files /dev/null and b/data/pictures/cards/king_of_hearts.png differ diff --git a/data/pictures/cards/king_of_spades.png b/data/pictures/cards/king_of_spades.png new file mode 100644 index 0000000..2edbbc1 Binary files /dev/null and b/data/pictures/cards/king_of_spades.png differ diff --git a/data/pictures/cards/queen_of_clubs.png b/data/pictures/cards/queen_of_clubs.png new file mode 100644 index 0000000..7be5f9a Binary files /dev/null and b/data/pictures/cards/queen_of_clubs.png differ diff --git a/data/pictures/cards/queen_of_diamonds.png b/data/pictures/cards/queen_of_diamonds.png new file mode 100644 index 0000000..928f650 Binary files /dev/null and b/data/pictures/cards/queen_of_diamonds.png differ diff --git a/data/pictures/cards/queen_of_hearts.png b/data/pictures/cards/queen_of_hearts.png new file mode 100644 index 0000000..21839e6 Binary files /dev/null and b/data/pictures/cards/queen_of_hearts.png differ diff --git a/data/pictures/cards/queen_of_spades.png b/data/pictures/cards/queen_of_spades.png new file mode 100644 index 0000000..7983d03 Binary files /dev/null and b/data/pictures/cards/queen_of_spades.png differ diff --git a/data/pictures/green_carpet.jpeg b/data/pictures/green_carpet.jpeg new file mode 100644 index 0000000..65ba6df Binary files /dev/null and b/data/pictures/green_carpet.jpeg differ diff --git a/pictures/menu/background_menu.png b/data/pictures/menu/background_menu.png similarity index 100% rename from pictures/menu/background_menu.png rename to data/pictures/menu/background_menu.png diff --git a/data/pictures/menu/bgd_menu.png b/data/pictures/menu/bgd_menu.png new file mode 100644 index 0000000..e73ca13 Binary files /dev/null and b/data/pictures/menu/bgd_menu.png differ diff --git a/data/pictures/tokens/token_black.png b/data/pictures/tokens/token_black.png new file mode 100644 index 0000000..3545965 Binary files /dev/null and b/data/pictures/tokens/token_black.png differ diff --git a/data/pictures/tokens/token_blue.png b/data/pictures/tokens/token_blue.png new file mode 100644 index 0000000..8d0262e Binary files /dev/null and b/data/pictures/tokens/token_blue.png differ diff --git a/data/pictures/tokens/token_green.png b/data/pictures/tokens/token_green.png new file mode 100644 index 0000000..9c37e5e Binary files /dev/null and b/data/pictures/tokens/token_green.png differ diff --git a/data/pictures/tokens/token_red.png b/data/pictures/tokens/token_red.png new file mode 100644 index 0000000..52b200a Binary files /dev/null and b/data/pictures/tokens/token_red.png differ diff --git a/data/pictures/tokens/token_white.png b/data/pictures/tokens/token_white.png new file mode 100644 index 0000000..9fcc58f Binary files /dev/null and b/data/pictures/tokens/token_white.png differ diff --git a/main.py b/main.py new file mode 100644 index 0000000..2bf39cf --- /dev/null +++ b/main.py @@ -0,0 +1,133 @@ +# ============================================================================ +# = +# = Imports +# = +# ============================================================================ + +import os + +import pygame +from pygame.locals import ( + QUIT, + KEYDOWN, + K_ESCAPE, +) + +from src.common.constants import ( + Game, + CONFIG_MENU, + DIR_CONFIG, + DIR_SRC, + DIR_DATA, + DIR_PICTURES, +) +from src.common.game_view_config import game_view_config +from src.common.config import ConfigPath +from src.views import view_menu, view_option +from src.controller.game_controller import GameController +from src.views.image_loaders.cardsloader import CardsLoader +from src.views.image_loaders.tokensloader import TokensLoader + + +# ============================================================================ +# = +# = Application +# = +# ============================================================================ + + +class Main: + """ + The main application + """ + + def __init__(self): + + # Init pygame + self.game_window = None + self.menu_window = None + self.init_pygame() + + # Init GameController + self.ctrl = GameController(self.game_window) + + # Needs Pygame initialization + TokensLoader.initialize(ConfigPath.file("tokens")) + CardsLoader.initialize() + + # mainloop + self.main_loop() + + def init_pygame(self): + """ + Initialize the main screen + """ + + pygame.init() + pygame.display.set_caption("Black Jack by Hackiflette") + self.game_window = pygame.display.set_mode(( + game_view_config.window.width, + game_view_config.window.height, + )) + self.menu_window = pygame.display.set_mode(( + CONFIG_MENU["window"]["width"], + CONFIG_MENU["window"]["height"], + )) + + def main_loop(self): + """ + The mainloop the launch the game + """ + + state, param = view_menu.main( + self.menu_window, CONFIG_MENU["window"], CONFIG_MENU["menu_buttons"]) + + while state != Game.quit: + if state == Game.menu: + self.ctrl.reset_all_humans() + state, param = view_menu.main( + self.menu_window, CONFIG_MENU["window"], CONFIG_MENU["menu_buttons"]) + elif state == Game.play: + self.ctrl.game_launch() + state = self.game_loop() + # state, param = view_game.main(self.window, self.config["window"]) + elif state == Game.option: + state, param = view_option.main(self.menu_window, CONFIG_MENU["window"]) + else: + state = 0 + + pygame.quit() + + def game_loop(self): + """ + The loop of the game which communicate with controller + """ + state = Game.play + print("GameLoop") + + # First Create Player + self.ctrl.initiate_players() + + while state == Game.play: + for event in pygame.event.get(): + if event.type == QUIT: + state = Game.menu + elif event.type == KEYDOWN and event.key == K_ESCAPE: + state = Game.menu + elif event.type: + keep_playing = self.ctrl.first_round() + if keep_playing: + keep_playing = self.ctrl.play_one_round() + if not keep_playing: + # Player want to quit + state = Game.menu + print("gameLoop") + return state + + +if __name__ == '__main__': + print("Exists?") + for folder in [DIR_SRC, DIR_DATA, DIR_CONFIG, DIR_PICTURES]: + print(folder, os.path.exists(folder)) + + Main() diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..a2fe072 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,7 @@ +dataclasses==0.6 +marshmallow==2.19.5 +pygame==1.9.4 +typing==3.6.6 +python_coveralls>=2 +pytest-cov>=2 +coverage>4 \ No newline at end of file diff --git a/src/__init__.py b/src/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/button/__init__.py b/src/button/__init__.py new file mode 100644 index 0000000..8729f03 --- /dev/null +++ b/src/button/__init__.py @@ -0,0 +1 @@ +from .button import Button diff --git a/src/button/button.py b/src/button/button.py new file mode 100644 index 0000000..b57ed5b --- /dev/null +++ b/src/button/button.py @@ -0,0 +1,245 @@ +import enum +import pygame + +from src.common.utils import Signal + + +# ============================================================================ +# = +# = Enum +# = +# ============================================================================ + + +class State(enum.Enum): + normal = enum.auto() + hover = enum.auto() + pressed = enum.auto() + + +# ============================================================================= +# = +# = Button +# = +# ============================================================================= + + +class Button: + """ + Set attributes to the button + + :param pygame.Surface window: surface where to blit the button + :param 3-tuple bg_normal: color for normal background + :param 3-tuple bg_hover: color for background when hover + :param 3-tuple bg_pressed: color for background when pressed + :param int bd: border size + :param 3-tuple bd_color: color for the border + :param str text: text to display on button + :param dict text_font: {file: font family, size: font size} + :param 3-tuple text_color: color for the text + """ + + def __init__(self, window: pygame.Surface=None, **kwargs): + # Set attributes + self.window = window + self.state = State.normal + self.enabled = True + # Rectangle + self.rect = pygame.Rect(0, 0, 100, 80) + # Background + self.bg = None + self.bg_normal = None + self.bg_hover = None + self.bg_pressed = None + # Border + self.bd = 0 + self.bd_color = (0, 0, 0) + # Text + self.text = "Button" + self.text_font = {"file": None, "size": 30} + self.text_color = (0, 0, 0) + # command + self.signal = Signal() + + self.__setKwargs(**kwargs) + self.text_core = pygame.font.Font(None, 30) + + def __setKwargs(self, **kwargs): + """ + Set attributes to the button + + :param 3-tuple bg_normal: color for normal background + :param 3-tuple bg_hover: color for background when hover + :param 3-tuple bg_pressed: color for background when pressed + :param int bd: border size + :param 3-tuple bd_color: color for the border + :param str text: text to display on button + :param dict text_font: {file: font family, size: font size} + :param 3-tuple text_color: color for the text + """ + + # Validate kwargs + attr = [ + "bg_normal", "bg_hover", "bg_pressed", + "bd", "bd_color", + "text", "text_font", "text_color", + "pos", "size" + ] + for kwarg in kwargs: + if kwarg not in attr: + raise ValueError(f"{kwarg} is not a valid attribute") + + # If a parameter has changed + # Update rect + if "pos" in kwargs: + self.rect.x, self.rect.y = kwargs.pop("pos") + if "size" in kwargs: + self.rect.w, self.rect.h = kwargs.pop("size") + + self.__dict__.update(**kwargs) + # Update text_core + if "text_font" in kwargs: + self.text_core = pygame.font.Font(**self.text_font) + + # ========================================================================= + # = Events + # ========================================================================= + + def __on_clic_down(self): + pos = pygame.mouse.get_pos() + if self.rect.collidepoint(*pos): + self.state = State.pressed + self.draw() + + def __on_clic_up(self): + pos = pygame.mouse.get_pos() + if self.rect.collidepoint(*pos): + self.state = State.hover + self.signal.emit() + else: + self.state = State.normal + self.draw() + + def __on_hover(self): + pos = pygame.mouse.get_pos() + changed = False + # If on button + if self.rect.collidepoint(*pos): + if self.state == State.normal: + self.state = State.hover + changed = True + else: + if self.state == State.hover: + self.state = State.normal + changed = True + + if changed: + self.draw() + + # ========================================================================= + # = Public methods + # ========================================================================= + + def execute(self, *args, **kwargs): + """ + Emit the signals attached to this button if it's not disabled + """ + + if self.enabled: + self.signal.emit(*args, **kwargs) + + def enable(self): + """ + Enable the button. + """ + + self.enabled = True + self.draw() + + def disable(self): + """ + Disable the button. + """ + + self.enabled = False + self.draw() + + def collide(self, pos): + """ + Return True if the position is on the button + """ + + return self.rect.collidepoint(pos) + + def set(self, **kwargs): + """ + Set attributes to the button + + :param 3-tuple bg_normal: color for normal background + :param 3-tuple bg_hover: color for background when hover + :param 3-tuple bg_pressed: color for background when pressed + :param int bd: border size + :param 3-tuple bd_color: color for the border + :param str text: text to display on button + :param dict text_font: {file: font family, size: font size} + :param 3-tuple text_color: color for the text + """ + + self.__setKwargs(**kwargs) + + def handle_event(self, event): + """ + Handle the events used by the button + + :param pygame.event event: event generated by pygame + """ + + if not self.enabled: + return + + if event.type == pygame.MOUSEMOTION: + self.__on_hover() + elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1: + self.__on_clic_down() + elif event.type == pygame.MOUSEBUTTONUP and event.button == 1: + self.__on_clic_up() + + def draw(self): + """ + Draw the button on window + """ + + core_text = self.text_core.render(self.text, 2, self.text_color) + + x_b, y_b = self.rect.x, self.rect.y + w_b, h_b = self.rect.width, self.rect.height + w_t, h_t = core_text.get_size() + mid_x = x_b + (w_b - w_t) // 2 + mid_y = y_b + (h_b - h_t) // 2 + + self.bg = { + State.normal: self.bg_normal, + State.hover: self.bg_hover, + State.pressed: self.bg_pressed + }.get(self.state, None) + + if self.bg: + pygame.draw.rect(self.window, self.bg, self.rect) + + if self.bd > 0: + points = ( + (x_b, y_b), + (x_b, y_b + h_b), + (x_b + w_b, y_b + h_b), + (x_b + w_b, y_b) + ) + pygame.draw.lines(self.window, self.bd_color, True, points, self.bd) + + self.window.blit(core_text, (mid_x, mid_y)) + + if not self.enabled: + s = pygame.Surface((self.rect.w, self.rect.h), pygame.SRCALPHA) + s.fill((0, 0, 0, 128)) + self.window.blit(s, (self.rect.x, self.rect.y)) + + pygame.display.update(self.rect) diff --git a/src/button/tests/test_button.py b/src/button/tests/test_button.py new file mode 100644 index 0000000..9e76077 --- /dev/null +++ b/src/button/tests/test_button.py @@ -0,0 +1,25 @@ +from src.button import Button + +import pygame + + +pygame.init() + + +def testInitButton(): + try: + btn = Button(text="Test") + except: + assert False + else: + assert True + + +def testButtonPos(): + btn = Button(text="Test", pos=(10, 20)) + assert btn.rect.x == 10 and btn.rect.y == 20 + + +def testButtonSize(): + btn = Button(text="Test", size=(10, 20)) + assert btn.rect.w == 10 and btn.rect.h == 20 diff --git a/src/cards/__init__.py b/src/cards/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/cards/card.py b/src/cards/card.py new file mode 100644 index 0000000..c9bb5b9 --- /dev/null +++ b/src/cards/card.py @@ -0,0 +1,120 @@ +import re +from typing import Union, Pattern + +card_names_and_values = { + ("ACE", 1), + ("TWO", 2), + ("THREE", 3), + ("FOUR", 4), + ("FIVE", 5), + ("SIX", 6), + ("SEVEN", 7), + ("EIGHT", 8), + ("NINE", 9), + ("TEN", 10), + ("JACK", 11), + ("QUEEN", 12), + ("KING", 13), +} + +card_to_value_dict = { + key: min(10, value) for (key, value) in card_names_and_values +} +value_to_card_dict = {key: value for (value, key) in card_names_and_values} + +colors = {"HEARTS", "SPADES", "CLUBS", "DIAMONDS"} + + +class Card: + def __init__(self, value: Union[int, str], color: str = "hearts"): + self._value = None + self._color = None + self.name = None + + # Calls color.setter + self.color = color + + # Calls value.setter + self.value = value + try: + self.value = value + except KeyError: + raise ValueError( + "First argument 'value' should be a card name " + "or integer between 1 and 13" + ) + + @property + def color(self) -> str: + return self._color + + @color.setter + def color(self, color: str = "HEARTS"): + color = color.upper() + for c in colors: + regexp = self.cardColorToRegexp(c).match(color) + if regexp is None: + # regexp.match returns None if nothing is matched, + # which will raise a error if end method is used on the + # matching result + continue + if regexp.end() == len(color): + self._color = c + break + else: + raise ValueError( + 'Invalid value for Card object\'s "color" member.\n' + 'Value should be either "HEARTS", "DIAMONDS", "CLUBS", ' + '"SPADES", their singular variant, or their first letter.\n' + "Case is not relevant." + ) + + @property + def value(self) -> int: + return self._value + + @value.setter + def value(self, arg: Union[str, int]): + if isinstance(arg, str): + self.name = arg.upper() + elif isinstance(arg, int): + self.name = value_to_card_dict[arg] + self._value = card_to_value_dict[self.name] + + def __radd__(self, other: Union['Card', int]) -> int: + if self.name == "ACE": + if self._value + other <= 11: + return self._value + other + 10 + return self._value + other + + def __add__(self, other: Union['Card', int]) -> int: + if self.name == "ACE": + if self._value + other <= 11: + return self._value + other + 10 + return self._value + other + + def __int__(self) -> int: + return self._value + + def __repr__(self) -> str: + return "Card(value = %d, name = %s, color = %s)" % ( + self._value, + self.name, + self.color, + ) + + def __str__(self) -> str: + return "%s of %s" % (self.name, self.color) + + @staticmethod + def cardColorToRegexp(string: str) -> Pattern[str]: + """ + Creates a regular expression to match user inputs for color parameter + For example, replace "HEARTS" by "H(EART(S)?)?" + Allows matching "H", "HEART" and "HEARTS" + :param str string: String to be changed to regular expression + :return: a regular expression + :rtype: Pattern[str] + """ + string = string[0] + "(" + string[1:-1] + "(" + string[-1] + ")?)?" + return re.compile(string) diff --git a/src/cards/deck.py b/src/cards/deck.py new file mode 100644 index 0000000..ad8b36a --- /dev/null +++ b/src/cards/deck.py @@ -0,0 +1,56 @@ +import itertools +import random + +from src.cards.card import Card, card_to_value_dict, colors + + +class Deck: + def __init__(self, SHUFFLE: bool = True): + # boolean flag to tell the controller if the deck needs to be shuffled + # should be checked at the end of every turn by the controller + self.needs_shuffling = False + + self.cards = ( + list(itertools.product(card_to_value_dict.keys(), colors)) * 6 + ) + + if SHUFFLE: + self.shuffle() + + # index of the card on the top of the deck + self.top_card_index = 0 + + # index of the red card, when the dealer finds this card, he shuffles + # the deck. Usually placed around 3/4 of the deck + # self.needs_shuffling is set to True when this index is reached + self.red_card_index = self.computeRedCardIndex(len(self.cards)) + + def shuffle(self): + # shuffle deck + random.shuffle(self.cards) + # reset counter + self.top_card_index = 0 + # recalculate red card index, not really necessary but more realistic + self.red_card_index = self.computeRedCardIndex(len(self.cards)) + # reset shuffling flag to False + self.needs_shuffling = False + + def getCard(self) -> Card: + self.top_card_index += 1 + if self.top_card_index == self.red_card_index: + # The deck needs to be shuffled + self.needs_shuffling = True + + return Card(*self.cards[self.top_card_index]) + + @staticmethod + def computeRedCardIndex(deck_length: int) -> int: + """ + Utility function to choose a random index at 3/4th of the deck's + length += 30 + :param deck_length: + :return: red card index + """ + return random.randint( + (3 / 4) * deck_length - 30, (3 / 4) * deck_length + 30 + ) diff --git a/src/cards/exceptions.py b/src/cards/exceptions.py new file mode 100644 index 0000000..7ee0f38 --- /dev/null +++ b/src/cards/exceptions.py @@ -0,0 +1,2 @@ +class CardsAPIError(Exception): + pass diff --git a/src/cards/hand.py b/src/cards/hand.py new file mode 100644 index 0000000..ed85dd9 --- /dev/null +++ b/src/cards/hand.py @@ -0,0 +1,174 @@ +from typing import List, Tuple + +from src.cards.card import Card +from src.cards.exceptions import CardsAPIError + + +class Hand: + def __init__( + self, + card_list: List[Card] = None, + is_dealer_hand: bool = False, + isSplit: bool = False, + ): + self.card_list = card_list or [] + self.is_split = isSplit + self.is_dealer_hand = is_dealer_hand + + @property + def value(self) -> int: + # without this sort, aces are always counted as 11 + sorted_card_list = sorted( + self.card_list, key=lambda x: x.value, reverse=True + ) + return sum(sorted_card_list) + + @property + def is_black_jack(self) -> bool: + hand_sum = sum(self.card_list) + if hand_sum == 21 and len(self.card_list) == 2 and not self.is_split: + return True + else: + return False + + @property + def is_burnt(self) -> bool: + # without this sort, aces are always counted as 11 + sorted_card_list = sorted( + self.card_list, key=lambda x: x.value, reverse=True + ) + hand_sum = sum(sorted_card_list) + if hand_sum > 21: + return True + else: + return False + + def checkSplitIsPossible(self) -> bool: + """ + Check if the card are the same + :return: True is split can be done False otherwise + """ + if ( + len(self.card_list) == 2 + and self.card_list[0].value == self.card_list[1].value + and not self.is_dealer_hand + ): + return True + return False + + def split(self) -> Tuple['Hand', 'Hand']: + """ + Performs a split action. Returns two instances of Hand. + The methods checks for number of cards in the original Hand (which + should be 2) and for equality of the two cards' values + :return: The two resulting hands in a tuple + :raise: AssertionError + """ + if self.checkSplitIsPossible(): + return ( + Hand([self.card_list[0]], isSplit=True), + Hand([self.card_list[1]], isSplit=True), + ) + raise CardsAPIError(f"{self!r} cannot be split") + + """ + The following are comparison methods for comparing Hand objects. All + standard comparison operators are defined and take into account the fact + that a Hand can be a blackjack or not and that it can belong to the + dealer or not + """ + + def __gt__(self, other: 'Hand') -> bool: + if not isinstance(other, Hand): + return NotImplemented + if self.is_black_jack and not other.is_black_jack: + return True + elif other.is_burnt and not self.is_burnt: + return True + elif self.is_burnt and other.is_burnt and self.is_dealer_hand: + return True + elif self.value > other.value and not self.is_burnt: + return True + else: + return False + + def __lt__(self, other: 'Hand') -> bool: + if not isinstance(other, Hand): + return NotImplemented + return not self.__gt__(other) and not self.__eq__(other) + + def __eq__(self, other: 'Hand') -> bool: + if not isinstance(other, Hand): + return NotImplemented + if self.is_black_jack and other.is_black_jack: + return True + elif ( + self.is_burnt + and other.is_burnt + and not self.is_dealer_hand + and not other.is_dealer_hand + ): + return True + elif ( + self.value == other.value + and not self.is_black_jack + and not other.is_black_jack + ): + return True + else: + return False + + def __ge__(self, other: 'Hand') -> bool: + if not isinstance(other, Hand): + return NotImplemented + return not self.__lt__(other) + + def __le__(self, other: 'Hand') -> bool: + if not isinstance(other, Hand): + return NotImplemented + return not self.__gt__(other) + + def __ne__(self, other: 'Hand') -> bool: + if not isinstance(other, Hand): + return NotImplemented + return not self.__eq__(other) + + def __add__(self, card: Card) -> 'Hand': + """ + Creates a new hand from self with the added card using: + "hand = hand + card" + :param card: a Card object to append to the new Hand's card_list + :return: A new Hand with the + """ + if not isinstance(card, Card): + return NotImplemented + new_card_list = self.card_list + [card] + return Hand( + card_list=new_card_list, + is_dealer_hand=self.is_dealer_hand, + isSplit=self.is_split, + ) + + def __iadd__(self, card) -> 'Hand': + """ + Adds a card to the Hand, using "hand += card" + :param card: a Card object to append to the Hand's card_list + :return: The Hand itself + """ + if not isinstance(card, Card): + return NotImplemented + self.card_list += [card] + return self + + def __repr__(self) -> str: + return ( + f"Hand(card_list={self.card_list!r}, " + f"is_dealer_hand={self.is_dealer_hand!r})" + ) + + def __str__(self) -> str: + if self.is_dealer_hand: + owner = "Dealer" + else: + owner = "Player" + return f"{owner} Hand : {self.card_list}" diff --git a/src/cards/tests/test_cards.py b/src/cards/tests/test_cards.py new file mode 100644 index 0000000..1ac79ca --- /dev/null +++ b/src/cards/tests/test_cards.py @@ -0,0 +1,49 @@ +from src.cards.card import Card + +# To launch test in console : +# ... $ python -m pytest tests/ + + +def test_create_num_card(): + + card = Card(1) + assert card.value == 1 + assert card.color == 'HEARTS' + + card = Card('TWO') + assert card.value == 2 + + card = Card('Three', 'diamond') + assert card.value == 3 + assert card.color == 'DIAMONDS' + + +def test_create_face_card(): + + card = Card(12) + assert card.name == "QUEEN" + assert card.value == 10 + + card = Card("King") + assert card.name == "KING" + assert card.color == 'HEARTS' + + +def test_add_cards(): + + card_1 = Card(5, "Hearts") + card_2 = Card(7, "DIAMONDS") + assert card_1 + card_2 == 12 + + card_3 = Card("TWO", "spades") + card_4 = Card(13) + assert card_3 + card_4 == 12 + + +def test_add_ace(): + + card_1 = Card("KING", "hearts") + card_2 = Card(9) + card_3 = Card("ACE", "heaRts") + assert card_1 + card_2 + card_3 == 20 + # assert card_3 + card_2 + card_1 == 20 diff --git a/src/cards/tests/test_deck.py b/src/cards/tests/test_deck.py new file mode 100644 index 0000000..45a6449 --- /dev/null +++ b/src/cards/tests/test_deck.py @@ -0,0 +1,66 @@ +from src.cards.deck import Deck +from src.cards.card import Card + + +def test_init_deck(): + + deck = Deck() + assert deck.top_card_index == 0 + assert len(deck.cards) == 312 + # Check placement of the red Card + assert ((3 / 4) * 312) - 30 <= deck.red_card_index <= ((3 / 4) * 312) + 30 + + # Assert not shuffle + deck = Deck(False) + assert deck.top_card_index == 0 + assert len(deck.cards) == 312 + assert ((3 / 4) * 312) - 30 <= deck.red_card_index <= ((3 / 4) * 312) + 30 + + +def test_deal_deck(): + + deck = Deck() + card = deck.getCard() + assert type(card) == Card + assert deck.top_card_index == 1 + + +def test_shuffle_deck(): + + deck = Deck() + try: + for i in range(500): + card = deck.getCard() + except IndexError: + assert True + else: + # This shouldn't work because the Deck is only 312 cards long + assert False + + deck = Deck() + + for i in range(deck.red_card_index): + assert not deck.needs_shuffling + deck.getCard() + + assert deck.needs_shuffling + + deck.shuffle() + + assert not deck.needs_shuffling + + try: + # This won't work if the deck has not been shuffled + for i in range( + (len(deck.cards) - deck.red_card_index) + 1 + ): + deck.getCard() + except IndexError: + assert False + + +def test_init_shuffle_deck(): + + deck1 = Deck(False) + deck2 = Deck(False) + assert deck1.cards[0] == deck2.cards[0] diff --git a/src/cards/tests/test_hand.py b/src/cards/tests/test_hand.py new file mode 100644 index 0000000..299e172 --- /dev/null +++ b/src/cards/tests/test_hand.py @@ -0,0 +1,69 @@ +from src.cards.hand import Hand +from src.cards.card import Card + +# To launch test in console : +# ... $ python -m pytest tests/ +from src.cards.exceptions import CardsAPIError + + +def test_init_hand(): + + hand = Hand() + assert len(hand.card_list) == 0 + + hand = Hand([Card(2)]) + assert hand.value == 2 + + +def test_add_card(): + + hand = Hand() + card = Card(2) + hand = hand + card + card = Card(5) + hand = hand + card + assert len(hand.card_list) == 2 + assert hand.value == 7 + + +def test_iadd_card(): + + hand = Hand([Card(5)]) + hand_list = [hand] + hand += Card(2) + assert len(hand_list[0].card_list) == 2 + assert hand_list[0].value == 7 + + +def test_comparison_hand(): + + hand_1 = Hand([Card(5), + Card(7)]) + hand_2 = Hand([Card(3)]) + assert hand_1 > hand_2 + + +def test_split_hand(): + + hand = Hand([Card(3, 'heart'), + Card(3, 'spades')]) + [hand_1, hand_2] = hand.split() + assert hand_1.value == 3 and hand_2.value == 3 + assert hand_1 == hand_2 + + hand2 = Hand([Card(3), Card(4)]) + try: + hand2.split() + except CardsAPIError: + assert True + else: + assert False + + # testing too many cards in hand + hand += Card(3) + try: + hand.split() + except CardsAPIError: + assert True + else: + assert False diff --git a/src/common/__init__.py b/src/common/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/common/config.py b/src/common/config.py new file mode 100644 index 0000000..fd2155a --- /dev/null +++ b/src/common/config.py @@ -0,0 +1,54 @@ +import json +import os + + +class ConfigPath: + path = dict() + + @classmethod + def initialize(cls, path): + with open(path, encoding="utf-8") as f: + cls.path = json.load(f) + + @classmethod + def get(cls, *keys): + """ + Return the value after each key. + + ..Example: + ConfigPath.get("folder", "data") + + :return: value in the path config file + :rtype: any json storage type + """ + + config = cls.path + for key in keys: + config = config[key] + return os.path.abspath(os.path.join(*config)) + + @classmethod + def folder(cls, key): + """ + Return the path to the folder given by its name + + :param str key: folder name + :return: folder path + :rtype: str + """ + + return cls.get("folders", key) + + @classmethod + def file(cls, key): + """ + Return tge path to a file given by its name + + :param str key: file name in path.cfg.json + :return: file path + :rtype: str + """ + + folder, *path = cls.path["files"][key] + folder = cls.folder(folder) + return os.path.join(folder, *path) diff --git a/src/common/constants.py b/src/common/constants.py new file mode 100644 index 0000000..fb0dc95 --- /dev/null +++ b/src/common/constants.py @@ -0,0 +1,93 @@ +# -*- coding: utf-8 -*- + +# ============================================================================ +# = File containing all the constant variables +# ============================================================================ + +import os +import json +from enum import Enum + +from src.cards.hand import Hand +from src.common.config import ConfigPath + +# ============================================================================ +# = Configuration parameters +# ============================================================================ + +ConfigPath.initialize("data/config/path.cfg.json") +__tmp = "data/config/menu.cfg.json" +with open(__tmp, "r", encoding="utf-8") as f: + CONFIG_MENU = json.load(f) +__tmp = "data/config/game_view.cfg.json" +with open(__tmp, "r", encoding="utf-8") as f: + CONFIG_GAME_VIEW = json.load(f) + +# ============================================================================ +# = Directories path +# ============================================================================ + +DIR_SRC = ConfigPath.folder("src") # Source files +DIR_DATA = ConfigPath.folder("data") # Data files +DIR_CONFIG = ConfigPath.folder("config") # Configuration files +DIR_PICTURES = ConfigPath.folder("pictures") # Pictures + +# ============================================================================ +# = Enum +# ============================================================================ + + +class Game(Enum): + """ + Class with all the states of the game + """ + quit = 0 + menu = 1 + play = 2 + option = 3 + + +class Decision(Enum): + """ + Class with decisions regarding Hands + """ + stand = 0 + hit = 1 + double = 2 + split = 3 + + +class Moves(Enum): + """ + Class with moves possibilities + """ + up = -1 + down = 1 + + +class PlayerHand: + """ + Hand list index for player hand + """ + + def __init__(self, hand: Hand = None, + hand_bet: int = 0, is_lock: bool = False): + self.hand: Hand = hand or Hand() + self.hand_bet: int = hand_bet + self.is_lock: bool = is_lock + + def __repr__(self): + return (f"PlayerHand object(hand = {self.hand}, " + f"hand_bet = {self.hand_bet}, " + f"is_lock = {self.is_lock})") + + def __str__(self): + return (f"{['', 'Locked'][self.is_lock]} " + f"{self.hand} with bet: {self.hand_bet}") + +# ============================================================================ +# = Clear temporary variables +# ============================================================================ + + +del __tmp diff --git a/src/common/func_pictures.py b/src/common/func_pictures.py new file mode 100644 index 0000000..39e0dd2 --- /dev/null +++ b/src/common/func_pictures.py @@ -0,0 +1,47 @@ +import os + +import pygame + +from src.common.config import ConfigPath +from src.cards.card import card_to_value_dict + + +def load_card_image(name: str, color: str) -> pygame.Surface: + """ + From a Card object, compute its path and loads the corresponding image + :param str name: value of the card to be loaded + :param color: value of the card to be loaded + :return pygame.Surface: pygame surface + """ + return load_image(convert_card_to_picture_path(name, color)) + + +def load_image(path: str) -> pygame.Surface: + """ + Loads an image + :param path: path of the object to be loaded + :return pygame.Surface: + """ + + filename = os.path.join(ConfigPath.folder("pictures"), path) + try: + surface = pygame.image.load(filename) + except pygame.error: + e = OSError( + f"Could not load image \"{filename}\" {pygame.get_error()}" + ) + raise e + return surface.convert_alpha() + + +def convert_card_to_picture_path(name: str, color: str) -> str: + """ + Return the picture name of a Card object + """ + if name.upper() not in ("ACE", "JACK", "QUEEN", "KING"): + name = str(card_to_value_dict[name]) + + color = color.lower() + + card_picture_name = "%s_of_%s.png" % (name, color) + return os.path.join('cards', card_picture_name) diff --git a/src/common/game_view_config.py b/src/common/game_view_config.py new file mode 100644 index 0000000..14eac6d --- /dev/null +++ b/src/common/game_view_config.py @@ -0,0 +1,108 @@ +import json + +from dataclasses import dataclass, field +from typing import Optional, List, Tuple +from marshmallow import fields, Schema, post_load + +from src.common.constants import CONFIG_GAME_VIEW + + +@dataclass +class Dimensions: + width: Optional[int] = field(default=None) + height: Optional[int] = field(default=None) + + +class DimensionsSchema(Schema): + width = fields.Integer(default=None) + height = fields.Integer(default=None) + + @post_load + def make(self, data): + return Dimensions(**data) + + +@dataclass +class Coordinates: + x: Optional[int] = field(default=None) + y: Optional[int] = field(default=None) + + @property + def as_tuple(self): + return self.x, self.y + + +class CoordinatesSchema(Schema): + x = fields.Integer() + y = fields.Integer() + + @post_load + def make(self, data): + return Coordinates(**data) + + +@dataclass +class AreaDefinition(Coordinates, Dimensions): + color: Optional[List[int]] = field(default=None) + pass + + +class AreaDefinitionSchema(CoordinatesSchema, DimensionsSchema): + color = fields.List(fields.Integer()) + @post_load() + def make(self, data): + return AreaDefinition(**data) + + +@dataclass +class CardArea: + dealer: AreaDefinition + player: AreaDefinition + extra_card_offset: Coordinates + + +class CardAreaSchema(Schema): + dealer = fields.Nested(AreaDefinitionSchema()) + player = fields.Nested(AreaDefinitionSchema()) + extra_card_offset = fields.Nested(CoordinatesSchema()) + + @post_load + def make(self, data): + return CardArea(**data) + + +@dataclass +class GameView: + card_areas: CardArea + window: AreaDefinitionSchema + cards: Dimensions + tokens: Dimensions + game_menu_area: AreaDefinitionSchema + + +class GameViewSchema(Schema): + card_areas = fields.Nested(CardAreaSchema()) + window = fields.Nested(AreaDefinitionSchema()) + cards = fields.Nested(DimensionsSchema()) + tokens = fields.Nested(DimensionsSchema()) + game_menu_area = fields.Nested(AreaDefinitionSchema()) + + def load(self, config: dict, **kwargs) -> Tuple[GameView, dict]: + """ + The only reason we override this function is to add the type hints + so that auto-completion on editors works fine + :param config: + :return: + """ + return super().load(config, **kwargs) + + @post_load + def make(self, data) -> GameView: + return GameView(**data) + + +game_view_schema = GameViewSchema() +game_view_config, _ = game_view_schema.loads( + json.dumps(CONFIG_GAME_VIEW) +) +# TODO: Add tests for loading diff --git a/src/common/tests/test_config.py b/src/common/tests/test_config.py new file mode 100644 index 0000000..7ed3230 --- /dev/null +++ b/src/common/tests/test_config.py @@ -0,0 +1,13 @@ +import os +import json +from src.common.config import ConfigPath + +def test_config_path(): + file_config_path = os.path.join("data", "config", "path.cfg.json") + + ConfigPath.initialize(file_config_path) + with open(file_config_path) as f: + paths = json.load(f) + + assert ConfigPath.get("folders", "data") == os.path.abspath(os.path.join(*paths["folders"]["data"])) + assert ConfigPath.folder("data") == os.path.abspath(os.path.join(*paths["folders"]["data"])) diff --git a/src/common/utils.py b/src/common/utils.py new file mode 100644 index 0000000..2c1cd71 --- /dev/null +++ b/src/common/utils.py @@ -0,0 +1,27 @@ +from src.common.game_view_config import Coordinates +import pygame + + +class Signal: + def __init__(self): + self.__subscribers = [] + + def emit(self, *args, **kwargs): + for subscriber in self.__subscribers: + subscriber(*args, **kwargs) + + def attach(self, subscriber): + self.__subscribers.append(subscriber) + + def detach(self, subscriber): + try: + self.__subscribers.remove(subscriber) + except ValueError: + print('Warning: function %s not removed ' + 'from signal %s' % (subscriber, self)) + + +class SurfaceWithPosition: + def __init__(self, surface: pygame.Surface, position: Coordinates): + self.surface = surface + self.position = position diff --git a/src/controller/game_controller.py b/src/controller/game_controller.py new file mode 100644 index 0000000..9e53e6f --- /dev/null +++ b/src/controller/game_controller.py @@ -0,0 +1,318 @@ +from src.views.view_game import ViewGame +from src.humans.dealer import Dealer +from src.humans.player import Player +from src.cards.deck import Deck +from src.common.constants import Decision + +import pygame +from pygame.locals import ( + QUIT, + KEYDOWN, + K_ESCAPE, + K_1, + K_2, + K_3, + K_4, + K_5, + K_6, + K_KP1, + K_KP2, + K_KP3, + K_KP4, + K_KP5, + K_KP6, +) + + +class GameController: + """ + A controller for all the game + """ + def __init__(self, window): + print("Enter in controller") + self.window = window + self.humans_list = [] + self.dealer = Dealer() + self.view_game = None + self.player_wallet = 500 + self.deck = Deck() + # Game loop variables + self.playing = False + self.quit = False + self.human = None + self.hand_idx = None + # self.view_game = View_game(window, view_config) + + def game_launch(self): + self.view_game = ViewGame(self.window) + self.view_game.buttons["card"].signal.attach(self.btn_card) + self.view_game.buttons["bet"].signal.attach(self.btn_bet) + self.view_game.buttons["end_turn"].signal.attach(self.btn_end_turn) + self.view_game.buttons["split"].signal.attach(self.btn_split) + self.view_game.buttons["double"].signal.attach(self.btn_double) + self.view_game.buttons["quit"].signal.attach(self.btn_quit) + + def initiate_players(self): + """ + ask the player(s) how many they are and their name(s) + + :return: bool initialisation is done and OK + """ + # ask the view to open a new window and ask the number of player + number_of_player = 1 + + for _ in range(number_of_player): + # ask the name of the player and create the Player + name_of_player = "Jesus" + self.add_human(Player(name_of_player, self.player_wallet)) + + def refresh(self): + self.view_game.refresh() + + def enable_buttons(self, *btn_names): + """ + Enable the given buttons + """ + + for btn in btn_names: + self.view_game.buttons[btn].enable() + + def disable_buttons(self, *btn_names): + """ + Disable the given buttons + """ + + for btn in btn_names: + self.view_game.buttons[btn].disable() + + def add_human(self, human) -> bool: + """ + Adding one player into the list of humans to handle at each round + + :param human: Player to add + :type arg1: Player + """ + if isinstance(human, Player): + self.humans_list.append(human) + return True + else: + # Given human isn't a player + return False + + def remove_player(self, player_uuid) -> bool: + """ + Removing one player + + :param player_uuid: Player's id to remove + :type arg1: Player + """ + if len(self.humans_list) > 2: + for i in range(len(self.humans_list[:-1])): + if self.humans_list[i].uuid == player_uuid: + self.humans_list = self.humans_list[:i] + self.humans_list[i+1:] + return True + else: + # No player to remove, player list is empty + return False + # Id not found + return False + + def reset_all_humans(self): + """Resetting all humans : no more player and new dealer""" + self.humans_list = [] + self.dealer = Dealer() + + def first_round(self): + """ + First round allow the players to bet them deal the card for everybody + :return: bool : state of the round + """ + + for human in self.humans_list: + human.clear_hands() + self.dealer.clear_hand() + + # Set buttons state + self.enable_buttons("bet", "quit") + self.disable_buttons("card", "end_turn", "split", "double") + + # loop only for betting. Betting buttons should be the only one modifiable + for self.human in self.humans_list: + print(self.human.name + " is betting.") + self.quit = False + self.playing = True + while self.playing: + event = pygame.event.wait() + if event.type == QUIT: + return False + elif event.type == KEYDOWN and event.key == K_ESCAPE: + return False + elif event.type == KEYDOWN : + if event.key in [K_2, K_KP2]: + self.view_game.buttons["bet"].execute() + elif event.key in [K_3, K_KP3]: + self.view_game.buttons["end_turn"].execute() + elif event.key in [K_6, K_KP6]: + self.view_game.buttons["quit"].execute() + + for btn in self.view_game.buttons.values(): + btn.handle_event(event) + + if self.quit: + return False + + # loop to deal hands to everybody + for self.human in self.humans_list: + print(self.human.name + "is receiving cards.") + # at initialization we only change the first hand of the player with 2 cards + self.human.add_card(self.deck.getCard(), 0) + self.human.add_card(self.deck.getCard(), 0) + + # giving the dealer a hand (with 2 card) + self.dealer.add_card(self.deck.getCard()) + self.dealer.add_card(self.deck.getCard()) + print("End bet_round") + return True + + def play_one_round(self): + + # Set buttons state + self.enable_buttons("card", "end_turn", "quit") + self.disable_buttons("bet", "split", "double") + + for self.human in self.humans_list: + print(str(self.human) + " round") + for self.hand_idx in range(len(self.human.hands)): + print("Hand %i" % self.hand_idx) + print(self.human.name + " is playing.") + # Get list of possible actions + # Manage interfaces + # Let human choose + self.quit = False + self.playing = True + while self.playing: + event = pygame.event.wait() + if event.type == QUIT: + return False + elif event.type == KEYDOWN: + if event.key == K_ESCAPE: + return False + elif event.key in [K_1, K_KP1]: + self.view_game.buttons["card"].execute() + elif event.key in [K_2, K_KP2]: + self.view_game.buttons["bet"].execute() + elif event.key in [K_3, K_KP3]: + self.view_game.buttons["end_turn"].execute() + elif event.key in [K_4, K_KP4]: + self.view_game.buttons["split"].execute() + elif event.key in [K_5, K_KP5]: + self.view_game.buttons["double"].execute() + elif event.key in [K_6, K_KP6]: + self.view_game.buttons["quit"].execute() + + for btn in self.view_game.buttons.values(): + btn.handle_event(event) + + if self.quit: + return False + + dealer_decision = self.dealer.choose_action() + print("Dealer hand : " + str(self.dealer.hand)) + + while dealer_decision != Decision.stand: + print(dealer_decision) + if dealer_decision == Decision.hit: + self.dealer.add_card(self.deck.getCard()) + print("Dealer hand : " + str(self.dealer.hand)) + dealer_decision = self.dealer.choose_action() + + print("Dealer decision : " + str(dealer_decision)) + + # Win of loose ? + if self.dealer.hand.is_burnt: + print("Everyone win !") + else: + for human in self.humans_list: + for hand in human.hands: + if hand.hand.is_burnt: + print("Player %s loose with hand %s." % (human, str(hand))) + elif hand.hand > self.dealer.hand: + print("Player %s win with hand %s." % (human, str(hand))) + elif hand.hand == self.dealer.hand: + print("Player %s with hand %s is even with the dealer." % (human, str(hand))) + + return True + + # ========================================================================= + # = Buttons + # ========================================================================= + + def btn_card(self): + """ + Manage actions on card button + """ + + card = self.deck.getCard() + self.human.add_card(card, self.hand_idx) + print("You : " + str(self.human.hands[self.hand_idx].hand)) + if self.human.hands[self.hand_idx].hand.is_burnt or self.human.hands[self.hand_idx].hand.is_black_jack: + print("Is burnt or black jack") + self.playing = False + + print("btn_card") + + def btn_bet(self): + """ + Manage actions on bet button + """ + + bet_amount = 5 + hand_id = 0 + if len(self.human.hands) >= 2: + print("You have %i hands" % len(self.human.hands)) + hand_id = input("Hand number for bet : ") + self.human.bet(int(bet_amount), int(hand_id)) + print(f"Hand amount {self.human.hands[hand_id].hand_bet} in the {hand_id}") + self.enable_buttons("end_turn") + + print("btn_bet") + + def btn_end_turn(self): + """ + Manage actions on end turn button + """ + + self.playing = False + + print("btn_end_turn") + + def btn_split(self): + """ + Manage actions on split button + """ + + hand_id = 0 + if len(self.human.hands) >= 2: + print("You have %i hands" % len(self.human.hands)) + hand_id = input("Hand number for bet : ") + self.human.split(hand_id) + + print("btn_split") + + def btn_double(self): + """ + Manage actions on double button + """ + + self.human.double(0) + + print("btn_double") + + def btn_quit(self): + """ + Manage quit on quit button + """ + + self.quit = True + + print("btn_quit") diff --git a/src/helloWorld.py b/src/helloWorld.py deleted file mode 100644 index 1eaa088..0000000 --- a/src/helloWorld.py +++ /dev/null @@ -1 +0,0 @@ -print("Hello World !") \ No newline at end of file diff --git a/src/humans/dealer.py b/src/humans/dealer.py new file mode 100644 index 0000000..1f3f712 --- /dev/null +++ b/src/humans/dealer.py @@ -0,0 +1,44 @@ +from src.cards.hand import Hand +from src.common.constants import Decision + + +class Dealer: + def __init__(self): + self.hand = Hand() + self.name = "Hackiflette God" + + def choose_action(self, mode=0) -> Decision: + """ + Function to choose action, Hit or Stand, depending on the dealer's + hand value. Usually 2 rules can be chosen regarding the dealer's + decision making: + - mode 0: dealer stands on all 17s and above (and hits below) + - mode 1: dealer hits on soft 17 and below (and stands on hard 17 and + above) + :return: decision + """ + if mode == 0: + if self.hand.value < 17: # Dealer stands on all 17s + return Decision.hit + + elif mode == 1: + if self.hand.value < 17: # Dealer hits on soft 17 + return Decision.hit + elif self.hand.value == 17: + card_list = self.hand.card_list + raw_sum = sum((card.value for card in card_list)) + if raw_sum != 17: + # if the raw sum (calculated without taking into account + # that an ace can count as 11) is not 17 (then it would + # be 7), we have a soft 17, thus we hit + return Decision.hit + else: + raise ValueError("'mode' parameter of class Dealer's " + "'chooseAction' method should be 0 or 1") + return Decision.stand + + def add_card(self, card_to_add): + self.hand += card_to_add + + def clear_hand(self): + self.hand = Hand() diff --git a/src/humans/player.py b/src/humans/player.py new file mode 100644 index 0000000..e9aab83 --- /dev/null +++ b/src/humans/player.py @@ -0,0 +1,130 @@ +from src.cards.exceptions import CardsAPIError +import uuid +from typing import List +from src.common.constants import PlayerHand + + +class Player: + def __init__(self, name, wallet, uid=None): + self.uuid: uuid.UUID = self.create_uuid(uid) + # hands are list of Hand, money bet and if the hand is lock + self.hands: List[PlayerHand] = [PlayerHand()] + self.wallet: int = wallet + self.name = name + + @staticmethod + def create_uuid(uid): + if uid is None: + return uuid.uuid4() + else: + return uid + + def bet(self, amount, index_of_the_hand) -> bool: + """ + Check wallet value and substract the amount or take all the wallet + :return: boolean value : + - True : amount betted can be bet + - False : amount is too high bet only what left in the wallet + """ + + if amount <= self.wallet : + # subtract amount from wallet and add it the the pot + self.wallet -= amount + # increasing the amount of money bet for this hand + self.hands[index_of_the_hand].hand_bet += amount + return True + else: + # amount is higher than wallet put wallet at zero and put it into + # the money bet on hand + self.hands[index_of_the_hand].hand_bet += self.wallet + self.wallet = 0 + + return False + + def check_split_is_possible(self, index_of_hand_to_split) -> bool: + """ + Check if a split is possible according to the money bet on the hand and + the value of the wallet. + :return: boolean + - True : split can be done + - False: split can't be done + """ + if ( + self.check_double_bet_is_possible(index_of_hand_to_split) + and self.hands[index_of_hand_to_split].hand.checkSplitIsPossible() + ): + return True + + return False + + def check_double_bet_is_possible(self, index_of_the_bet_to_double) -> bool: + """ + Check if player can bet again what he has already bet on his hands + :return: True if double is possible False if not + """ + if self.hands[index_of_the_bet_to_double].hand_bet <= self.wallet: + return True + + return False + + def double(self, index_of_the_hand_to_double): + """ + Double the money spend by the player + """ + if self.check_double_bet_is_possible(index_of_the_hand_to_double): + # ---- Double the bet ---- + # 3 - lock the hand + self.hands[index_of_the_hand_to_double].is_lock = True + + # 1 - removing the bet in the wallet + self.wallet -= self.hands[index_of_the_hand_to_double].hand_bet + + # 2 - adding the new bet value + self.hands[index_of_the_hand_to_double].hand_bet *= 2 + else: + print("[double] double bet on Player", self.uuid, "is impossible") + + def split(self, index_of_hand_to_split): + """ + Check if the hand can be split if so it split it + """ + + if self.check_split_is_possible(index_of_hand_to_split): + # if check is ok cards are good and wallet have enough money + splitted_hand = self.hands[index_of_hand_to_split].hand.split() + bet_of_the_hand = self.hands[index_of_hand_to_split].hand_bet + + # remove bet of the second hand just created + self.wallet -= bet_of_the_hand + + if len(splitted_hand) == 2: + # ---- Creating the new hands --- + # 1 - reinitialize hands of the player + self.clear_hands() + self.hands.pop() + + # 2 - adding first hand with the associated bet + self.hands.append(PlayerHand(splitted_hand[0], + bet_of_the_hand, False)) + + # 3 - adding second hand with it associated bet + self.hands.append(PlayerHand(splitted_hand[1], + bet_of_the_hand, False)) + else: + raise CardsAPIError( + f"Split does not return exactly two hands for " + f"Player: {self!r}" + ) + + def add_card(self, card_to_add, index_of_the_hand_to_change): + self.hands[index_of_the_hand_to_change].hand += card_to_add + + def clear_hands(self): + self.hands = [PlayerHand()] + + def __repr__(self): + return f"Player(name = {self.name}, uuid = {self.uuid},\n" \ + f"hands = {self.hands})" + + def __str__(self) -> str: + return f"Player: {self.name}" diff --git a/src/humans/tests/test_player.py b/src/humans/tests/test_player.py new file mode 100644 index 0000000..29c3472 --- /dev/null +++ b/src/humans/tests/test_player.py @@ -0,0 +1,79 @@ +from src.humans.player import Player +from src.humans.dealer import Dealer +from src.cards import card +from src.common.constants import Decision + + +def testInitPlayer(): + player = Player("TestPlayer1", 1000) + assert player.name == "TestPlayer1" + assert player.wallet == 1000 + + +def testPlayerBet(): + player = Player("TestPlayer1", 1000) + player.add_card(card.Card(1), 0) + player.bet(500, 0) + assert player.wallet == 500 + + player.bet(1000, 0) + assert player.wallet == 0 + + +def testSplit(): + ace_heart_card = card.Card("ace", "heart") + ace_spade_card = card.Card("ace", "spades") + + assert ace_heart_card.value == 1 + assert ace_heart_card.color.lower() == "hearts" + + assert ace_spade_card.value == 1 + assert ace_spade_card.color.lower() == "spades" + + player = Player("TestPlayer1", 1000) + player.add_card(ace_heart_card, 0) + player.add_card(ace_spade_card, 0) + + player.bet(250, 0) + + split_possible = player.check_split_is_possible(0) + assert split_possible + + player.split(0) + assert len(player.hands) == 2 + assert player.wallet == 500 + +def testDealerDecision(): + dealer = Dealer() + + ace_heart_card = card.Card("ace", "heart") + ten_heart_card = card.Card(10, "heart") + + dealer.add_card(ace_heart_card) + dealer.add_card(ten_heart_card) + + # dealer hand is at 21 should stand, ace should be 11 + assert dealer.choose_action() == Decision.stand + + dealer.clear_hand() + + six_heart_card = card.Card(6, "heart") + + dealer.add_card(ace_heart_card) + dealer.add_card(six_heart_card) + + # dealer hand is at 17 in mode 0 should stand, ace should be 1 + assert dealer.choose_action() == Decision.stand + # dealer hand is at 17 in mode 1 should hit, ace should be 1 + assert dealer.choose_action(1) == Decision.hit + + dealer.clear_hand() + + four_heart_card = card.Card(4, "heart") + three_heart_card = card.Card(3, "heart") + + dealer.add_card(four_heart_card) + dealer.add_card(three_heart_card) + + # dealer hand is at 7 should hit + assert dealer.choose_action() == Decision.hit diff --git a/src/view_menu.py b/src/view_menu.py deleted file mode 100644 index d258b1d..0000000 --- a/src/view_menu.py +++ /dev/null @@ -1,71 +0,0 @@ -import os.path - -import pygame -from pygame.locals import QUIT - - -DIR_SRC = os.path.dirname(__file__) -DIR_PICTURES = os.path.join(os.path.dirname(DIR_SRC), "pictures") -DIR_MENU_PICTURES = os.path.join(DIR_PICTURES, "menu") - -def load_image(file): - """ Loads an image, prepares it for play """ - - file = os.path.join(DIR_MENU_PICTURES, file) - try: - surface = pygame.image.load(file) - except pygame.error: - error = "Could not load image \"%s\" %s"%(file, pygame.get_error()) - raise SystemExit(error) - return surface.convert() - - -def main(): - """ The main function of the view of menu""" - - # Init pygame - pygame.init() - screen = pygame.display.set_mode((500, 310)) - pygame.display.set_caption("Black Jack by Hackiflette") - - # Load background image - bgd_tile = load_image("background_menu.png") - background = pygame.Surface((500, 310)) - background.blit(bgd_tile, (0, 0)) - - # Prepare text - title_font = pygame.font.Font(None, 36) - text = title_font.render("Black Jack Project", 2, (255, 255, 255)) - - # Display on windows - screen.blit(background, (0, 0)) - screen.blit(text, (80, 30)) - pygame.display.flip() - - # Init sprites - all_sprites = pygame.sprite.RenderUpdates() - clock = pygame.time.Clock() - - play = True - while play: - - # Clear all the sprites - all_sprites.clear(screen, bgd_tile) - all_sprites.update() - - # Check for events - for event in pygame.event.get(): - if event.type == QUIT: - play = False - - # Update the scene - dirty = all_sprites.draw(screen) - pygame.display.update(dirty) - - clock.tick(40) - - pygame.quit() - - -if __name__ == '__main__': - main() diff --git a/src/views/__init__.py b/src/views/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/views/card_area_organizer.py b/src/views/card_area_organizer.py new file mode 100644 index 0000000..2db884b --- /dev/null +++ b/src/views/card_area_organizer.py @@ -0,0 +1,189 @@ +from typing import List + +import pygame + +from src.cards.card import Card +from src.common.game_view_config import game_view_config, Coordinates +from src.common.utils import Signal, SurfaceWithPosition +from src.views.image_loaders.cardsloader import CardsLoader + + +class CardAreaOrganizer: + """ + Organizer class used to handle card placement for the view. + Comes with a signal to tell the view we updated the cards to show. + The add_card method is used to add a card to the organizer, + which triggers the signal that tells the ViewGame class to refresh its + view. + """ + + dealer_card_area_config = game_view_config.card_areas.dealer + player_card_area_config = game_view_config.card_areas.player + extra_card_offset = game_view_config.card_areas.extra_card_offset + + window_width = game_view_config.window.width + window_height = game_view_config.window.height + + def __init__(self): + self.areas_updated = Signal() + self.dealer_area: List[SurfaceWithPosition] = [] + self.player_areas: List[List[SurfaceWithPosition]] = [] + + def add_card(self, card: Card, human_type: str, area_id: int = None): + """ + Generic method to add a Card to the organizer. Delegates to + specialized methods depending on the parameters. Emits a signal to + tell the ViewGame class to update the view + :param Card card: the card we want to add to the organizer + :param str human_type: either "dealer" or "player" + :param int area_id: only for "player" human_type, specifies the id + of the area to add the card to + :return: None + """ + card_tile = self._create_card_tile(card) + if human_type == "dealer": + self._add_dealer_card(card_tile) + elif human_type == "player": + if area_id is None: + raise ValueError("Missing area_id for adding a player card") + elif area_id > len(self.player_areas): + raise ValueError( + f"Wrong area_id ({area_id}) for adding a player card: " + f"only {len(self.player_areas)} are currently declared") + elif area_id == len(self.player_areas): + self._add_new_player_area(card_tile, area_id) + else: + self._add_player_card(card_tile, area_id) + else: + raise ValueError( + f"Unknown human type {human_type!r}, should be either " + f'"dealer" or "player"' + ) + self.areas_updated.emit() + + def split_hand(self, area_id): + """ + Splits the hand designated by the area_id. + The new created hand will be located on the right of the older one + :param int area_id: the id of the area we want to split + :return: None + """ + if area_id >= len(self.player_areas): + raise ValueError( + f"Wrong area_id {area_id} for splitting a player hand," + f"only {len(self.player_areas)} are currently declared" + ) + if len(self.player_areas[area_id]) != 2: + raise ValueError( + f"Cannot split hand with {len(self.player_areas[area_id])} " + f"cards" + ) + + areas_dict_ = { + area: cards for area, cards in enumerate(self.player_areas) + } + self.player_areas = [[] for _ in range(len(self.player_areas) + 1)] + + areas_dict = {} + + for area, cards in areas_dict_.items(): + if area < area_id: + areas_dict[area] = cards + elif area == area_id: + areas_dict[area] = [cards[0]] + areas_dict[area + 1] = [cards[1]] + else: + areas_dict[area + 1] = cards + + for area, cards in areas_dict.items(): + for card in cards: + self._add_player_card(card, area) + + self.areas_updated.emit() + + def clear_areas(self): + self.player_areas = [] + self.dealer_area = [] + self.areas_updated.emit() + + def _add_dealer_card(self, card_tile): + """ + Adds the card to self.dealer_area + :param pygame.Surface card_tile: the image representing the card + :return: None + """ + x_offset = self.extra_card_offset.x * len(self.dealer_area) + y_offset = self.extra_card_offset.y * len(self.dealer_area) + + x_pos = self.dealer_card_area_config.x + x_offset + y_pos = self.dealer_card_area_config.y + y_offset + + position = Coordinates(x=x_pos, y=y_pos) + + self.dealer_area.append(SurfaceWithPosition(card_tile, position)) + + def _add_player_card(self, card_tile: pygame.Surface, area_id: int): + """ + Adds the card to self.player_areas + :param pygame.Surface card_tile: the image representing the card + :param int area_id: id of the area to which we want to add the card + :return: None + """ + position = self._compute_player_area_position(area_id) + self.player_areas[area_id].append( + SurfaceWithPosition(card_tile, position) + ) + + def _add_new_player_area(self, card_tile, area_id): + """ + Called when adding a new card to a new player area. Since we add an + area, we will need to re-compute position for all the already placed + cards + :param pygame.Surface card_tile: the image representing the new card + :param int area_id: id of the new area to which we want to add the + card to + :return: None + """ + areas_dict = { + area: cards for area, cards in enumerate(self.player_areas) + } + self.player_areas = [[] for _ in range(len(self.player_areas) + 1)] + + for area, cards in areas_dict.items(): + for card in cards: + self._add_player_card(card, area) + + self._add_player_card(card_tile, area_id) + + def _compute_player_area_position(self, area_id: int) -> Coordinates: + """ + Utility function, side-effect-free, used to compute the coordinates + of the card to show, accounting for area id and the offset due to + already present cards + :param int area_id: id of the area to which we want to add the card + :return Coordinates: Coordinates object containing x and y + coordinates used to show the card tile onto the window + """ + x_offset = self.extra_card_offset.x * len(self.player_areas[area_id]) + y_offset = self.extra_card_offset.y * len(self.player_areas[area_id]) + + num_areas = len(self.player_areas) + player_area_width = self.player_card_area_config.width + + x_pos = round( + self.player_card_area_config.x + + (player_area_width / (1 + num_areas)) * (area_id + 1) + ) + x_offset + y_pos = self.player_card_area_config.y + y_offset + + return Coordinates(x_pos, y_pos) + + @classmethod + def _create_card_tile(cls, card: Card) -> pygame.Surface: + """ + Utility side-effect-free staticmethod. Loads the image corresponding + to the card and scale it + :param Card card: the card we want to load the image for + :return pygame.Surface: The image of the card, loaded and scaled + """ + return CardsLoader.get_image(card.name, card.color) diff --git a/src/views/image_loaders/__init__.py b/src/views/image_loaders/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/views/image_loaders/cardsloader.py b/src/views/image_loaders/cardsloader.py new file mode 100644 index 0000000..5a824c6 --- /dev/null +++ b/src/views/image_loaders/cardsloader.py @@ -0,0 +1,41 @@ +import itertools +from typing import Dict, Tuple + +import pygame + +from src.cards.card import card_to_value_dict, colors +from src.common.func_pictures import load_card_image +from src.common.game_view_config import game_view_config + + +class CardsLoader: + data: Dict[Tuple[str, str], pygame.Surface] = dict() + card_width = game_view_config.cards.width + card_height = game_view_config.cards.height + + @classmethod + def initialize(cls): + card_names = card_to_value_dict.keys() + color_list = colors + + cards_tuples = itertools.product(card_names, color_list) + + # Convert key values as integer + # And load images + for card in cards_tuples: + cls.data[card] = pygame.transform.scale( + load_card_image(*card), + (cls.card_width, cls.card_height) + ) + + @classmethod + def get_image(cls, name: str, color: str) -> pygame.Surface: + """ + Return the image corresponding to the value + + :param str name: card name + :param str color: card color + :return pygame.Surface: pygame surface object + """ + + return cls.data[(name, color)] diff --git a/src/views/image_loaders/tokensloader.py b/src/views/image_loaders/tokensloader.py new file mode 100644 index 0000000..163cce3 --- /dev/null +++ b/src/views/image_loaders/tokensloader.py @@ -0,0 +1,58 @@ +import json +import os + +from src.common.func_pictures import load_image +from src.common.config import ConfigPath + + +class TokensLoader: + data = dict() + + @classmethod + def initialize(cls, file): + with open(file) as f: + cls.data = json.load(f) + + # Convert key values as integer + # And load images + for k in list(cls.data.keys()): + filename = cls.data.pop(k) + path = os.path.join(ConfigPath.folder("tokens"), filename) + cls.data[int(k)] = load_image(path) + + @classmethod + def get_image(cls, value): + """ + Return the image corresponding to the value + + :param value: token value + :type value: int + :return: pygame + :rtype: pygame.Surface + """ + + return cls.data[value] + + @classmethod + def decompose_value_to_tokens(cls, value): + """ + Return a dictionary with the token values and their quantity. + The sum of the tokens being equal to the value. + + :param value: researched value + :type value: int + :return: dictionnary {value: quantity} + :rtype: dict + """ + + values = sorted(cls.data.keys(), reverse=True) + + dict_tokens = dict() + + for v in values: + # If enough + if value >= v: + n, value = divmod(value, v) + dict_tokens[v] = n + + return dict_tokens diff --git a/src/views/tests/test_card_area_organizer.py b/src/views/tests/test_card_area_organizer.py new file mode 100644 index 0000000..8dfd1cc --- /dev/null +++ b/src/views/tests/test_card_area_organizer.py @@ -0,0 +1,193 @@ +from src.cards.card import Card +from src.common.game_view_config import game_view_config +from src.views.card_area_organizer import CardAreaOrganizer + +# override method so we don't have to initialize a pygame window +CardAreaOrganizer._create_card_tile = lambda _, __: None + + +class SignalTriggerCounter: + signal_trigger_count = 0 + + def signal_triggered(self): + self.signal_trigger_count += 1 + + +def test_dealer_cards(): + card_1 = Card(1) + card_2 = Card(2) + dealer_card_area_config = game_view_config.card_areas.dealer + extra_card_offset = game_view_config.card_areas.extra_card_offset + + signal_triggered = SignalTriggerCounter() + + organizer = CardAreaOrganizer() + organizer.areas_updated.attach(signal_triggered.signal_triggered) + + assert not organizer.dealer_area + + organizer.add_card(card_1, "dealer") + + assert signal_triggered.signal_trigger_count == 1 + assert len(organizer.dealer_area) == 1 + assert organizer.dealer_area[0].position.as_tuple == ( + dealer_card_area_config.x, + dealer_card_area_config.y, + ) + + organizer.add_card(card_2, "dealer") + + # Check signal trigger + assert signal_triggered.signal_trigger_count == 2 + + assert len(organizer.dealer_area) == 2 + + # Check if adding new card didn't change first card position + assert organizer.dealer_area[0].position.as_tuple == ( + dealer_card_area_config.x, + dealer_card_area_config.y, + ) + + # Checking new card position, with offset + assert organizer.dealer_area[1].position.as_tuple == ( + dealer_card_area_config.x + extra_card_offset.x, + dealer_card_area_config.y + extra_card_offset.y, + ) + + +def test_player_cards_single_hand(): + card_1 = Card(1) + card_2 = Card(2) + player_card_area_config = game_view_config.card_areas.player + extra_card_offset = game_view_config.card_areas.extra_card_offset + + signal_triggered = SignalTriggerCounter() + + organizer = CardAreaOrganizer() + organizer.areas_updated.attach(signal_triggered.signal_triggered) + + assert not organizer.player_areas + + organizer.add_card(card_1, "player", 0) + + assert signal_triggered.signal_trigger_count == 1 + assert len(organizer.player_areas) == 1 + assert len(organizer.player_areas[0]) == 1 + assert organizer.player_areas[0][0].position.as_tuple == ( + player_card_area_config.x + player_card_area_config.width / 2, + player_card_area_config.y, + ) + + organizer.add_card(card_2, "player", 0) + + # Check signal trigger + assert signal_triggered.signal_trigger_count == 2 + + assert len(organizer.player_areas) == 1 + assert len(organizer.player_areas[0]) == 2 + + # Check if adding new card didn't change first card position + assert organizer.player_areas[0][0].position.as_tuple == ( + player_card_area_config.x + player_card_area_config.width / 2, + player_card_area_config.y, + ) + + # Checking new card position, with offset + assert organizer.player_areas[0][1].position.as_tuple == ( + player_card_area_config.x + + player_card_area_config.width / 2 + + extra_card_offset.x, + player_card_area_config.y + extra_card_offset.y, + ) + + +def test_player_cards_multi_hand(): + card_1 = Card(1) + card_2 = Card(2) + player_card_area_config = game_view_config.card_areas.player + + signal_triggered = SignalTriggerCounter() + + organizer = CardAreaOrganizer() + organizer.areas_updated.attach(signal_triggered.signal_triggered) + + organizer.add_card(card_1, "player", 0) + organizer.add_card(card_2, "player", 1) + + # Check signal trigger + assert signal_triggered.signal_trigger_count == 2 + + assert len(organizer.player_areas) == 2 + assert len(organizer.player_areas[0]) == 1 + assert len(organizer.player_areas[1]) == 1 + + # Check the old card's position (it should have changed) + assert organizer.player_areas[0][0].position.as_tuple == ( + round(player_card_area_config.x + + player_card_area_config.width / 3), + player_card_area_config.y, + ) + + # Checking new card position + assert organizer.player_areas[1][0].position.as_tuple == ( + round(player_card_area_config.x + + 2 * player_card_area_config.width / 3), + player_card_area_config.y, + ) + + +def test_player_cards_split(): + card_1 = Card("QUEEN") + card_2 = Card("KING") + card_3 = Card(1) + player_card_area_config = game_view_config.card_areas.player + + signal_triggered = SignalTriggerCounter() + + organizer = CardAreaOrganizer() + organizer.areas_updated.attach(signal_triggered.signal_triggered) + + organizer.add_card(card_1, "player", 0) + organizer.add_card(card_2, "player", 0) + organizer.add_card(card_3, "player", 1) + organizer.split_hand(0) + + assert len(organizer.player_areas) == 3 + assert len(organizer.player_areas[0]) == 1 + assert len(organizer.player_areas[1]) == 1 + assert len(organizer.player_areas[2]) == 1 + assert organizer.player_areas[0][0].position.as_tuple == ( + round(player_card_area_config.x + player_card_area_config.width / 4), + player_card_area_config.y, + ) + assert organizer.player_areas[1][0].position.as_tuple == ( + round(player_card_area_config.x + + 2 * player_card_area_config.width / 4), + player_card_area_config.y, + ) + assert organizer.player_areas[2][0].position.as_tuple == ( + round(player_card_area_config.x + + 3 * player_card_area_config.width / 4), + player_card_area_config.y, + ) + + # Check signal trigger + assert signal_triggered.signal_trigger_count == 4 + + +def test_clear_areas(): + card_1 = Card(1) + card_2 = Card(2) + + signal_triggered = SignalTriggerCounter() + + organizer = CardAreaOrganizer() + organizer.areas_updated.attach(signal_triggered.signal_triggered) + + organizer.add_card(card_1, "dealer") + organizer.add_card(card_2, "player", 0) + organizer.clear_areas() + + assert signal_triggered.signal_trigger_count == 3 + assert len(organizer.dealer_area) == 0 + assert len(organizer.player_areas) == 0 diff --git a/src/views/view_game.py b/src/views/view_game.py new file mode 100644 index 0000000..c671240 --- /dev/null +++ b/src/views/view_game.py @@ -0,0 +1,111 @@ +from collections import defaultdict + +import pygame + +from src.button import Button +from src.cards.card import Card +from src.common.constants import CONFIG_GAME_VIEW +from src.common.func_pictures import load_image +from src.common.game_view_config import game_view_config +from src.views.card_area_organizer import CardAreaOrganizer +from src.views.image_loaders.tokensloader import TokensLoader + + +class ViewGame: + def __init__(self, window): + self._area_counts = defaultdict(int) + + # Organizers + self.card_area_organizer = CardAreaOrganizer() + self.organizers = ( + self.card_area_organizer, + ) + + self.subscribe_to_organizers() + + # Buttons + self.buttons = dict() + + # Init Window + self.window = window + self.background = None # init in init_window + self.init_window() + + def subscribe_to_organizers(self): + for organizer in self.organizers: + organizer.areas_updated.attach(self.refresh) + + def init_window(self): + # Init the window with background + bgd_tile = load_image("green_carpet.jpeg") + bgd_tile = pygame.transform.scale( + bgd_tile, (game_view_config.window.width, game_view_config.window.height) + ) + self.background = pygame.Surface( + (game_view_config.window.width, game_view_config.window.height) + ) + self.background.blit(bgd_tile, (0, 0)) + + # Display on windows + self.window.blit(self.background, (0, 0)) + + self.init_game_btns() + + # Display everything + pygame.display.flip() + + # Init sprites + # all_sprites = pygame.sprite.Group() + # + # # Update the scene + # dirty = all_sprites.draw(self.window) + # pygame.display.update(dirty) + self.card_area_organizer.add_card(Card("KING"), "dealer") + self.card_area_organizer.add_card(Card("QUEEN"), "dealer") + + self.card_area_organizer.add_card(Card("ACE", "SPADES"), "player", 0) + + def init_game_btns(self): + # Display game buttons area + cfg_btns = game_view_config.game_menu_area + pygame.draw.rect( + self.window, + cfg_btns.color, + (cfg_btns.x, cfg_btns.y, cfg_btns.width, cfg_btns.height), + ) + + # FIXME: Use the config instance instead + for iid, btn_params in CONFIG_GAME_VIEW["game_buttons"].items(): + b = Button( + self.window, + **btn_params + ) + b.draw() + self.buttons[iid] = b + + def refresh(self): + print("Updating View...") + # Init sprites + sprite_group = pygame.sprite.Group() + + self.window.blit(self.background, (0, 0)) + self.init_game_btns() + + for el in self.card_area_organizer.dealer_area: + self.window.blit(el.surface, el.position.as_tuple) + for area in self.card_area_organizer.player_areas: + for el in area: + self.window.blit(el.surface, el.position.as_tuple) + + # TODO: Tokens should be resized and transparent + token = TokensLoader.get_image(10) + token = pygame.transform.scale( + token, (game_view_config.tokens.width, game_view_config.tokens.height) + ) + self.window.blit(token, (500, 300)) + + # Update the scene + scene = sprite_group.draw(self.window) + pygame.display.flip() + + print("Updating View...Done!") diff --git a/src/views/view_menu.py b/src/views/view_menu.py new file mode 100644 index 0000000..b2975de --- /dev/null +++ b/src/views/view_menu.py @@ -0,0 +1,141 @@ +# import os.path + +import pygame +from pygame.locals import * +from typing import List + +from src.common.constants import Game, Moves +from src.common.func_pictures import load_image + +from src.button import Button + +# TODO: Use a class instead of a function +def main(window: pygame.Surface, menu_config: dict, menu_buttons: dict): + """ The main function of the view of menu""" + + # Init window + screen = window + state = Game.menu + + # Load background image + bgd_tile = load_image("green_carpet.jpeg") + background = pygame.Surface((menu_config["width"], menu_config["height"])) + background.blit(bgd_tile, (0, 0)) + + # Prepare text + title_font = pygame.font.Font(None, 44) + title_text = title_font.render("Black Jack Project", 2, (255, 255, 255)) + + # Buttons + btn_index = 0 + default_btn_format = { + 'text_color': (0, 0, 0), + 'bd': 0, + 'bd_color': (255, 255, 255), + 'bg_normal': None + } + selected_btn_format = { + 'text_color': (255, 255, 255), + 'bd': 2, + 'bd_color': (255, 255, 255), + 'bg_normal': (0, 170, 140) + } + + def update_button_display(btn_index: int, btns_list: List[Button]): + # Update button view according btn_index + for btn in btns_list: + btn.set(**default_btn_format) + btns_list[btn_index].set(**selected_btn_format) + + # Update buttons display + screen.blit(background, (0, 0)) + screen.blit(title_text, (80, 30)) + for btn in btns_list: + btn.draw() + pygame.display.flip() + + def move_btn_index(move: Moves, btn_index: int, btns_list: List[Button]): + # Change btn_index + btn_index += move.value + btn_index %= len(btns_list) + + update_button_display(btn_index, btns_list) + + return btn_index + + def cmd_play_btn(): + nonlocal state + state = Game.play + + def cmd_option_btn(): + nonlocal state + state = Game.option + + def cmd_quit_btn(): + nonlocal state + state = Game.quit + + disp = ( + ("play_btn", "Start (s)", cmd_play_btn), + ("option_btn", "Options (o)", cmd_option_btn), + ("quit_btn", "Quit (Esc)", cmd_quit_btn) + ) + btns_list = list() + for iid, text, cmd in disp: + b = Button( + window=window, + text=text, + pos=(menu_buttons[iid]["x"], menu_buttons[iid]["y"]), + size=(200, 50) + ) + b.signal.attach(cmd) + btns_list.append(b) + + update_button_display(btn_index, btns_list) + + # Display on windows + screen.blit(background, (0, 0)) + screen.blit(title_text, (80, 30)) + for btn in btns_list: + btn.draw() + + pygame.display.flip() + + # Init sprites + all_sprites = pygame.sprite.RenderUpdates() + clock = pygame.time.Clock() + + while state == Game.menu: + + # Clear all the sprites + all_sprites.clear(screen, bgd_tile) + all_sprites.update() + + # Check for events + for event in pygame.event.get(): + if event.type == QUIT: + state = Game.quit + elif event.type == KEYDOWN and event.key == K_RETURN: + btns_list[btn_index].signal.emit() + elif event.type == KEYDOWN and event.key == K_s: + state = Game.play + elif event.type == KEYDOWN and event.key == K_o: + state = Game.option + elif event.type == KEYDOWN and event.key == K_ESCAPE: + state = Game.quit + + elif event.type == KEYDOWN and event.key == K_DOWN: + btn_index = move_btn_index(Moves.down, btn_index, btns_list) + elif event.type == KEYDOWN and event.key == K_UP: + btn_index = move_btn_index(Moves.up, btn_index, btns_list) + + for btn in btns_list: + btn.handle_event(event) + + # Update the scene + dirty = all_sprites.draw(screen) + pygame.display.update(dirty) + + clock.tick(40) + + return state, dict() diff --git a/src/views/view_option.py b/src/views/view_option.py new file mode 100644 index 0000000..e2be47e --- /dev/null +++ b/src/views/view_option.py @@ -0,0 +1,52 @@ +import pygame +from pygame.locals import * + +import src.common.constants as cst +from src.common.func_pictures import load_image + + +def main(window, menu_config): + """ The main function of the view of options""" + + # Init window + screen = window + + # Load background image + bgd_tile = load_image("green_carpet.jpeg") + background = pygame.Surface((menu_config["width"], menu_config["height"])) + background.blit(bgd_tile, (0, 0)) + + # Prepare text + title_font = pygame.font.Font(None, 44) + title_text = title_font.render("Options", 2, (255, 255, 255)) + + # Display on windows + screen.blit(background, (0, 0)) + screen.blit(title_text, (80, 30)) + pygame.display.flip() + + # Init sprites + all_sprites = pygame.sprite.RenderUpdates() + clock = pygame.time.Clock() + + state = cst.Game.option + while state == cst.Game.option: + + # Clear all the sprites + all_sprites.clear(screen, bgd_tile) + all_sprites.update() + + # Check for events + for event in pygame.event.get(): + if event.type == QUIT: + state = cst.Game.menu + elif (event.type == KEYDOWN and event.key == K_ESCAPE): + state = cst.Game.menu + + # Update the scene + dirty = all_sprites.draw(screen) + pygame.display.update(dirty) + + clock.tick(40) + + return state, dict()