problem in character creation for mud game in python - python-3.x

hello i m new to python and i m making a mud game so i m stuck at a certain point where i have to create a character and following is my code. as i need to give 2 option to the player with the description and then player will select one of the given choices. help me with the code in python.
def selectcharacter():
character = ""
while character != "Red pirate" and character != "dreed prince":
character = input("which character you want to choose? (Red pirate or Dreed prince ):")
return character
def checkcharacter(chosencharacter):
if (chosencharacter == Red pirate):
print("the ability of the character is to fight close range battles and has 125 health and 50 armor!"),
if (chosencharacter == Dreed prince):
print("the ability of the character is to fight long range battles and has 100 health and 25 armor!")
else:
print("no character selected.please select the character!")
checkcharacter()
selectcharacter()

You have some syntax errors and you need to pass a string as a function argument.
From what I can tell you want to first select a character and then change the output based on your selection.
Your code is almost working you just need to fix the syntax errors and save the selection in a variable, to be able to pass it to the next function.
def selectcharacter():
character = ""
while character != "Red pirate" and character != "Dreed prince":
character = input("which character you want to choose? (Red pirate or Dreed prince ):")
return character
def checkcharacter(chosencharacter):
if (chosencharacter == "Red pirate"): # should be string
print("the ability of the character is to fight close range battles and has 125 health and 50 armor!"),
elif (chosencharacter == "Dreed prince"): # should be string
print("the ability of the character is to fight long range battles and has 100 health and 25 armor!")
else:
print("no character selected.please select the character!")
selected_character = selectcharacter()
checkcharacter(selected_character)
The characters should be converted to strings, so you can check if they are equal to the passed argument chosencharacter. You also should use an elif instead of a second if because, otherwise the second if would get evaluated (to False) even if the first one is True.

Related

How to check if a string contains only letters or only numbers?

