Game Development Reference
In-Depth Information
14 - Caesar Cipher
Getting the Key from the Player
18. def getKey():
19. key = 0
20. while True:
21. print('Enter the key number (1-%s)' %
(MAX_KEY_SIZE))
22. key = int(input())
23. if (key >= 1 and key <= MAX_KEY_SIZE):
24. return key
The
getKey()
function lets the player type in key they will use to encrypt or decrypt
the message. The
while
loop ensures that the function only returns a valid key. A valid
key here is one that is between the integer values
1
and
26
(remember that
MAX_KEY_SIZE
will only have the value
26
because it is constant). It then returns this
key. Remember that on line 22 that
key
was set to the integer version of what the user
typed in, and so
getKey()
returns an integer.
Encrypt or Decrypt the Message with the Given Key
26. def getTranslatedMessage(mode, message, key):
27. if mode[0] == 'd':
28. key = -key
29. translated = ''
getTranslatedMessage()
is the function that does the encrypting and decrypting
in our program. It has three parameters.
mode
sets the function to encryption mode or
decryption mode.
message
is the plaintext (or ciphertext) to be encrypted (or decrypted).
key
is the key that is used in this cipher.
The first line in the
getTranslatedMessage()
function determines if we are in
encryption mode or decryption mode. If the first letter in the
mode
variable is the string
'd'
, then we are in decryption mode. The only difference between the two modes is that in
decryption mode, the key is set to the negative version of itself. If
key
was the integer
22
,
then in decryption mode we set it to
-22
. The reason for this will be explained later.
translated
is the string that will hold the end result: either the ciphertext (if we are
encrypting) or the plaintext (if we are decrypting). We will only be concatenating strings to
this variable, so we first store the blank string in
translated
. (A variable must be
defined with some string value first before a string can be concatenated to it.)
The
isalpha()
String Method
The
isalpha()
string method will return
True
if the string is an uppercase or