Python Programming: Caesar Cipher

# Caesar Cipher
# URL: https://inventwithpython.com/cipher.py

MAX_KEY_SIZE = 26

def getMode():
    while True:
        print('Do you wish to encrypt or decrypt a message?')
        mode = input().lower()
        if mode in 'encrypt e decrypt d'.split():
            return mode
        else:
            print('Enter either "encrypt" or "e" or "decrypt" or "d".')

def getMessage():
    print('Enter your message:')
    return input()

def getKey():
    key = 0
    while True:
        print('Enter the key number (1-%s)' % (MAX_KEY_SIZE))
        key = int(input())
        if (key >= 1 and key <= MAX_KEY_SIZE):
            return key

def getTranslatedMessage(mode, message, key):
    if mode[0] == 'd':
        key = -key
    translated = ''

    for symbol in message:
        if symbol.isalpha():
            num = ord(symbol)
            num += key

            if symbol.isupper():
                if num > ord('Z'):
                    num -= 26
                elif num < ord('A'):
                    num += 26
            elif symbol.islower():
                if num > ord('z'):
                    num -= 26
                elif num < ord('a'):
                    num += 26

            translated += chr(num)
        else:
            translated += symbol
    return translated

mode = getMode()
message = getMessage()
key = getKey()

print('Your translated text is:')
print(getTranslatedMessage(mode, message, key))

Python Game: Sonar

# Sonar
# URL: https://inventwithpython.com/sonar.py

import random
import sys

def drawBoard(board):
    # Draw the board data structure.

    hline = '    ' # initial space for the numbers down the left side of the board
    for i in range(1, 6):
        hline += (' ' * 9) + str(i)

    # print the numbers across the top
    print(hline)
    print('   ' + ('0123456789' * 6))
    print()

    # print each of the 15 rows
    for i in range(15):
        # single-digit numbers need to be padded with an extra space
        if i < 10:
            extraSpace = ' '
        else:
            extraSpace = ''
        print('%s%s %s %s' % (extraSpace, i, getRow(board, i), i))

    # print the numbers across the bottom
    print()
    print('   ' + ('0123456789' * 6))
    print(hline)


def getRow(board, row):
    # Return a string from the board data structure at a certain row.
    boardRow = ''
    for i in range(60):
        boardRow += board[i][row]
    return boardRow

def getNewBoard():
    # Create a new 60x15 board data structure.
    board = []
    for x in range(60): # the main list is a list of 60 lists
        board.append([])
        for y in range(15): # each list in the main list has 15 single-character strings
            # use different characters for the ocean to make it more readable.
            if random.randint(0, 1) == 0:
                board[x].append('~')
            else:
                board[x].append('`')
    return board

def getRandomChests(numChests):
    # Create a list of chest data structures (two-item lists of x, y int coordinates)
    chests = []
    for i in range(numChests):
        chests.append([random.randint(0, 59), random.randint(0, 14)])
    return chests

def isValidMove(x, y):
    # Return True if the coordinates are on the board, otherwise False.
    return x >= 0 and x <= 59 and y >= 0 and y <= 14

def makeMove(board, chests, x, y):
    # Change the board data structure with a sonar device character. Remove treasure chests
    # from the chests list as they are found. Return False if this is an invalid move.
    # Otherwise, return the string of the result of this move.
    if not isValidMove(x, y):
        return False

    smallestDistance = 100 # any chest will be closer than 100.
    for cx, cy in chests:
        if abs(cx - x) > abs(cy - y):
            distance = abs(cx - x)
        else:
            distance = abs(cy - y)

        if distance < smallestDistance: # we want the closest treasure chest.
            smallestDistance = distance

    if smallestDistance == 0:
        # xy is directly on a treasure chest!
        chests.remove([x, y])
        return 'You have found a sunken treasure chest!'
    else:
        if smallestDistance < 10:
            board[x][y] = str(smallestDistance)
            return 'Treasure detected at a distance of %s from the sonar device.' % (smallestDistance)
        else:
            board[x][y] = 'O'
            return 'Sonar did not detect anything. All treasure chests out of range.'


def enterPlayerMove():
    # Let the player type in her move. Return a two-item list of int xy coordinates.
    print('Where do you want to drop the next sonar device? (0-59 0-14) (or type quit)')
    while True:
        move = input()
        if move.lower() == 'quit':
            print('Thanks for playing!')
            sys.exit()

        move = move.split()
        if len(move) == 2 and move[0].isdigit() and move[1].isdigit() and isValidMove(int(move[0]), int(move[1])):
            return [int(move[0]), int(move[1])]
        print('Enter a number from 0 to 59, a space, then a number from 0 to 14.')