I'm creating a login system which includes a password strength test. A password must contain letters and numbers, uppercase and lowercase letters and be between 6 and 12 characters in length. I am being told that there is a syntax error but not where. I have only just added in the password strength test to a much larger program, and I know that the rest of the program is working perfectly and that therefore this section is the issue.
def Password():
global UName
global FName
global SName
global Email
print('A secure password should be between 6 and 12 letters in')
print('length, have upper and lowercase letters and have numbers.')
PWord = input('Please enter a secure password:')
if PWord.isalpha() or if PWord.isdigit():
if len(PWord) < 6 or if len(Pword) > 12:
if PWord.isupper() or if PWord.islower():
print('You need upper and lowercase letters. Try again')
Password()
else:
print('Password is strong')
g = open('Database1.txt', 'a')
g.write('\n' + UName +',')#Writes user details to database file
g.write(FName +',')
g.write(SName +',')
g.write(Email +',')
g.write(PWord +',')
g.close()#Closes file
h = open('Database2.txt', 'a')
Daily = input('Enter your daily energy use target:')
Monthly = input('Enter your monthly energy use target:')
Yearly = input('Enter your yearly energy use target:')
h.write('\n' + UName +',')#Writes user details to the second database file
h.write(Daily +',')
h.write(Monthly +',')
h.write(Yearly +',')
h.write('0' +',')#Other values
h.write('0' +',')#Other values
h.write('0' +',')#Other values
h.write('0' +',')#Other values
h.close()#Closes file
main()#takes user back to menu so they can login
else:
print('Password is not the correct length, try again')
Password()
else:
print('You need letters and numbers, try again')
Password()
UName, FName, SName and Email are all taken from a previous function, hence why they have been declared as global variables.
By commenting out various sections, I have determined that the line
if PWord.isalpha() or if PWord.isdigit():
is throwing up the syntax error, but I can't work out why. I have created systems like this before and can't determine the issue. If someone could help me I would be very grateful.
This is why the syntax error is here
you can put multiple conditions in the if conditions by using and or operators no need to use if multiple times.
You can also use regex to validate the password here -
import re
password = raw_input("Enter string to test: ")
if re.match(r'[A-Za-z0-9##$%^&+=]{6,12}', password):
# match
else:
# no match
Here's the explanation for the regex
[A-Za-z0-9##$%^&+=]{6,12} " gm Match a single character present in the
list below [A-Za-z0-9##$%^&+=]{8,} {8,} Quantifier — Matches between 8
and unlimited times, as many times as possible, giving back as needed
(greedy) A-Z a single character in the range between A (index 65) and
Z (index 90) (case sensitive) a-z a single character in the range
between a (index 97) and z (index 122) (case sensitive) 0-9 a single
character in the range between 0 (index 48) and 9 (index 57) (case
sensitive) ##$%^&+= matches a single character in the list ##$%^&+=
(case sensitive) Global pattern flags g modifier: global. All matches
(don't return after first match) m modifier: multi line. Causes ^ and
$ to match the begin/end of each line (not only begin/end of string)
try
if PWord.isalpha() or PWord.isdigit():
But you better have to use regex for that, as explained in others answers
Good luck

Replace isn't working for every letter in python

import time, random
#WELSCR
print(WOF1)
print("\n")
print(WOF2)
print("\n"*2)
input("Hit enter to play")
print("\n"*45)
print(WOF1)
print("\n")
print(WOF2)
doublespace = print("\n\n")
singlespace = print("\n")
tripplespace = print("\n\n\n")
guessed = []
score = 1000
wrong = 0
puzzle , hint = random.choice(questions)
blank = puzzle
for round in range (1,10):
tries = 0
iscorrect = False
while (not iscorrect) and (tries < 6):
blank = puzzle
for letter in blank:
if letter in "abcdefghijklmnopqrstuvwxyz":
blank = blank.replace(letter, "-")
def print_puzzle():
print("\n"*45)
print(WOF1)
print("\n")
print(WOF2)
print("\n"*2)
print(blank.center(80))
print("The hint is:",hint.title())
print("You currently have $",score)
print_puzzle()
input("enter")
break
break
This is the beginning of my program that I just started, a wheel of fortune game for a class. I can get it to replace almost all of the letters with a dash, however, there are the occasional few letters that do not always get hidden by this code and I'm not sure why. I have a variable defined as question which is a nested tuple but I did not include it because it's long and contains about 150 different entries.
Nevermind, the problem was case sensitivity. I had proper nouns and capitalized them, but I did not include capital letters in my replace string.

Using the random function in Python for Evil Hangman

What I am trying to do is alter my original hangman game into what is called evil hangman. In order to do this, I need to first generate a random length of a word and pull out all words of that length from the original list.
Here is the code I am working with:
def setUp():
"""shows instructions, reads file,and returns a list of words from the english dictionary"""
try:
print(60*'*' +'''\n\t\tWelcome to Hangman!\n\t
I have selected a word from an english dictionary. \n\t
I will first show you the length of the secret word\n\t
as a series of dashes.\n\t
Your task is to guess the secret word one letter at a time.\n\t
If you guess a correct letter I will show you the guessed\n\t
letter(s) in the correct position.\n
You can only make 8 wrong guesses before you are hanged\n
\t\tGood luck\n''' + 60*'*')
infile=open('dictionary.txt')
l=infile.readlines()# list of words from which to choose
infile.close()
cleanList = []
for word in l:
cleanList.append(l[:-1])
return(cleanList)
except IOError:
print('There was a problem loading the dictionary file as is.')
def sort_dict_words_by_length(words):
"""Given a list containing words of different length,
sort those words based on their length."""
d = defaultdict(list)
for word in words:
d[len(word)].append(word)
return d
def pick_random_length_from_dictionary(diction):
max_len, min_len = ( f(diction.keys()) for f in (max, min) )
length = random.randint(min_len, max_len)
return diction[length]
def playRound(w,g):
""" It allows user to guess one letter. If right,places letter in correct positions in current guess string g, and shows current guess to user
if not, increments w, number of wrongs. Returns current number of wrongs and current guess string"""
print('You have ' + str(8 - w) + ' possible wrong guesses left.\n')
newLetter = input('Please guess a letter of the secret word:\n')
glist = list(g)#need to make changes to current guess string so need a mutable version of it
if newLetter in secretWord:
for j in range (0,len(secretWord)):
if secretWord[j]==newLetter:
glist[j] = newLetter
g = ''.join(glist)#reassemble the guess as a string
print('Your letter is indeed present in the secret word: ' + ' '.join(g)+'\n')
else:
w += 1
print('Sorry, there are no ' + newLetter + ' in the secret word. Try again.\n')
return(w,g)
def endRound(wr, w,l):
"""determines whether user guessed secret word, in which case updates s[0], or failed after w=8 attempts, in s\which case it updates s[1]"""
if wr == 8:
l += 1
print('Sorry, you have lost this game.\n\nThe secret word was '+secretWord +'\n')#minor violation of encapsulation
else:
w +=1
print(15*'*' + 'You got it!' + 15*'*')
return(w,l)
def askIfMore():
"""ask user if s/he wants to play another round of the game"""
while True:
more = input('Would you like to play another round?(y/n)')
if more[0].upper() == 'Y' or more[0].upper()=='N':
return more[0].upper()
else:
continue
def printStats(w,l):
"""prints final statistics"""
wGames='games'
lGames = 'games'
if w == 1:
wGames = 'game'
if l ==1:
lGames = 'game'
print('''Thank you for playing with us!\nYou have won {} {} and lost {} {}.\nGoodbye.'''.format(w,wGames,l,lGames))
try:
import random
from collections import defaultdict
words=setUp()#list of words from which to choose
won, lost = 0,0 #accumulators for games won, and lost
while True:
wrongs=0 # accumulator for wrong guesses
secretWord = random.choice(words)[:#eliminates '\n' at the end of each line
print(secretWord) #for testing purposes
guess= len(secretWord)*'_'
print('Secret Word:' + ' '.join(guess))
while wrongs < 8 and guess != secretWord:
wrongs, guess = playRound(wrongs, guess)
won, lost = endRound(wrongs,won,lost)
if askIfMore()== 'N':
break
printStats(won, lost)
except:
quit()
What I would like to do is generate a random number with the lower bound being the shortest length word and the upper bound being the highest length word, and then use that random number to create a new container with words of only that length, and finally returning that container to be used by the game further. I tried using min and max, but it seems to only return the first and last item of the list instead of showing the word with the most characters. Any help is appreciated.
If your 'dictionary.txt' has a single word on each line, you could use the following, which is speed efficient, because it'll only go over the list once. But it'll consume the memory of your original list again.
from collections import defaultdict
import random
def sort_dict_words_by_length(words):
"""Given a list containing words of different length,
sort those words based on their length."""
d = defaultdict(list)
for word in words:
d[len(word)].append(word)
return d
def pick_random_length_from_dictionary(diction):
max_len, min_len = ( f(diction.keys()) for f in (max, min) )
length = random.randint(min_len, max_len)
return diction[length]
You would then pass the output from your setUp to sort_dict_words_by_length and that output to pick_random_length_from_dictionary.
If you are memory-limited, then you should first go over all words in the wordlist, keeping track of the minimal and maximal length of those words and then reiterate over that wordlist, appending only those words of the desired length. What you need for that is mentioned in the code above and just requires some code reshuffling. I'll leave that up to you as an exercise.

using .find for multiple letters in a string

I'm working on a hobby project. I'm attempting to make a hangman game in Python. So far everything works nice. There's just one problem. If I type a letter that appears in the word two times, I can't get the second letter to appear. I've been toying around with string.find and string.count methods but to no avail. Does anyone have an idea how I would go about doing this? I'm stumped.
#!bin/bash/python
import os
import time
word = 'megalopolis'
l = len(word)
list = []
n=0
while n!=l:
list.append('-')
n+=1
os.system('cls' if os.name=='nt' else 'clear')
print list
i=3
while i!=0:
x = raw_input('Enter a letter: ')
if x in word and x!='':
print 'Good choice!'
count=word.count(x)
loc=word.find(x)
print count
print loc
list[loc]=x
os.system('cls' if os.name=='nt' else 'clear')
if '-' not in list:
break
print list
else:
print 'Sorry...'
i-=1
if i==2:
print 'You have '+`i`+' more chances.'
if i==1:
print 'You have '+`i`+' more chance!'
time.sleep(1)
os.system('cls' if os.name=='nt' else 'clear')
print list
if '-' not in list:
print 'YOU WIN!!'
else:
print 'GAME OVER!!'
x = raw_input('press enter')
If you just need the index of every character occurence:
indexes = [idx for idx, ch in enumerate(word) if ch == x]
Perhaps you should use Unidecode to keep the accents in words, it might be useful depending on the language (if not English). Also, you can use str.lower() or str.upper() methods to ensure every word and trial is in the same case.
The string module has useful constants for you (e.g. ascii_uppercase).
However, in this game you don't need to worry about any index. I've made another version for you:
#!/usr/bin/env python
from string import ascii_uppercase
word = "megalopolis".upper() # Top-secret!
trial = 3 # Total trials available (number of mistakes to lose the game)
typed = set() # Typed characters
word_letters = set(word)
while trial:
print
print "".join(ch if ch in typed else "-" for ch in word)
# Winning condition
if typed.issuperset(word_letters):
break
# Data input
x = raw_input("Enter a letter: ").upper()
# Error cases
if len(x) != 1:
print "Invalid input."
continue
if x in typed:
print "Already typed."
continue
if x not in ascii_uppercase:
print "What you typed isn't a letter."
continue
# Valid data cases
typed.add(x)
if x in word:
print "Good choice!"
else:
print "{} not found!".format(x),
trial -= 1
if trial == 1:
print "You have one more chance!"
elif trial > 1:
print "You have {} more chances.".format(trial)
else:
print 'Sorry...'
# Ending message
print
if trial:
print "YOU WIN!!"
else:
print "GAME OVER!!"
Hashbang: Your shebang should usually start with "#!/". You're probably using Windows, so the "bin" as a relative directory wasn't used by you.
"l" / l as a variable name should be avoided! It might be seen as one or lower "L" (PEP8), or even a pipe "|". PS: At the beginning of this item, I typed the same letter here twice.
There's no need to use "list" as a variable name here, and you shouldn't do, as that's a built-in name.
Multiplication like "txt" * 3 returns "txttxttxt" (it repeats the data) for both strings and lists
Neither "cls" nor "clear" worked here, showing
"TERM environment variable not set."
instead of clearing the console screen. I replaced these with an empty
"print", and removed the time sleep. Look for subprocess if you want to call something from console (although I'd also look for curses if there's a need to do some CLI visualization).
Suppose x is a string. When x == "", bool(x) is False, else bool(x) is True.
Suppose x is an integer. When x == 0, bool(x) is False, else bool(x) is True.
Avoid backticks (`). No one uses them today in Python, they doesn't exist in Python 3 and you can use the repr built-in instead. However, you probably wanted something like str(trial), "%d" % trial or "{}".format(trial).
The last "press enter" probably has to do with an operating system "auto-close-after-finish" behaviour, but you [at least] didn't need to store it in x.
I've used a generator expression. You should read here about list comprehensions if the "for" in the middle of one line is confusing for you. Python developers use generator expressions and list comprehensions all the time, you shouldn't avoid learning about them.
I replaced the original winning evaluation to a comparison between the set of characters the word originally has and the set of typed characters (both uppercase).
If there's something here you didn't understand, please ask a new question.
This SO question ought to cover it for you:
Finding multiple occurrences of a string within a string in Python
It should work just as well for individual characters as strings, considering how easy it is to form the second from the first.
So in the end, I wound up doing it this way:
if x in word and x!='':
count=word.count(x)
loc=0
while count==1 or count>1:
loc=word.find(x,loc)
list[loc]=x
loc+=1
count-=1
print 'Good choice!'
Thanks for your help everyone. I definitely learned something.

Can someone explain Rule 110 in the simplest way possible?

I can't wrap my head around what the Wikipedia article or the answer here say.
Can someone explain Rule 110 in simple terms? How does it guarantee Turing completeness?
My attempt at a succinct, layman's terms explanation:
Rule 110 is an elementary cellular automaton: a rule for transforming a finite pattern of 1's and 0's into another pattern of 1's and 0's.
When Rule 110 is iteratively applied on certain input bit sequences, patterns emerge depending on sub-sequences found in the input bits. Given enough iterations, the following can happen:
The original sub-sequence appears in the same location as in the original input.
The original sub-sequence is preserved but 'moves' to a different location in the bitfield.
Two sub-sequences moving toward each other interact and 'pass through' each other.
Two sub-sequences combine to create a new sub-sequence.
Different sub-sequences can be given symbolic meaning like '1', '0', 'clock pulse', or 'production rule' that correspond to the elements of a cyclic tag system.
With many iterations of Rule 110 on a carefully constructed input bitfield, the interaction of the sub-sequences simulates the behavior of a cyclic tag system.
A cyclic tag system can be used to simulate a universal Turing machine. Thus a cyclic tag system is Turing-complete.
Since Rule 110 can simulate a cyclic tag system, it too is Turing-complete.
I'll have a go at elaborating: I don't think you are looking for more details of the proof which is already quite complex in the article, although it clearly omits many details.
To quote from the article you cite: "In an elementary cellular automaton, a one-dimensional pattern of 0's and 1's evolves according to a simple set of rules. Whether a point in the pattern will be 0 or 1 depends in the new generation on its current value, as well of that of its two neighbors. The Rule 110 automaton has the following set of rules..." (see the wikipedia table that follows)
The starting point, which you can view as the data, but which can be taken as a representation of code (representing code as data is necessary for any proof of Turing-completeness; this goes back to Turing's original results), is a sequence of 0's and 1's, often, but not necessarily, surrounded on both sides by cells containing just 0. Rule 110 shows how that sequence evolves. For instance, if there is a pattern of 3 1's in one row, the middle 1 will "die" (turn into a 0) in the next row. What happens to its two neighbours depends on how the pattern extends beyond them. The triangular diagrams you see are a graphical representation of the evolution of the automaton from the original state, coding 1 as black and 0 as white and representing evolution from above to below. The initial state is often very short in length to show how very complex patterns can evolve from simple initial states.
Two unusual features of the proof of Turing completeness are that, firstly, it looks highly unlikely that such a very simple rule could do everything your favourite programming language could do, and secondly, which makes the first fact rather less amazing, is that the proof requires an infinitely long repeating background on which to work its magic. I cannot see anything fundamentally dishonest about this though; no more so than assuming a potentially infinite or semi-infinite blank tape, as Turing originally did.
To understand the proof properly you would need to get to grips with how data (and later, code) is encoded in the starting pattern, and it also looks as if familiarity with cyclic tag systems would help enormously. I'm not the person to explain those.
Although it may seem harder to understand the situation with a 2-D cellular automaton, such as Conway's "Game of Life", I found it instructive to play with that game, studying "gliders", "glider guns" and "puffer trains" and other amusing constructions. (A puffer train constructs glider guns and a glider gun fires gliders). These can be used to establish Turing-completeness for this automaton as well.
You may also find the talk page informative (you are not alone in not grasping the point, see the entry beginning "the pictures don't make any sense to me..").
In 1970 John Conway has invented Game of Life.
Ever since, I think almost every programmer tried to write its implementation - I certainly did long time ago, and it was a lot of fun.
This game is actually cellular automaton, which sets simple rules between generations of cells in infinite 2-dimensional plane. For example, if in current generation cell has less than 2 neighbors alive (bit value 1), then it should die in next generation of loneliness. If it has more than 3 neighbors alive, it should die of overcrowding. If empty (bit value 0, or dead) cell has exactly 3 neighbors, it will cause it to be born (become 1).
Since then, it was found that Game of Life is surprisingly complex - it can generate a lot of very complex patterns that continue to evolve. Also, it was shown that it is Turing-complete, that is, you can encode arbitrarily complex algorithms using starting cell combination as a program, and final combination as a result. However, it took few years to find how to actually generate complicated forms, like gliders or guns.
Now back to what rule 110 is. Simply put, rule 110 is one-dimensional variation of Game of Life.
110 is just a decimal number representation of binary string 01101110 which is short form of rule system of how current generation of cells (bits) will be translated into next one, similar to Game of Life's rule system of cells dying of loneliness or overcrowding and being born of having exactly three neighbors.
Much like Game of Life, it has been proven that rule 110 is Turing-complete. You can encode arbitrarily complex algorithm using starting cells (bits) combination as your program, and final bits combination as a result.
An implementation in python:
(Be adviced: actual python programmers would kill you for this)
import time
seed = raw_input("Feed me a string! (At least 3 characters long please)\n>")
lastline = '>'
iterator = 0
while (iterator<len(seed)):
temp = (ord(seed[iterator]))%2
if (temp == 1):
lastline += '#'
else:
lastline += ' '
iterator += 1
stop = 0
while (stop != 1): #Keep printing as long as CTRL-C isn't pressed
#dummy = raw_input(lastline)
print lastline
iterator = 0
nextline = '>'
while (iterator<len(seed)): #Convert entire string
if (len(seed) < 3): # if wrong
print "You had ONE JOB!"
stop = 1
elif (iterator == 0): # if at start
if (lastline[1] == ' '):
nextline += ' '
else:
nextline += '#'
elif (iterator+1 == len(seed)): # if at end
if (lastline[iterator+1] == ' '):
nextline += ' '
else:
nextline += '#'
else: #if in middle
if (lastline[iterator] == '#' and lastline[iterator+1] == '#' and lastline[iterator+2] == '#'): #111
nextline += ' '
elif (lastline[iterator] == '#' and lastline[iterator+1] == '#' and lastline[iterator+2] == ' '): #110
nextline += '#'
elif (lastline[iterator] == '#' and lastline[iterator+1] == ' ' and lastline[iterator+2] == '#'): #101
nextline += '#'
elif (lastline[iterator] == '#' and lastline[iterator+1] == ' ' and lastline[iterator+2] == ' '): #100
nextline += ' '
elif (lastline[iterator] == ' ' and lastline[iterator+1] == '#' and lastline[iterator+2] == '#'): #011
nextline += '#'
elif (lastline[iterator] == ' ' and lastline[iterator+1] == '#' and lastline[iterator+2] == ' '): #010
nextline += '#'
elif (lastline[iterator] == ' ' and lastline[iterator+1] == ' ' and lastline[iterator+2] == '#'): #001
nextline += '#'
else: # (lastline[iterator-1] == ' ' and lastline[iterator] == ' ' and lastline[iterator+1] == ' '): #000
nextline += ' '
iterator += 1
lastline = nextline
time.sleep(0.02)

Resources