Python Forum
My version of Rock Paper Scissors
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
My version of Rock Paper Scissors
#1
Tried my luck with rock paper scissors game from one of the post.
It contains terminal/console colors and may not show colors on windows systems.
As always, I welcome feedback.

#! /usr/bin/env python3

import random as rnd
import os
import sys
from subprocess import call

class Game:
    def __init__(self):
        # Default scores
        self.player_wins = 0
        self.computer_wins = 0

        # Setup our choices
        self.options = ['rock', 'paper', 'scissors']

        # Clear the screen and display title
        self.clear()
        print(f'\033[38;2;15;200;200m\033[4m\033[1mRock Paper Scissors\033[0m')
        print()
        while True:
            try:
                # Show wins/scores
                self.score()
                # Display player Choices
                print(f'\033[38;2;100;255;100m"q" or "quit" without quotes to exit game\033[0m \n')
                print(f'\033[38;2;255;190;190mChoices: {", ".join(self.options)}\033[0m')
                # Give player input field
                self.player_choice = input('Player Choice: ').lower()
                # If player wants to exit the game
                if self.player_choice == 'q' or self.player_choice == 'quit':
                    self.clear()
                    # Display the over all winner
                    if self.player_wins > self.computer_wins:
                        total = self.convert(self.player_wins, self.computer_wins)
                        print(f'Player is over all winner. Player won {total} of the games played.')
                    elif self.player_wins < self.computer_wins:
                        total = self.convert(self.computer_wins, self.player_wins)
                        print(f'Computer is over all winner. Computer won {total} of the games played.')
                    else:
                        print('Nobody is the over all winner')
                    print('\033[38;2;20;190;255mThanks for playing\033[0m')
                    sys.exit()

                # Setup some errors if wrong input is entered
                if self.player_choice.replace('.','').isdigit():
                    self.clear()
                    print(f'\033[38;2;255;0;0mNumbers are not allowed\033[0m')
                    continue
                elif self.player_choice not in self.options:
                    self.clear()
                    print(f'\033[38;2;255;0;0mPlease use only the given choices\033[0m')
                    continue
                else:
                    self.clear()
                    print(self.play())
                    print()

            except ValueError as error:
                print(f'Error: {error}')

    def play(self):
        # Get the computers random choice
        computer = self.computer()
        # Display player and computers choices
        print(f'\033[38;2;10;250;190mPlayer Choice\033[0m: {self.player_choice}')
        print(f'\033[38;2;190;190;150mComputer Choice\033[0m: {computer}')

        # Who wins
        if self.player_choice == 'rock' and computer == 'scissors':
            winner = f'\033[38;2;10;250;190mPlayer\033[0m\033[38;2;10;200;250m {self.player_choice} beats {computer}'
            self.player_wins += 1
        elif self.player_choice == 'paper' and computer == 'rock':
            winner = f'\033[38;2;10;250;190mPlayer\033[0m\033[38;2;10;200;250m {self.player_choice} beats {computer}'
            self.player_wins += 1
        elif self.player_choice == 'scissors' and computer == 'paper':
            winner = f'\033[38;2;10;250;190mPlayer\033[0m\033[38;2;10;200;250m {self.player_choice} beats {computer}'
            self.player_wins += 1
        elif self.player_choice == computer:
            winner = 'Player and Computer tie'
        else:
            winner = f'\033[38;2;190;190;150mComputer\033[0m\033[38;2;10;200;250m {computer} beats {self.player_choice}'
            self.computer_wins += 1
        return f'\n\033[38;2;10;200;250mWinner: {winner}\033[0m'

    # Helps clear the screen so there is not a terminal full of text
    def clear(self):
        _ = call('clear' if os.name == 'posix' else 'cls')

    # Define the computers choice
    def computer(self):
        self.computer_choice = rnd.choice(self.options)
        return self.computer_choice

    # For displaying the score/wins
    def score(self):
        print('\033[1m\033[38;2;200;200;150mWins:\033[0m')
        print(f'\033[38;2;10;250;190mPlayer\033[0m: {self.player_wins} | \033[38;2;190;190;150mComputer\033[0m: {self.computer_wins}')
        print()

    def convert(self, num1, num2):
        total = num1 / (num1 + num2)
        return format(total, '.0%')

def main():
    Game()

if __name__ == '__main__':
    main()
I welcome all feedback.
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags


Reply
#2
Truthfully, this is interactive
pyzyx3qwerty
"The greatest glory in living lies not in never falling, but in rising every time we fall." - Nelson Mandela
Need help on the forum? Visit help @ python forum
For learning more and more about python, visit Python docs
Reply
#3
Wow, Don't think I've seen this level of detail in a Rock paper scissors game.
Reply
#4
Simple color version. Works on windows and linux. I do not know about macs.
Requires colorama for windows
python3 -m pip install colorama

