3kstc
3kstc

Reputation: 1956

How to print with different colours with Python using termcolor inside an array?

I am fairly new to python, and wrote my second game, as I feel this is the best way to learn a new language. My code is as follows:

The Code:

#!/usr/bin/env python

from random import randint
from termcolor import colored
import os
import sys
import time
clear = lambda : os.system('tput reset')

clear()

board = []

board_size=5

for x in range(board_size):
    board.append(["[W]"] * board_size)

def print_board(board):
    for row in board:
        print colored(" ".join(row),"cyan")

#print "Let's play Battleship!"
print_board(board)

def random_row(board):
    return randint(0, len(board) - 1)

def random_col(board):
    return randint(0, len(board[0]) - 1)

ship_row = random_row(board) +1
ship_col = random_col(board) +1

# Prints  where the ship is placed
# Do the right and don't cheat! 
# print ship_row
# print ship_col


print colored("\nNot bombed:      ","yellow") + colored("[W]","cyan")
print colored("Has been bombed: ","yellow") + colored("[","cyan") + colored("X","red") + colored("]\n","cyan")

guess_row = int(raw_input("Guess Row:")) 
guess_col = int(raw_input("Guess Col:"))

counter=0

state=True

while bool(state):

    counter=int(counter)+1

    if guess_row == ship_row and guess_col == ship_col:
        clear()
        print "\n\n  Congratulations! You sunk my battleship!\n\n"
        print "You got it right after " + str(counter) + " guesses."
        state=False
        time.sleep(2)
        clear()
        sys.exit()

    else:
        if (guess_row -1 < 0 or guess_row > board_size) or (guess_col -1 < 0 or guess_col > board_size):
            print "Oops, that's not even in the ocean."
            counter=int(counter)-1
            time.sleep(1)
            clear()

        elif(board[guess_row-1][guess_col-1] == "[X]"):
            print "You guessed that one already."
            counter=int(counter)-1
            time.sleep(1)
            clear()

        else:
            print "You missed my battleship!"
            clear()
            board[guess_row-1][guess_col-1] = "[X]"
            #counter=int(counter)+1


    print_board(board)

    print colored("\nNot bombed:      ","yellow") + colored("[W]","cyan")
    print colored("Has been bombed: ","yellow") + colored("[","cyan") + colored("X","red") + colored("]\n","cyan")

    guess_row = int(raw_input("Guess Row:"))
    guess_col = int(raw_input("Guess Col:"))

I want to, when the user guesses I just want the letter X to be red, as the key suggests.

Current output:

enter image description here

Note how only "X" is in red and the square brackets are cyan, this is fundamentally what I want to achieve in the game.

Ideal output:

enter image description here

Question:

How can I make it print as above?

Upvotes: 3

Views: 3405

Answers (2)

Open AI - Opting Out
Open AI - Opting Out

Reputation: 24133

The problem code is:

print colored(" ".join(row),"cyan")

You need:

print ' '.join(colored(element, 'cyan') if element != 'X'
               else colored(element, 'red')
               for element in row)

edit

More generally, you could look up the colour based upon the character. A common tool is to use Python's dict which provides a mapping between keys and values.

>>> color_key = {
...     'X': 'red',
...     'H': 'magenta'}
>>> color_key['X']
'red'

If you use get you can provide a default for missing keys:

>>> color_key.get('[', 'cyan')
'cyan'

otherwise you'll raise an exception:

>>> color_key['[']
...KeyError...

Usage:

print ' '.join(colored(element, color_key.get(element, 'cyan')
           for element in row)

Upvotes: 2

Mitch Pomery
Mitch Pomery

Reputation: 493

You are going to want to update the print_board method.

def print_board(board):
    for row in board:
        print colored(" ".join(row),"cyan")

Without writing the exact code you'll need to write, you'll need to change this to:

def print_board(board):
    for row in board:
        for each cell in the row:
            if it is a W:
                print it cyan
            if it is an X:
                print it in red
        move to a new line now

Normally when you print it will put in a newline, so you will need to check out How to print without newline or space?

Upvotes: 2

Related Questions