DragonMastur 23 Light Poster

I am trying to convert a file to a dictionary here is the contents of the file,

Name: DragonMastur;
Hand: None;
Inventory: {"Gold": 0, "Brush": 0, "Twig": 0, "Sapling": 0, "Metal Axe": 0, "Grass": 0, "Metal Pickaxe": 0, "Metal": 0, "Log": 0, "Diamond": 0, "Stick": 0, "Stone": 0, "Wheat": 0, "Stone Axe": 0, "Stone Pickaxe": 0};
Health: 100;

And here is my code for conversion,

file = open(self.curDir+"/playerstats.txt", "r")
print(file.read().strip().split(";\n"))
print(editor.join(file.read().strip().split(";\n"), ": "))
print(editor.join(file.read().strip().split(";\n"), ": ").split(": "))
self.playerinfo = editor.dictfromlist(editor.join(file.read().strip().split(";\n"), ": ").split(": "))
self.playerinfo["Inventory"] = ast.literal_eval(self.playerinfo["Inventory"].strip().strip(";"))
file.close()
print(self.playerinfo)

The "self.curDir" is the directory with all my files, it opens the file fine but it returns a blank string and/or list after I try to convert it.

And here is the funtion in my custom moudle "editor",

def join(self, list, joiner="\n"):
    returnstr = ""
    for x in list:
        returnstr += str(x) + joiner
    returnstr = returnstr[:-int(len(joiner))]
    return returnstr

Thanks all help helps.

DragonMastur 23 Light Poster

use the random module and a for loop like this.

import random

ll = "a;b;c;d;e;f;g;h;i;j;k;l;m;n;o;p;q;r;s;t;u;v;w;x;y;z"
ul = "A;B;C;D;E;F;G;H;I;J;K;L;M;N;O;P;Q;R;S;T;U;V;W;X;Y;Z"
key = []
finalKey = []
finalKeyStr = ""
lettersList = ll.split(";") + ul.split(";")

for number in range(0, 100):
    key.append(str(random.randint(1, 26)))

for letter in range(0, 100):
    key.append(str(random.choice(lettersList)))

for char in key:
    rl = random.choice(key)
    key.remove(rl)
    finalKey.append(rl)

for char in finalKey:
    finalKey.remove(char)
    finalKeyStr += char

print(str(finalKeyStr))
DragonMastur 23 Light Poster

It looks as if only 1/4 of your moudles are missing so looking in your python folder for your moduldes is a way to start.

Locations of folders:
Mac: /Users/Shared/bin/python
Then look for the lib folder.

Windows: C:\Python34\Lib
Replace "Python34" with what ever version of python your running.

If you what to make your own module any thing with a init is concidered a moulde by python.

If this doesn't work try copy and pasting the modules from PyInstaller to the python library. Also try rearanging your imports, which order they import in.

DragonMastur 23 Light Poster

Change the dict(zip(v_Keys, v_Values)) to OrderedDict(zip(v_Keys, v_Values)), on line 4. Thanks megaflo!

DragonMastur 23 Light Poster

My dad gave me a programing idea but I needed ordered dictionaries. I could solve it till now. Thanks!

DragonMastur 23 Light Poster

Nice. I like the way you used a loop to make the widgets and place them I never thought of that.

DragonMastur 23 Light Poster

I would like the widgets on the window to expand as you expand the window. I know you can do it with the pack method but I'm using the grid method to arange my widgets.

Pack Method:

label = Label(root, text="Some Text")
label.pack(expand=1, fill=BOTH)

Grid Method I'm using:

self.inventoryLabel = Label(self.root, text="\nInventory")
self.inventoryLabel.grid(row=3, column=15, columnspan=15, rowspan=1)
DragonMastur 23 Light Poster

I needed a calculator and I didn't want to use google since my internet is slow. So I made one! Here it is.

Working with it is simple. Use the number and operation keys("c" for clear, "p" for pi, and "s" for sqrt) as well as the return and enter key, for equals, or just use the button gui! Hope you like it!

The only thing I would really like to work on is the gui. If some one would help me on that that would be greatly appreciated. I will be adding more operations, fixing the power button, and would eventually like to turn it in to a graphing calculator.

Thank you for all your support!