#! /usr/bin/env python3

# Do the imports
import random as rnd
import os
from time import sleep as os_sleep

# Check if the os is *nix or windows
# if it's windows import colorama and initiate
if os.name == 'nt':
    import colorama
    colorama.init()
else:
    pass

# Define some basic ansi colors
red = '\033[31m'
yellow = '\033[33m'
cyan = '\033[36m'
blue = '\033[34m'
magenta = '\033[35m'
green = '\033[32m'

bright_red = '\033[91m'
bright_yellow = '\033[33;1m'
bright_cyan = '\033[36;1m'
bright_blue = '\033[34;1m'
bright_magenta = '\033[35;1m'
bright_green = '\033[32;1m'

# Other ansi sequences
underline = '\033[4m'
bold = '\033[1m'

# Resets all ansi to system default
reset = '\033[0m'


class Game:
    def __init__(self):
        # Set some default options
        self.player_wins = 0
        self.computer_wins = 0
        self.ties = 0
        self.games_played = 0

        self.player_name = ''

        # Define our choices
        self.options = ['rock', 'paper', 'scissors']

        # Clears the screen so we do not have cluttered text
        self.clear()
        # Display the game title
        print(f'{underline}{bright_blue}Rock Paper Scissors{reset}\n')

        # Start the game loop
        while True:
            try:
                # Check if we have a player name. If not ask for one.
                if not self.player_name:
                    self.player_name = input("What's your name?: ").lower()
                    # This throws an error if player does not enter a name.
                    if not self.player_name:
                        self.clear()
                        print(f'{bright_red}Error!{reset}: {bright_yellow}Please enter a player name.{reset}')
                        continue
                    # Welcome the player to the game and do a countdown to game start
                    else:
                        self.clear()
                        i = 10
                        while i > 0:
                            print(f'Hello {bright_cyan}{self.player_name.title()}{reset}! Welcome to the {bright_blue}Rock Paper Scissors{reset} Game!')
                            print(f'Game starting in {bright_yellow}{i}{reset}')
                            i -= 1
                            os_sleep(1)
                            self.clear()
                # Everything is ok up to this point. Start the game
                print(f'\n{yellow}Type "q" or "quit" without quotes to exit game.{reset}\n')
                print(f'{bright_blue}Choices: {", ".join(self.options).title()}{reset}')

                self.player_choice = input(f'Player Choice: ').lower()

                # Player enter q or qiut to exit the game
                if self.player_choice == 'q' or self.player_choice == 'quit':
                    self.clear()

                    # Check for the overall winner
                    if self.player_wins > self.computer_wins:
                        total = self.convert(self.player_wins, self.computer_wins, self.ties)
                        print(f'{bright_cyan}{self.player_name.title()}{reset} is the overall winner.')
                        print(f'{bright_cyan}{self.player_name.title()}{reset} won {total} of the games played.')

                    elif self.computer_wins > self.player_wins:
                        total = self.convert(self.computer_wins, self.player_wins, self.ties)
                        print(f'{bright_magenta}Computer{reset} is the overall winner.')
                        print(f'{bright_magenta}Computer{reset} won {total} of the games played.')

                    else:
                        print(f'No player is the overall winner.')

                    print(f'{bright_green}Games Played{reset}: {self.games_played}\n')

                    print(f'{bright_yellow}Thanks for playing{reset} {bright_cyan}{self.player_name.title()}{bright_yellow}!{reset}')
                    os.sys.exit()

                # Setup some errors if wrong input is entered
                if self.player_choice.replace('.', '').isdigit():
                    self.clear()
                    print(f'{bright_red}Error!: {bright_yellow}Numbers are not allowed.{reset}')
                    continue
                elif self.player_choice not in self.options:
                    self.clear()
                    print(f'{bright_red}Error!: {bright_yellow}Please use only the given choices.{reset}')

                # No errors continue to play
                else:
                    self.clear()
                    print(self.play())

            # Throw an exception if any unknown errors
            except ValueError as error:
                print(f'{bright_red}Error!{reset}: {yellow}{error}{reset}')

            # Show scores
            print()
            self.score()

    # This function is used to clear the screen of cluttered text
    def clear(self):
        # Check if the os is windows or not
        if os.name == 'nt':
            _ = os.system('cls')
        else:
            _ = os.system('clear')

    def play(self):
        # Get the computer's choice
        computer = self.computer()

        self.games_played += 1

        # Print out what each has chosen
        print(f'\n{bright_cyan}{self.player_name.title()}{reset} Chose: {self.player_choice.title()}')
        print(f'{bright_magenta}Computer{reset} Chose: {computer.title()}\n')

        txt1 = 'Rock Crushes Scissors'
        txt2 = 'Paper Covers Rock'
        txt3 = 'Scissors Cuts Paper'

        # Check to see who won and return
        if self.player_choice == 'rock' and computer == 'scissors':
            winner = f'{bright_cyan}{self.player_name.title()}{reset} won! {txt1}.'
            self.player_wins += 1
        elif self.player_choice == 'paper' and computer == 'rock':
            winner = f'{bright_cyan}{self.player_name.title()}{reset} won! {txt2}.'
            self.player_wins += 1
        elif self.player_choice == 'scissors' and computer == 'paper':
            winner = f'{bright_cyan}{self.player_name.title()}{reset} won! {txt3}.'
            self.player_wins += 1

        elif computer == 'rock' and self.player_choice == 'scissors':
            winner = f'{bright_magenta}Computer{reset} won! {txt1}'
            self.computer_wins += 1
        elif computer == 'paper' and self.player_choice == 'rock':
            winner = f'{bright_magenta}Computer{reset} won! {txt2}'
            self.computer_wins += 1
        elif computer == 'scissors' and self.player_choice == 'paper':
            winner = f'{bright_magenta}Computer{reset} won! {txt3}'
            self.computer_wins += 1
        else:
            winner = f'{bright_cyan}{self.player_name.title()}{reset} and {bright_magenta}Computer{reset} have tied.\nThere is no winner.'
            self.ties += 1
        return winner

    # Get a random choice for the computer and return
    def computer(self):
        self.computer_choice = rnd.choice(self.options)
        return self.computer_choice

    # Displays the score/wins
    def score(self):
        print(f'{cyan}Score{reset}:')
        print(f'{bright_cyan}{self.player_name.title()}{reset}: {self.player_wins} | {bright_magenta}Computer{reset}: {self.computer_wins} | {bright_yellow}Ties{reset}: {self.ties}')
        print()

    # Convert wins into percentages
    def convert(self, num1, num2, num3):
        total = num1 / (num1 + num2 + num3)
        return format(total, '.0%')