def playAgain():
    # This function returns True if the player wants to play again, otherwise it returns False.
    print('Do you want to play again? (yes or no)')
    return input().lower().startswith('y')


def showInstructions():
    print('''Instructions:
You are the captain of the Simon, a treasure-hunting ship. Your current mission
is to find the three sunken treasure chests that are lurking in the part of the
ocean you are in and collect them.

To play, enter the coordinates of the point in the ocean you wish to drop a
sonar device. The sonar can find out how far away the closest chest is to it.
For example, the d below marks where the device was dropped, and the 2's
represent distances of 2 away from the device. The 4's represent
distances of 4 away from the device.

    444444444
    4       4
    4 22222 4
    4 2   2 4
    4 2 d 2 4
    4 2   2 4
    4 22222 4
    4       4
    444444444
Press enter to continue...''')
    input()

    print('''For example, here is a treasure chest (the c) located a distance of 2 away
from the sonar device (the d):

    22222
    c   2
    2 d 2
    2   2
    22222

The point where the device was dropped will be marked with a 2.

The treasure chests don't move around. Sonar devices can detect treasure
chests up to a distance of 9. If all chests are out of range, the point
will be marked with O

If a device is directly dropped on a treasure chest, you have discovered
the location of the chest, and it will be collected. The sonar device will
remain there.

When you collect a chest, all sonar devices will update to locate the next
closest sunken treasure chest.
Press enter to continue...''')
    input()
    print()


print('S O N A R !')
print()
print('Would you like to view the instructions? (yes/no)')
if input().lower().startswith('y'):
    showInstructions()

while True:
    # game setup
    sonarDevices = 16
    theBoard = getNewBoard()
    theChests = getRandomChests(3)
    drawBoard(theBoard)
    previousMoves = []

    while sonarDevices > 0:
        # Start of a turn:

        # sonar device/chest status
        if sonarDevices > 1: extraSsonar = 's'
        else: extraSsonar = ''
        if len(theChests) > 1: extraSchest = 's'
        else: extraSchest = ''
        print('You have %s sonar device%s left. %s treasure chest%s remaining.' % (sonarDevices, extraSsonar, len(theChests), extraSchest))

        x, y = enterPlayerMove()
        previousMoves.append([x, y]) # we must track all moves so that sonar devices can be updated.

        moveResult = makeMove(theBoard, theChests, x, y)
        if moveResult == False:
            continue
        else:
            if moveResult == 'You have found a sunken treasure chest!':
                # update all the sonar devices currently on the map.
                for x, y in previousMoves:
                    makeMove(theBoard, theChests, x, y)
            drawBoard(theBoard)
            print(moveResult)

        if len(theChests) == 0:
            print('You have found all the sunken treasure chests! Congratulations and good game!')
            break

        sonarDevices -= 1

    if sonarDevices == 0:
        print('We\'ve run out of sonar devices! Now we have to turn the ship around and head')
        print('for home with treasure chests still out there! Game over.')
        print('    The remaining chests were here:')
        for x, y in theChests:
            print('    %s, %s' % (x, y))

    if not playAgain():
        sys.exit()

Python Game: GUI Russian Roulette

# Russian Roulette
#
# Based on visual basic code found at:
# http://www.vintage-basic.net/bcg/russianroulette.bas

from tkinter import *
import random
import time
 
#root window
root = Tk()

#window title
root.title("Russian Roulette")

#window geometry
root.geometry("400x875")

#variables
rannum = IntVar() # Holds an integer; default value 0

#random_answers
random_answers = ["BANG!!!!! YOU'RE DEAD!\nCONDOLENCES WILL BE SENT TO YOUR RELATIVES.",
                 "YOU WIN!!!!!\nLET SOMEONE ELSE BLOW HIS BRAINS OUT."]



L1 = Label(root, text = "RUSSIAN ROULETTE")
L1.pack()
L2 = Label(root, text = "CREATIVE COMPUTING\nMORRISTOWN, NEW JERSEY")
L2.pack()
L3 = Label(root, text = "THIS IS A GAME OF RUSSIAN ROULETTE.")
L3.pack()
L4 = Label(root, text = "HERE IS A REVOLVER.")
L4.pack()
L5 = Label(root, text = "SPIN CHAMBER AND PULL TRIGGER")
L5.pack()
L6 = Label(root, text = "OR GIVE UP?")
L6.pack()