DragonMastur 23 Light Poster

Also check out my other program(s):

www.prestonprograming.weebly.com

And:

https://www.daniweb.com/software-development/python/code/497789/calculator

Thanks.

DragonMastur 23 Light Poster

It could be simplifide more, I know. I was doing it as an exersise so its rough and skecthy. But it's workable, I tested it more then 50 times.

DragonMastur 23 Light Poster

I got it wrong I have v1.6.3, not v1.6.2. But either way here it is. Almost double in length.

#/User/bin/Python
import os, sys

if sys.hexversion >= 0x030000F0:
    runningPython3 = True
else:
    runningPython3 = False
if runningPython3:
    import tkinter.filedialog as tk_FileDialog
    from tkinter import*
else:
    from Tkinter import*
    import tkFileDialog as tk_FileDialog

class PyEditorErrors:
    def nothingError(self, title="nothingError", buttonText="OK"):
        nothingErrorRoot = Tk()
        nothingErrorRoot.geometry("300x100")
        nothingErrorRoot.minsize(width=300, height=100)
        nothingErrorRoot.title(title)

        nothingErrorMsg = Label(nothingErrorRoot, text="Nothing entered please try again.")
        nothingErrorButton = Button(nothingErrorRoot, text=buttonText, command=nothingErrorRoot.destroy)
        nothingErrorMsg.pack()
        nothingErrorButton.pack()

    def noFileError(self, title="noFileError", buttonText="OK"):
        noFileErrorRoot = Tk()
        noFileErrorRoot.geometry("300x100")
        noFileErrorRoot.minsize(width=300, height=100)
        noFileErrorRoot.title(title)

        noFileErrorMsg = Label(noFileErrorRoot, text="No file found try opening more files.")
        noFileErrorButton = Button(noFileErrorRoot, text=buttonText, command=noFileErrorRoot.destroy)
        noFileErrorMsg.pack()
        noFileErrorButton.pack()

    def mendList(self, list):
        returnstr = ""
        for things in list:
            returnstr += str(things) + "\ "
        return str(returnstr)

    def mendStr(self, str):
        varlist = [str.split(" ")]
        mendList(varlist)