def main():
    Game()

if __name__ == '__main__':
    main()
I welcome all feedback.
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags


Reply
#5
(Jun-02-2020, 09:59 AM)menator01 Wrote: Simple color version. Works on windows and linux. I do not know about macs.
I tried it on my mac - works fine
pyzyx3qwerty
"The greatest glory in living lies not in never falling, but in rising every time we fall." - Nelson Mandela
Need help on the forum? Visit help @ python forum
For learning more and more about python, visit Python docs
Reply
#6
I'm eager to try this out, but I'm not having any luck in Windows 10 (with colorama installed) or Linux Mint 19.3. I'm just seeing the control characters like:
Output:
Rock Paper Scissors What's your name?:
What am I missing? Confused
Reply
#7
Which are you trying? The first post or the second? Should work with the second.
I welcome all feedback.
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags


Reply
#8
I tried them both on Linux Mint, and the second one on Windows 10. I'm updating my Ubuntu box (20.04) now to give it a shot on that one.
Reply
#9
On ubuntu
I welcome all feedback.
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags


Reply
#10
(Jun-02-2020, 03:46 PM)menator01 Wrote: On ubuntu

Looks very cool, but it's not working for me in Ubuntu, either. I'm sure it's something on my end, just not sure what it could be. Huh

Just in case I'm doing something dumb: I'm opening IDLE, creating a new file, pasting in the code, then saving and executing. Anything I could be overlooking? (No need to pursue it any further if you can't think of anything obvious I'm missing, but thanks!)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Another Rock, Paper, Scissors Yoriz 4 3,126 Jun-30-2020, 07:56 PM
Last Post: Yoriz
  The tkinter version of Rock Paper Scissors menator01 3 3,144 Jun-28-2020, 07:15 AM
Last Post: ndc85430
  PyQt5 Version of Rock, Paper, & Scissors menator01 8 3,607 Jun-06-2020, 12:15 PM
Last Post: pyzyx3qwerty
  Rock, Paper, Scissors foksikrasa 11 4,235 May-28-2020, 05:58 PM
Last Post: BitPythoner
  Rock Paper Scissor GAME inamullah9 3 3,229 Aug-11-2019, 12:17 PM
Last Post: ichabod801
  A CLI based Rock,Paper or Scissor game. Ablazesphere 7 4,427 Oct-28-2018, 07:25 AM
Last Post: Ablazesphere
  A basic Rock-paper-scissors game by me... Unlimiter 0 2,454 Dec-25-2017, 03:41 PM
Last Post: Unlimiter
  Basic Rock, Paper, Scissors CinnamonBeard 1 3,524 Dec-19-2017, 02:32 PM
Last Post: sparkz_alot

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020