def goodbye(): 
    root.destroy()

def gu():
    L7 = Label(root, foreground='black', background='yellow', text = "CHICKEN!!!!!")
    L7.pack()
    # Disable button so user can't click again
    b1.config(state="disabled")
    b2.config(state="disabled")
    button = Button (root, text="QUIT", command=goodbye)
    button.pack()
   

def sp():
    L8 = Label(root, text = "- CLICK -")
    L8.pack()
    answer_1 = Label(root, text=random.choice(random_answers))
    answer_1.pack()
    L9 = Label(root, text = "...NEXT VICTIM...")
    L9.pack()
    

b1 = Button(root,
            text="SPIN",
            command=sp)
b1.pack()

b2 = Button(root,
            text="GIVE UP",
            command=gu)
b2.pack()

root.mainloop()

How to read from a binary file in C programming

/*
* Program to read from a binary file
* From the book: C Programming Visual Quickstart Guide
*/

#include <stdio.h>

/*
* Set the file path and name. 
*/

#define THEFILE "numbers.dat"

/*
* Number of the items being wrritten.
*/

#define ITEMS 50

int main (void) {

/*
* Need a pointer of type FILE.
*/

FILE *fp;

/*
* Loop counter
*/

int i;

/*
* Array of numbers.
*/

int numbers[ITEMS];

/*
* Attempt to open the file for reading
*/

fp = fopen(THEFILE, "rb");

/*
* The file is open.
*/

if (fp != NULL) {

printf("The contents of the numbers file:\n");

/*
* Read the entire contents into the numbers array.
*/

fread(numbers, sizeof(int), ITEMS, fp);

/*
* Print each element.
*/

for (i = 0; i < ITEMS; i++) {

printf("%d\n", numbers[i]);

}

} else {

printf("The file could not be opened.\n");

/*
* Exit the function/application.
*/

return 1;
}

/*
* Close the file
*/

if (fclose(fp) != 0) {

printf("The file could not be closed/\n");
}

/*
* Pause
*/

getchar();
return 0;

}

How to change fonts in Python 3 using the tkinter module

# Original Source: http://www.devdungeon.com/content/gui-programming-python
# change_font.py
from tkinter import Tk, Message
root = Tk()

msg = Message(root, text='Hello, world!')

# Font is a tuple of (font_family, size_in_points, style_modifier_string)
msg.config(font=('times', 48, 'italic bold underline'))

msg.pack()

root.mainloop()

How to write to a binary file in C Programming

/*
* Program to write to a binary file
* From the book:
*
* This program writes fifty random numbers 
* (between 0 and 99) to a binary file.
*/

#include <stdio.h>
#include <stdlib.h> // For rand() and srand()
#include <time.h> // For time(), used with srand()

/*
* Set the file path and name as a C preprocessor macro.
* .dat is the three letter extension representing data.
*/

#define THEFILE "numbers.dat" 

/*
* Create a constant macro representing the number of 
* items in the array. 
*/

#define ITEMS 50

/*
* Begin the main function and create file pointer.
*/

int main (void) {

/*
* Need a pointer of type FILE.
*/

FILE *fp;

/*
* Loop counter.
*/

int i;

/*
* Array in which random numbers will be stored.
*/

int numbers[ITEMS];

/*
* Attempt to open the file for binary writing.
* This call opens the file for writing, creating
* the file if it doesn't exist, and wiping out
* any existing data. The binary mode is indicated
* by adding the b. This is only required on Windows.
*/

fp = fopen(THEFILE, "wb");

/*
* The file is open. Start a conditional based on 
* the file pointer. 
*/

if (fp != NULL) {

/*
* Seed the rand() function.
*/

srand((unsigned)time(NULL));

/*
* Populate the array with random numbers 
* less than 100. The for loop counts from
i to ITEMS, the number of elements in the
* array. Within the loop, each element is 
* assigned a random value between 0 and 99.
* This limit is accomplished by assigning 
* the remainder of dividing by the random 
* number by 100, rather than assigning the
* random number itself (which could be as 
* high as 32,767).
*/

for (i = 0; i < ITEMS; i++) {
numbers[i] = rand() % 100;

}

/*
* Write the array elements to the 
* binary file and print a message to
* the user. The fwrite() line starts
* by using the numbers variable as its
* pointer. This works because an array
* name is equivalent to its address in C.
* The function is then told to write ITEMS
* number of blocks, each of which is
* sizeof(int) bytes in size. We use 
* sizeof(int) because numbers is an array
* of integers.
*/

fwrite (numbers, sizeof(int), ITEMS, fp);

printf("The data has been written.\n");

} else {

printf("The file cound not be opened. \n");

/*
* Exit the function/application.
*/

return 1;

}

/*
* Close the file.
*/

if (fclose(fp) != 0) {
printf("The file could not be closed.\n");
}

/*
* Pause.
*/
getchar();

return 0;
}