class PyEditor:
    def doNew(self):
        self.askRoot = Tk()
        self.askRoot.geometry("300x200")
        self.askRoot.minsize(width=300, height=200)
        self.askRoot.title("Create New File")

        self.askFileLabel = Label(self.askRoot, text="Enter the file name.")
        self.askFileName = Entry(self.askRoot)
        self.askFileNameDoneButton = Button(self.askRoot, text="Done", command=self.doFileNameDone)

        self.askFileLabel.pack()
        self.askFileName.pack()
        self.askFileNameDoneButton.pack()

    def doFileNameDone(self):
        if str(self.askFileName.get()) != "":
            file = open((self.currentDir+"/Programs/"+self.askFileName.get()), "a")
            self.filename = file.name
            file.close()
            self.windowText.delete(0.0, END)
            self.windowText.insert(0.0, "#")
            self.windowText.insert(END, self.filename)
            self.askRoot.destroy()
        else:
            #self.errors.nothingError("Nothing Entered")
            print("Nothing Entered. Could not create new file.")
            self.askRoot.destroy()

    def doSave(self):
        if self.filename != "":
            file = open(self.filename, "w")
            currentContents = self.windowText.get(0.0, END)
            file.write(currentContents)
            file.close()
            print("Saved contents to",self.filename)
        else:
            #self.errors.noFileError("File Not Found")
            print("File not found. File might not exist.")

    def doSaveAs(self):
        file = tk_FileDialog.asksaveasfile(mode='w', title="Save As File", defaultextension=".py", initialdir=self.currentDir+"/Programs/")
        textoutput = self.windowText.get(0.0,END)
        if file != None:
            file.write(textoutput.rstrip())
            file.write('\n')
            self.filename = file.name
            print("Saved …
DragonMastur 23 Light Poster

I have another version coming, 1.6.2, it has more improvements. I comment things out mostly because I try to make them work in the future. It is also cross platform.

DragonMastur 23 Light Poster

I made a little py editor because I didn't want to go to all the troble of installing an idle, but I didn't like notepad either. Here it is!

JasonHippy commented: A great start, definitely something that can be built upon! +9
DragonMastur 23 Light Poster

Thanks! Never knew about that. See you learn some thing new ever day!

DragonMastur 23 Light Poster

I suggest using Tkinter. It is very simple and it is pre installed in python. Here is an example of a window with a single button.

from Tkinter import *

class App:
    def helloworldButtonClick(self):
        print("Hello World!")

    def __init__(self):
        self.root = Tk()
        self.root.geomentry("200x300")
        self.root.title("Window With Button")

        self.helloworldButton = Button(self.root, text="Hello World", command=self.helloworldButtonClick)
        self.helloworldButton.pack()

if __name__ "__main__":
    app = App()
    app.root.mainloop()

Only 13 lines of actual code!
You can also do listboxs, textboxs, labels, entrys and more!

DragonMastur 23 Light Poster

use pygame or tkinter. I recomend Tkinter. It is what I use.

DragonMastur 23 Light Poster

karmstrong ask in the Python chat if any one was farmilar with converting a for loop in C to Python. Here is a program in python that will do it for you!

Thank You!

Gribouillis commented: interesting attempt +14
DragonMastur 23 Light Poster

what are the error msgs? I tried installing it and needed to set up a PATH for it to word.

DragonMastur 23 Light Poster

vegaseat has it right. I used the same kind of menthod in a program for counting the number of words in a file. I just didn't use the ".lower()" part.

DragonMastur 23 Light Poster

Use a for loop like this:

for x in range(0, 8):
    if validatemove(move) == True:
        capture()

There are 8 posible times of capture in a single move. This doesn't use variables so there is no risk of it running forever.

DragonMastur 23 Light Poster

I think I figuered it out. When I copy and paste on my raspberry pi it doesn't like the tabs. I have to retype the entire program. vegaseat you said you used a raspberry pi. Try copy and pasting the program.

DragonMastur 23 Light Poster
DragonMastur 23 Light Poster

You have some errors on the imports, json and RPG_Data. We need the json and RPG_Data files in order to run the program.

DragonMastur 23 Light Poster

That is very simple math. Try to see if you can come up with something more complex(You should tell the user that they can use a caculator.) Also in line 34 what if the answer is "1221" or somthing random like that?

DragonMastur 23 Light Poster

Yes I have my username and password in there but that is for my raspberry pi. Not any of my other acounts.

DragonMastur 23 Light Poster

What your asking sound a lot like what Im making right now. here is what I have so far...

Note: If you run the program you will have to make some .txt file and change the directories.

import time

i = ""
fileContents = ""
#User 1
password1 = "hellomynameis"
username1 = "DragonMastur"
#User 2
password2 = "michael"
username2 = "aiden"
#User 3
password3 = "..........."
username3 = "..........."

line = "A line looks."

class Book:
    def readBook(self, line):
        print "Fetching Book..."
        file = open('/home/pi/BookFolder/book.txt', mode='r')
        time.sleep(1)
        print "Done"
        time.sleep(1)
        print "\n\n\n"
        while line != "":
            line = str(file.readline())
            print line
        print "\n\n\n"

    def readBook2(self, line):
        print "Fetching Book..."
        file = open('/home/pi/BookFolder/book2.txt', mode='r')
        time.sleep(1)
        print "Done"
        time.sleep(1)
        print "\n\n\n"
        while line != "":
            line = str(file.readline())
            print line
        print "\n\n\n"

    def readBook3(self, line):
        print "Fetching Book..."
        file = open('/home/pi/BookFolder/book3.txt', mode='r')
        time.sleep(1)
        print "Done"
        time.sleep(1)
        print "\n\n\n"
        while line != "":
            line = str(file.readline())
            print line
        print "\n\n\n"

    def __init__(self):
        i = "Input from the user."
        while True:
            print 'Enter Your Username: '
            u = raw_input()
            if u == username1 or u == username2 or u == username3:
                print "Enter Your Password: "
                p = raw_input()
                if p == password1 and u == username1 or p == password2
and u == username2 or p == password3 and u == username3:
                    while i != "q" or i != "Q":
                        print "-------Menu-------"
                        print "Look at book     1"
                        print "Quit             Q"
                        i = raw_input()
                        if i == "1":
                            if u == username1:
                                self.readBook(line) …
DragonMastur 23 Light Poster

I tried copy and pasting the program at the top and it gave me a bunch of syntax errors. Whats up with that. (Im on my raspberry 3.1415926358589793628(pi). Ans yes I have that much memoriesed, not much.

DragonMastur 23 Light Poster

I have a raspberry pi(Using it right now) and an arduino.Ill see if I can use them together. Iam useing the arduino for a science expiriment and know both python and sketch(I think that is the language that arduino runs on.) Thank vegaseat.

DragonMastur 23 Light Poster

vegaseat I tryed to but it didn't work I dont know whats wrong.

But Thanks anyway Everyone.

DragonMastur 23 Light Poster

Thanks guys.

DragonMastur 23 Light Poster

I am try to make a program that alows the user to input their username and password to recive a set of options. Right now the options are to look at a file or quit. In order to complete it I need to know how to turn of the visability on raw_input(). Or how to get input from the user without them knowing what the screen is showing. (Ex: "Hello World" would look like "***********" or nothing at all.)

Note: If you are trying to run the program you will have to make some .txt files and change the directories.

I am using a raspberry pi to do this so the fomating will not work. :(

Ill see if I can post the code later on my other computer...

Thanks

DragonMastur 23 Light Poster

I have done a lot of work on it and have a 1.5.8 version of it.

Unfortunitly I got mad at the computer and took it apart. So I still haave it on a drive but no machine. I am useing a raspberrie pi right now.

DragonMastur 23 Light Poster

I want to make a game that requires the arrow keys to be pressed. How do I detect if a key has been pressed?

DragonMastur 23 Light Poster

This is a PyEditor I made because I couldn't get a IDLE working on windows 95.

DragonMastur 23 Light Poster

Is it posible to have an optional veriable in a funtion?

Such as this:

>>>def Say(msg, (optional)):
>>>    print msg
>>>    print optional
>>>    
>>>Say('hi', 'option')
hi
option
>>>Say('not')
not

If so How?

DragonMastur 23 Light Poster

I have made a py editor which you can open save and run files. It is in python and is .py so you can just run as is.

import sys

if sys.hexversion >= 0x030000F0:    #First find which version and imports to import
    runningPython3 = True
else:
    runningPython3 = False
if runningPython3:
    import tkinter.filedialog as tk_FileDialog
    from tkinter import*
    from io import Stringl0         #This is not needed just make sure you import the correct libraries for your version
else:
    from tkinter import*
    import tkFileDialog as tk_FileDialog
    from Stringl0 import Stringl0

recents = []

class PyEditor:
    def doNew(self):
        self.text.delete(0.0,END)

    def doUndo(self):
        self.text.edit_undo()

    def doSaveAs(self):
        file = tk_FileDialog.asksavefile(mode='w')
        textoutput = self.text.get(0.0,END)
        file.write(textoutput.rstrip())
        file.write('\n')

    def doOpen(self):
        file = tk_FileDialog(mode='r')
        fileContets = file.read()
        recents.append(file)

        self.text.delete(0.0,END)
        self.text.insert(0.0,fileContents)

    def doRun(self):
        file = tk_FileDialog.askopenfile(mode='r')
        os.system('c:\\Python25\\python ' + file.name)

    def __init__(self):
        self.root = Tk()
        self.root.title('PyEditor1.0')
        self.root.minsize(with=800,height=535)

        menubar = Menu(self.root)

        filemenu = Menu(menubar,tearoff=0)
        filemenu.add_command(label='New File',command=self.doNew,accelerator='Ctrl+N)

        file.add_command(label='Open',command=self.doOpen,accelerator='CtrlO')

        filemenu.add_command(label='Save As',command=self.doSaveAs,accelerator='Ctrl+Shift+S')

        filemenu.add_command(label='Run Program',command=self.doRun,accelerator='Ctrl+R')

        editmenu = Menu(editmenu,tearoff=0)
        editmenu.add_command(label='Undo',command=self.doUndo,accelerator='Ctrl+Z')

        menubar.add_cascade(label='File',menu=filemenu)
        self.root.config(menu=menubar)
        editmenu.add_cascade(label='Edit',menu=editmenu)
        self.root.config(menu=editmenu)

        self.text = Text(self.root,undo=True)
        self.text.pack(expand=YES,fill=BOTH)

if __name__ == '__main__':
    app = PyEditor()
    app.root.mainloop()
DragonMastur 23 Light Poster

Expert

PyEditor1.0

from Tkinter import*
import tkDialog as tk_Dialog
from Stringl0 import Stringl0
import os
recents = []

class PyEditor:
    def doNew(self):
        self.text.delete(0.0,END)

    def doUndo(self):
        self.text.edit_undo()

    def doSaveAs(self):
        file = tk_FileDialog.asksavefile(mode='w')
        textoutput = self.text.get(0.0,END)
        file.write(textoutput.rstrip())
        file.write('\n')

    def doOpen(self):
        file = tk_FileDialog(mode='r')
        fileContets = file.read()
        recents.append(file)

        self.text.delete(0.0,END)
        self.text.insert(0.0,fileContents)

    def doRun(self):
        file = tk_FileDialog.askopenfile(mode='r')
        os.system('c:\\Python25\\python ' + file.name)

    def __init__(self):
        self.root = Tk()
        self.root.title('PyEditor1.0')
        self.root.minsize(with=800,height=535)

        menubar = Menu(self.root)

        filemenu = Menu(menubar,tearoff=0)
        filemenu.add_command(label='New File',command=self.doNew,accelerator='Ctrl+N)

        file.add_command(label='Open',command=self.doOpen,accelerator='CtrlO')

        filemenu.add_command(label='Save As',command=self.doSaveAs,accelerator='Ctrl+Shift+S')

        filemenu.add_command(label='Run Program',command=self.doRun,accelerator='Ctrl+R')

        editmenu = Menu(editmenu,tearoff=0)
        editmenu.add_command(label='Undo',command=self.doUndo,accelerator='Ctrl+Z')

        menubar.add_cascade(label='File',menu=filemenu)
        self.root.config(menu=menubar)
        editmenu.add_cascade(label='Edit',menu=editmenu)
        self.root.config(menu=editmenu)

        self.text = Text(self.root,undo=True)
        self.text.pack(expand=YES,fill=BOTH)

if __name__ == '__main__':
    app = PyEditor()
    app.root.mainloop()
DragonMastur 23 Light Poster

Anybody have ideas for some basic python programs???

DragonMastur 23 Light Poster

Make sure to import on this one!

from msvcrt import getch

keypress = 0
stopDown = 0

def keys(TargetKey):
    while keypress = 0:
        key = getch()
        if key == TagetKey:
            stopDown = 1
            keypress = 1

keys(delete)
if stopDown == 1:
    pass
    #code to stop the download
DragonMastur 23 Light Poster

I'am using different imports and python 3

import tkinter.filedialog as tk_FileDialog
from tkinter import*

fileCount = 0

for x in range(0,10)    #read as many as you want
    f = tk_FileDialog.askopenfile(mode='r')     #Or what file your trying to open
    fileContents = f.readlines(1)   #Or what lines you want to read
    if fileContents == 'H':
        fileCount += 0.5
    elif fileContents == 'h':
        fileCount += 0.5
    else:
        fileCount += 1

print "File count was", fileCount
DragonMastur 23 Light Poster

I made a PyEditor so here are a few of the lines from it:

import sys

if sys.hexversion >= 0x030000F0:    #First find which version and imports to import
    runningPython3 = True
else:
    runningPython3 = False
if runningPython3:
    import tkinter.filedialog as tk_FileDialog
    from tkinter import*
    from io import Stringl0         #This is not needed just make sure you import the correct libraries for your version
else:
    from tkinter import*
    import tkFileDialog as tk_FileDialog
    from Stringl0 import Stringl0


class files:   
    def Open(self): #Now open the file
        f = tk_FileDialog.askopenfile(mode='r')
        self.fileContents = f.read()
        self.fileName = f.name  #So it can be accessed where ever
        f.close()

    def Write(self, lines):
        f = open(self.fileName, 'w')
        f.writelines(lines)
        f.close()


if __name__ == '__main__':
    F = files()
    F.Open()
    line = raw_input()
    F.Write(line)