Python Game: Mad Lib

# Mad Lib
# Create a story based on user input
# From the book: Python Programming for the Absolute Beginner

from tkinter import *

class Application(Frame):
    """ GUI application that creates a story based on user input. """
    def __init__(self, master):
        """ Initialize Frame. """
        Frame.__init__(self, master)
        self.grid()
        self.create_widgets()

    def create_widgets(self):
        """ Create widgets to get story information and to display story. """
        # create instruction label
        Label(self,
              text = "Enter information for a new story"
              ).grid(row = 0, column = 0, columnspan = 2, sticky = W)

        # create a label and text entry for the name of a person
        Label(self,
              text = "Person: "
              ).grid(row = 1, column = 0, sticky = W)
        self.person_ent = Entry(self)
        self.person_ent.grid(row = 1, column = 1, sticky = W)

        # create a label and text entry for a plural noun
        Label(self,
              text = "Plural Noun:"
              ).grid(row = 2, column = 0, sticky = W)
        self.noun_ent = Entry(self)
        self.noun_ent.grid(row = 2, column = 1, sticky = W)

        # create a label and text entry for a verb
        Label(self,
              text = "Verb:"
              ).grid(row = 3, column = 0, sticky = W)
        self.verb_ent = Entry(self)
        self.verb_ent.grid(row = 3, column = 1, sticky = W)
     
        # create a label for adjectives check buttons
        Label(self,
              text = "Adjective(s):"
              ).grid(row = 4, column = 0, sticky = W)

        # create itchy check button
        self.is_itchy = BooleanVar()
        Checkbutton(self,
                    text = "itchy",
                    variable = self.is_itchy
                    ).grid(row = 4, column = 1, sticky = W)

        # create joyous check button
        self.is_joyous = BooleanVar()
        Checkbutton(self,
                    text = "joyous",
                    variable = self.is_joyous
                    ).grid(row = 4, column = 2, sticky = W)

        # create electric check button
        self.is_electric = BooleanVar()
        Checkbutton(self,
                    text = "electric",
                    variable = self.is_electric
                    ).grid(row = 4, column = 3, sticky = W)

        # create a label for body parts radio buttons
        Label(self,
              text = "Body Part:"
              ).grid(row = 5, column = 0, sticky = W)

        # create variable for single, body part
        self.body_part = StringVar()
  
        # create body part radio buttons
        body_parts = ["bellybutton", "big toe", "medulla oblongata"]
        column = 1
        for part in body_parts:
            Radiobutton(self,
                        text = part,
                        variable = self.body_part,
                        value = part
                        ).grid(row = 5, column = column, sticky = W)
            column += 1

        # create a submit button
        Button(self,
               text = "Click for story",
               command = self.tell_story
               ).grid(row = 6, column = 0, sticky = W)

        self.story_txt = Text(self, width = 75, height = 10, wrap = WORD)
        self.story_txt.grid(row = 7, column = 0, columnspan = 4)

    def tell_story(self):
        """ Fill text box with new story based on user input. """
        # get values from the GUI
        person = self.person_ent.get()
        noun = self.noun_ent.get()
        verb = self.verb_ent.get()
        adjectives = ""
        if self.is_itchy.get():
            adjectives += "itchy, "
        if self.is_joyous.get():
            adjectives += "joyous, "
        if self.is_electric.get():
            adjectives += "electric, "
        body_part = self.body_part.get()

        # create the story
        story = "The famous explorer "
        story += person
        story += " had nearly given up a life-long quest to find The Lost City of "
        story += noun.title()
        story += " when one day, the "
        story += noun
        story += " found "
        story += person + ". "
        story += "A strong, "
        story += adjectives
        story += "peculiar feeling overwhelmed the explorer. "
        story += "After all this time, the quest was finally over. A tear came to "
        story += person + "'s "
        story += body_part + ". "
        story += "And then, the "
        story += noun
        story += " promptly devoured "
        story += person + ". "
        story += "The moral of the story? Be careful what you "
        story += verb
        story += " for."
        
        # display the story                                
        self.story_txt.delete(0.0, END)
        self.story_txt.insert(0.0, story)

# main
root = Tk()
root.title("Mad Lib")
app = Application(root)
root.mainloop()

How to use radio buttons using tkinter in Python 3

# Movie Chooser 2
# Demonstrates radio buttons
# From the book: Python Programming for the Absolute Beginner

from tkinter import *

class Application(Frame):
    """ GUI Application for favorite movie type. """
    def __init__(self, master):
        """ Initialize Frame. """
        Frame.__init__(self, master)
        self.grid()
        self.create_widgets()

    def create_widgets(self):
        """ Create widgets for movie type choices. """
        # create description label
        Label(self,
              text = "Choose your favorite type of movie"
              ).grid(row = 0, column = 0, sticky = W)

        # create instruction label
        Label(self,
              text = "Select one:"
              ).grid(row = 1, column = 0, sticky = W)

        # create variable for single, favorite type of movie
        self.favorite = StringVar()

        # create Comedy radio button
        Radiobutton(self,
                    text = "Comedy",
                    variable = self.favorite,
                    value = "comedy.",
                    command = self.update_text
                    ).grid(row = 2, column = 0, sticky = W)

        # create Drama radio button
        Radiobutton(self,
                    text = "Drama",
                    variable = self.favorite,
                    value = "drama.",
                    command = self.update_text
                    ).grid(row = 3, column = 0, sticky = W)

        # create Romance radio button
        Radiobutton(self,
                    text = "Romance",
                    variable = self.favorite,
                    value = "romance.",
                    command = self.update_text
                    ).grid(row = 4, column = 0, sticky = W)

        # create text field to display result
        self.results_txt = Text(self, width = 40, height = 5, wrap = WORD)
        self.results_txt.grid(row = 5, column = 0, columnspan = 3)

    def update_text(self):
        """ Update text area and display user's favorite movie type. """
        message = "Your favorite type of movie is "
        message += self.favorite.get()
            
        self.results_txt.delete(0.0, END)
        self.results_txt.insert(0.0, message)

# main
root = Tk()
root.title("Movie Chooser 2")
app = Application(root)
root.mainloop()

How to use check button using tkinter in Python 3

# Movie Chooser
# Demonstrates check buttons
# From the book: Python Programming for the Absolute Beginner

from tkinter import *

class Application(Frame):
    """ GUI Application for favorite movie types. """
    def __init__(self, master):
        Frame.__init__(self, master)
        self.grid()
        self.create_widgets()

    def create_widgets(self):
        """ Create widgets for movie type choices. """    
        # create description label
        Label(self,
              text = "Choose your favorite movie types"
              ).grid(row = 0, column = 0, sticky = W)

        # create instruction label
        Label(self,
              text = "Select all that apply:"
              ).grid(row = 1, column = 0, sticky = W)
        
        # create Comedy check button
        self.likes_comedy = BooleanVar()
        Checkbutton(self,
                    text = "Comedy",
                    variable = self.likes_comedy,
                    command = self.update_text
                    ).grid(row = 2, column = 0, sticky = W)

        # create Drama check button
        self.likes_drama = BooleanVar()
        Checkbutton(self,
                    text = "Drama",
                    variable = self.likes_drama,
                    command = self.update_text
                    ).grid(row = 3, column = 0, sticky = W)

        # create Romance check button
        self.likes_romance = BooleanVar()
        Checkbutton(self,
                    text = "Romance",
                    variable = self.likes_romance,
                    command = self.update_text
                    ).grid(row = 4, column = 0, sticky = W)

        # create text field to display results
        self.results_txt = Text(self, width = 40, height = 5, wrap = WORD)
        self.results_txt.grid(row = 5, column = 0, columnspan = 3)

    def update_text(self):
        """ Update text widget and display user's favorite movie types. """
        likes = ""
        
        if self.likes_comedy.get():
            likes += "You like comedic movies.\n"

        if self.likes_drama.get():
            likes += "You like dramatic movies.\n"

        if self.likes_romance.get():
            likes += "You like romantic movies."
      
        self.results_txt.delete(0.0, END)
        self.results_txt.insert(0.0, likes)

# main
root = Tk()
root.title("Movie Chooser")
app = Application(root)
root.mainloop()