WildBamaBoy 19 Junior Poster

Hey don't worry about it. I've finally made it sort-of work! :cool:

WildBamaBoy 19 Junior Poster

Read your directions. The function 'first' should print "in function first()" and then it calls 'second'.

Your code right now calls second, and then first.

You also don't need the variable 'my_string' or the "any text here" because you don't use it. I only used that as an example.

WildBamaBoy 19 Junior Poster

No, you have not coded that yet.

All you need to do is check if their input is greater than or less than the number they're trying to guess.

Note: You've commented in your code where the guessing loop should go. Where is it? The code you have now will ask only three times because you call ask_number 3 times and then it will act as if their guess was correct. You don't need to do that, just put ONE call in a loop that continues until their response is equal to the number they're guessing.

WildBamaBoy 19 Junior Poster

Yes. Your function definition.

WildBamaBoy 19 Junior Poster

global scope lines are top-level lines outside the functions without indentation like line 6 in your code.

def first(my_string):
    print "In function", first('first()')

def second(my_string):
    return my_string
first("any text here") #call to function 'first' in global scope
WildBamaBoy 19 Junior Poster

It doesn't have any code to handle when the player goes off of the screen

WildBamaBoy 19 Junior Poster

And I give. :sad: Line 95 in Handlers.py is where I draw the background, then it moves whichever direction he's supposed to go(Up down left and right work now) and blits the current frame to the screen, then updates.

Maybe it's something simple I haven't set right, because it's slow again but not flickering or clearing the old sprites.

WildBamaBoy 19 Junior Poster

That means no value was returned. Look at your find_discount() function. You've set what discount should be on all occasions, but you only return on one occasion! You need to move it back so it returns after all the if and else statements.

Here's how it should be.

def find_discount(total):
    if total <120:     #Check for this
        discount = 0   #It's True! Skip the else: statement.

    else:              #Above is not true, execute this block of code
        if total <300: #You get the picture..
            discount = 0.03*total
        else:
            if total <500:
                discount = 0.05*total
            else:
                discount = 0.07*total

    #All checks are done, so return
    return discount

Also, line 39 needs to be: print "The total is " + str(discounted_total) This makes it a string. You must do this because your discounted total is a float, and you can't add letters and numbers.

WildBamaBoy 19 Junior Poster

Thank you, but I think I'll spend one more day with it before I give up and upload it.

WildBamaBoy 19 Junior Poster

Hmmm...nope. Still trying it though

WildBamaBoy 19 Junior Poster

To call a function you simply type its name and a pair of parenthesis. Between the parenthesis is where you'll supply any parameters the function takes.

Replace line 6 with: first("any text here") Consider redoing your code a little bit. It's a little confusing and it will not do what you want just yet.

WildBamaBoy 19 Junior Poster

C'mon, show a little effort. It's not hard, I promise.

This page might help.

WildBamaBoy 19 Junior Poster

You have the function inside your while loop. Functions must always be called so they will execute their code. To call it you need to type the name of the function and include any variables it needs within the parenthesis. Like so: ask_number("Type a number: ", 1, 100) In this case this will not work because Python begins the while() loop, which defines your function, before it reaches your function call. Also, placing the call before the while() loop will not work because your function is not defined yet.

You simply need to rearrange your code so the function is outside of your loop, and add the function call at the end.

import random

secretNum = random.randrange(100)+1
      
tries = 0

def ask_number(question, high, low):
    """Ask a yes or no question"""
    
    while tries < 5:
        try:
            response = None
            while response not in range(low, high):
                response = int(raw_input(question))
                return response              
                                                                       
        except ValueError:
            print('Please enter a number')

ask_number("Type a number: ", 1, 100)
WildBamaBoy 19 Junior Poster

I've made my code much more readable...

class Player():
        def __init__(self):
            self.screen       = gfx.screen

            # Values with NONE are set later
            self.X            = 355        # Current X Coords
            self.Y            = 265        # Current Y Coords
            self.PrevX        = None       # Previous X Coords
            self.PrevY        = None       # Previous Y Coords
            self.Speed        = 13         # How many pixels to move
            self.CurrentFrame = 0          # Which image is being displayed
            self.Direction    = "North"    # Which direction they're facing
            self.Standing     = True       # Are they still or moving?
            self.Rect         = None       # Current rectangle
            self.PrevRect     = None       # Previous rectangle
            self.DirtyRects   = []         # Rectangles to be updated

            # Load sprites
            self.StandNorth = pygame.image.load("./Characters/Player/Standing/N.png").convert_alpha()

            self.WalkNorth  = [None] * 5
            for i in range (1, 5):
                self.WalkNorth[i] = pygame.image.load("./Characters/Player/Walking/N_" + str(i) + ".png").convert_alpha()

        def Move(self):
            # Set variables according to key pressed

            if keys.Is("up"):
                self.Direction      = "North"
                self.Standing       = False
                self.CurrentFrame  += 1

            elif keys.Is("down"):
                self.Direction      = "South"
                self.Standing       = False
                self.CurrentFrame  +=1

            elif keys.Is("left"):
                self.Direction      = "West"
                self.Standing       = False
                self.CurrentFrame  +=1

            elif keys.Is("right"):
                self.Direction      = "East"
                self.Standing       = False
                self.CurrentFrame  +=1

            else: self.Standing = True

            # Set frames back to beginning if too far
            if self.CurrentFrame > 4: self.CurrentFrame = 1

            # Moving logic
            if self.Direction == "North" and keys.Is("up"):
                # Blit the current frame to the screen
                self.screen.blit(self.WalkNorth[self.CurrentFrame],(self.X,self.Y))

                # Set Prev values
                self.PrevX = self.X
                self.PrevY = self.Y

                self.Y -= self.Speed # Move it

                # Make dirty rectangles
                self.PrevRect = [self.PrevX, self.PrevY, 48, 48]
                self.Rect     = [self.X, self.Y, 48, 48]

                # …
WildBamaBoy 19 Junior Poster

I drew the rectangles on screen to see if they covered the areas they're supposed to. My background is a 1024x768 PNG image, not a rectangle drawn on the screen.

WildBamaBoy 19 Junior Poster

So close, I know it. I've got the rectangles to draw over the correct areas to be updated to test it. It works, but when I take out drawing the rectangles he still leaves a trail behind him.

if self.Dir == "North" and keys.Is("up"):
                self.Rect   = self.WalkNorth[self.CurrentFrame].get_rect()
                self.PrevX  = self.X
                self.PrevY  = self.Y
                
                self.screen.blit(self.WalkNorth[self.CurrentFrame],(self.X,self.Y))
                self.Y     -= self.Speed

                dirty = []

                dirty.append(pygame.rect.Rect([self.X, self.Y, self.Rect[2], self.Rect[3]])) #Current Location
                dirty.append(pygame.rect.Rect([self.PrevX, self.PrevY, self.Rect[2], self.Rect[3]])) #Previous Location

                pygame.display.update(dirty)
                
            else:
                self.Rect = self.StandNorth.get_rect()
                self.screen.blit(self.StandNorth, (self.X, self.Y))

                dirty = pygame.rect.Rect([self.X, self.Y, self.Rect[2], self.Rect[3]])
                pygame.display.update(dirty)
                
            pygame.display.flip() 
            pygame.time.delay(50)
WildBamaBoy 19 Junior Poster

I don't believe I'm understanding it correctly...I've got it to where a green square is drawn where the sprite is. Now all I need to do is use pygame.display.update() on that rectangle right? It doesn't work...He leaves a trail of his previous selves. :|

Can you tell what is wrong? I'm still looking into it.

if self.Dir == "North" and keys.Is("up"):
                self.Rect   = self.WalkNorth[self.CurrentFrame].get_rect()
                self.screen.blit(self.WalkNorth[self.CurrentFrame],(self.X,self.Y))
                self.Y     -= self.Speed

                #print self.Rect
                dirty = pygame.rect.Rect([self.X, self.Y, self.Rect[2], self.Rect[3]])
                #print dirty
                pygame.draw.rect(self.screen, (0, 255, 0), dirty) #Comment out

                pygame.display.update(dirty) #Update only that area?? Doesn't work.
                pygame.display.flip()
                
            else:
                self.Rect = self.StandNorth.get_rect()
                self.screen.blit(self.StandNorth, (self.X, self.Y))

                dirty = pygame.rect.Rect([self.X, self.Y, self.Rect[2], self.Rect[3]]) #Comment out
                pygame.display.update(dirty)

                pygame.draw.rect(self.screen, (0, 255, 0), dirty)
            pygame.display.flip() 
            pygame.time.delay(50)
WildBamaBoy 19 Junior Poster

I guess it's just my old computer then, if it looked fine on yours. I'm looking through those now. Thank you for the links.

WildBamaBoy 19 Junior Poster

You're very welcome.

WildBamaBoy 19 Junior Poster

Your working code is above.

WildBamaBoy 19 Junior Poster

It actually is passed through, but every time you call the function to draw a circle, radius is set back to 10. :)

EDIT: Moved 'radius' to outside the while loop, so it will never be set back to 10. Also added radius as an argument to the circle function.

Your circle function

def circle(quickdraw, x, y, radius):
	if(radius < 400):
		circle = "circle" + ' ' + str(x) + ' ' + str(y) + ' ' + str(radius)
		quickdraw.stdin.write(circle)
		quickdraw.stdin.write("\n")

And WindowEvents

def WindowEvents(quickdraw):
    shape = raw_input("What shape would you like to draw, choices are: square, circle or triangle ")
    quickdraw.stdin.write("windowevents true\n")
    quickdraw.stdin.write("mouseclick true\n")
    event = quickdraw.stdout.readline()

    radius = 10 
    while 1:
            if ("Window" in event):
                    while (not isQuickdrawClosed(event)) :
                            print event
                            event = quickdraw.stdout.readline()
            if ("Mouse" in event):
                        event = quickdraw.stdout.readline()
                        x, y = coordinates(quickdraw, event)

                        if shape == "square":
                            square(quickdraw, x, y)
                        if shape == "circle":
                            circle(quickdraw, x, y, radius) #added radius
                            radius = radius + 10
                        print event

Unfortunately the other circle in the top left also gets bigger...

WildBamaBoy 19 Junior Poster

Thought it was for Mac, lol.

Yup you have a whole lot of while() loops that will never end. I changed your WindowEvents and coordinates functions again.

def WindowEvents(quickdraw):
	shape = raw_input("What shape would you like to draw, choices are: square, circle or triangle ")
	quickdraw.stdin.write("windowevents true\n")
	quickdraw.stdin.write("mouseclick true\n")
	event = quickdraw.stdout.readline()

	while 1: #Repeating these ifs over and over until one is true.
            if ("Window" in event):
                    while (not isQuickdrawClosed(event)) :
                            print event  
                            event = quickdraw.stdout.readline()
            if ("Mouse" in event):
                        event = quickdraw.stdout.readline()
                        x, y =coordinates(quickdraw, event)

                        if shape == "square": #while() not needed. will draw same square forever.
                            square(quickdraw, x, y)
                        if shape == "circle": #same as above. 
                            circle(quickdraw, x, y)
                        print event
			
                        #Now it will return to the top of the while 1 loop, allowing you to click and place another circle.

def coordinates(quickdraw, event):
	if ((len(event) > 0) and ("MouseReleased" in event)):
		first  = event.split(":")[0]
		xcoord = event.split(":")[1]
		x = xcoord[0:4]		
		x = x.strip()
		y = xcoord[5:8]
		y = y.strip()
		print x
		print y
		return x, y

	else: #Should probably change this
                return 0, 0

For whatever reason there is an error when you click the second time. So I added the else statement to put a circle at the very top left when this occurs.

WildBamaBoy 19 Junior Poster

I used someone else's code as an example to start my game and move my character around. I understood the majority of it but there's a couple of parts I don't get.

I want my character to move Up when the up arrow is pressed, but smoothly! My code right now will move him and switch the images to make it look like he's walking, but it blinks between every frame because I reload the background to clear the old character off of the screen. I can't figure out any other way to do it though.

I know my code design right now is horrible and confusing, I'm sorry. I would like someone else's opinion on how this whole project should be structured, if you would be so kind.

The zip file below is my entire project as of now. Not much. :P

WildBamaBoy 19 Junior Poster

The while() loop at line 50 doesn't seem to have any condition that stops it, other than when "isQuickdrawClosed" is True. So it'll keep going forever...and ever...and ever....:|

EDIT: I just noticed you're on Windows. I googled quickdraw and only Mac stuff came up. :P Maybe I can test it for you after all.

EDIT 2: Sure can. Can you give me your current code?

WildBamaBoy 19 Junior Poster

It didn't return anything (NoneType), so your if() statement turned out to be false. I don't know know quickdraw works and I can't test your code as I am on Windows. So you need to add another if(), elif(), or else() statement to do something when your initial if() statement is False.

When the if() statement is not executed, there is no "x" to return.

WildBamaBoy 19 Junior Poster

I believe this should do it.

You need to have a variable (x and y in this case) assigned to the coordinates function. The variable will equal whatever the function returns. It is not defined by just calling the function, as it doesn't have a variable to return a value to.

Change line 52 to:

x, y  = coordinates(quickdraw, event)

And change the returns in the coordinates function to:

return x, y
WildBamaBoy 19 Junior Poster

Can you post that error as well?

WildBamaBoy 19 Junior Poster

Can't test it but it looks like bad indentation. Line it up like this.

def coordinates(quickdraw, event):
	if ((len(event) > 0) and ("MousePressed" in event)):
		first  = event.split(":")[0]
		xcoord = event.split(":")[1]
		x = xcoord[0:4]		
		x = x.strip()
		y = xcoord[5:8]
		y = y.strip()
		print x
		print y
	        return x
	        return y
WildBamaBoy 19 Junior Poster

Simply replace the numbers with raw_input(). Add a string between the parenthesis to also print a prompt.

a = raw_input("A = ")
b = raw_input("B = ")
c = raw_input("C = ")

class fallObj(DirectObject):
    def __init__(self):
#rest of the code goes here
WildBamaBoy 19 Junior Poster
def round32(x): return (x+16) & ~31

This seems to work right. Could you please explain what the '&' and '~31' are used for?

WildBamaBoy 19 Junior Poster

D'oh! I didn't think about Mac. :P

WildBamaBoy 19 Junior Poster

Same as me...
Go to C:\Python26\Lib\site-packages\pygame and see if you can find the locals.py file.

WildBamaBoy 19 Junior Poster

What version of Python are you running? I can't think of any reason it would do that. It works fine for me.

WildBamaBoy 19 Junior Poster

I know this is probably overly simple but I am terrible with math.

This is a section from a game I'm attempting with PyGame. Instead of using pixels for coordinates I have my own render function that uses blocks(actually just cnverts block value to pixels), which are 32x32 pixels, so it's easier to make levels. At least I think it will be. :S

Like the title says, if I accidentally put in a pixel value that is not a multiple of 32, my code will raise a ValueError. Instead I want it to round the pixel value to the nearest multiple of 32 and just warn me that it is incorrect.

class graphics():
    def __init__(self):
        pass

    def render(self, sprites):
        for sprite, coord in sprites:
            surface.blit(sprite, (coord[0], coord[1]))
        pygame.display.update()

    def PTB(self, pixels): #Pixels to blocks
        if pixels == 1024: return 1024/32

        if pixels not in range(0, 1024, 32):
            raise ValueError("PTB: Pixels not a multiple of 32.")
            #instead of an error, round to nearest multiple
        else: return pixels / 32

    def BTP(self, blocks): #Blocks to pixels
        return blocks * 32

gfx = graphics()
WildBamaBoy 19 Junior Poster

No. Void states that the function will not return anything. Int says that it will return an integer. Main must return an integer.

You still have not declared the variable "i". Add "int i;"(no quotes) after you declare "var".

I still don't think you need the variable "var" or "var" at all. It can be replaced with just "i". Otherwise you get some pretty strange outputs like 2009147472. I doubt that's what you want.

WildBamaBoy 19 Junior Poster

Erm...what ARE the consequences of recursion? Why should I not do it?

WildBamaBoy 19 Junior Poster

Consequences of recursion? Just curious.

WildBamaBoy 19 Junior Poster

I'm a beginner with C++ but I'll attempt to help.

Line 3: Your main() function is void. The Main() function must always return an int. So change void to int.
Line 5: I don't believe you'll need this. Replace with a declaration of the variable "i"
Line 6: The variable "i" is never declared.
Line 8: You're trying to call "var" and providing the argument "i". Var is not a function and cannot be called. Replace var(i) with just i.

Finally at the end of the function add return 0;
This tells the operating system that everything went ok.

WildBamaBoy 19 Junior Poster

It says the error is in main on line 61. Might be a good idea to show us that line.

Also
string filename = Work.Title += ".txt"; should be
string filename = Work.Title + ".txt"; I believe. I doubt you want to change Work.Title

My bad, line 61 is line number 8 in the last bit of code I posted.
Good eye with the += thing. I in fact did not want Work.Title changed. That would've took me forever to figure out.

In your original post, you are calling main() recursively - it's a poor practice and also forbidden. You could instead devise a regular do/while loop, for example.

I'm just using calls to main() as placeholders for now but I was not aware of that.
I did however plan to return to the main function when the program has finished a whole operation so the user can choose what else they may want to do. I don't know if this would be common practice or not but would just defining a different function to deal with choices and recursively call it be...acceptable? It seems much less complicated than doing a while loop. :|

Just something like:

void choose()
{
    system("CLS");

    int choice;

    cout << "Assignment Manager"            << endl << endl;
    cout << "1: Add an assignment"          << endl;
    cout << "2: Browse saved assignments"   << endl;
    cout << "3: Delete an assignment"       << endl;
    cout << "4: Exit"                       << endl << endl; …
WildBamaBoy 19 Junior Poster

Wow. Excellent explanation! It seems to be working fine now thank you.
Now I have a problem with naming the file it saves data to. Right now I just want it to be saved to a text file whose name is whatever Work.Title is.

void WriteInfo(Assignment Work)
{
    string filename = Work.Title += ".txt";
    cout << filename << endl; //Test to see what output was. My case was "test.txt"

    ofstream file;

    file.open(filename); //Does not accept the string "test.txt"

    file << "Assignment from "  << Teacher(Work) << ", " << Work.Period << PeriodAbbrev(Work) << " Period." << endl << endl;
    file << "Title: "           << Work.Title    << endl;
    file << "Page : "           << Work.Page     << endl;
    file << "Date : "           << Work.Date     << endl;
    file << "\nInstructions : " << Work.Instruct << endl;

    file.close();
}

Why doesn't it accept the filename I give it? I get these two build errors which make no sense to me.

main.cpp|61|error: no matching function for call to 'std::basic_ofstream<char, std::char_traits<char> >::open(std::string&)'|

c:\mingw\bin\..\lib\gcc\mingw32\4.4.1\include\c++\fstream|696|note: candidates are: void std::basic_ofstream<_CharT, _Traits>::open(const char*, std::_Ios_Openmode) [with _CharT = char, _Traits = std::char_traits<char>]|
WildBamaBoy 19 Junior Poster

Just started learning C++ today. I'm writing a program to keep up with school assignments.

#include <iostream>
#include <stdlib.h>
#include <fstream>
#include <string>

struct Assignment
{
    string Period;
    string Title;
    string Page;
    string Date;
    string Instruct;
};

void NewAssignment()
{
    system("CLS");

    Assignment Work;
    cout << "New Assignment Entry" << endl;
    cout << "--------------------------" << endl << endl;

    cout << "Period: ";
    getline(cin, Work.Period);

    cout << "Title: ";
    getline(cin, Work.Title);

    cout << "Page Number: ";
    getline(cin, Work.Page);

    cout << "Date: ";
    getline(cin, Work.Date);

    cout << "Instructions: ";
    getline(cin, Work.Instruct);

    WriteInfo(Work); //Writes to a file
}

int main()
{
    system("CLS");

    int choice;

    cout << "Assignment Manager"            << endl << endl;
    cout << "1: Add an assignment"          << endl;
    cout << "2: Browse saved assignments"   << endl;
    cout << "3: Delete an assignment"       << endl;
    cout << "4: Exit"                       << endl << endl;

    cin  >> choice;

    if(choice == 1)
    {NewAssignment();}

    else if (choice == 2)
    {main();}

    else if (choice == 3)
    {main();}

    else if (choice == 4)
    {exit(0);}

    else{main();}

    return 0;
}

It screws up somewhere in the NewAssignment function. When it is called it gives me

New Assignment Entry
------------------------

Period: Title:

It completely skips over getting input for Work.Period. It works right when I use cin but then all of the others do the same, and I must use getline() so spaces will be recognized.

WildBamaBoy 19 Junior Poster

Instead of using If to handle errors you need to use the Try and Except statement.

Here is your code using those.

import getpass, smtplib

gname = raw_input("Username: ")
gpass = getpass.getpass("Password: ")

try: #Try to execute the code between try: and except:
    server = smtplib.SMTP('smtp.gmail.com:587')
    server.ehlo()
    server.starttls()
    server.ehlo()
    server.login(gname,gpass) #<-- SMTPAuthenicationError is raised here.
    #Now Python will look for an Except clause that handles that specific error, skipping over the rest of the Try clause. 
    #Which is printing that we are logged in, which we aren't!

    print "Logged in as ", gname  

except smtplib.SMTPAuthenticationError:        #Found it! 
    print "Error! Wrong password or username." #Huzzah!

From the Python documentation:
"The try statement works as follows.

* First, the try clause (the statement(s) between the try and except keywords) is executed.

* If no exception occurs, the except clause is skipped and execution of the try statement is finished.

* If an exception occurs during execution of the try clause, the rest of the clause is skipped. Then if its type matches the exception named after the except keyword, the except clause is executed, and then execution continues after the try statement."

Here's a link to the page all about errors and exceptions.
http://docs.python.org/tutorial/errors.html

I apologize if I make no sense at all. I'm a terrible teacher. :P

WildBamaBoy 19 Junior Poster

What exactly is the problem?

WildBamaBoy 19 Junior Poster

Whitespace is your friend!

Try adding this to your code.

correct = 0       #Letters correct is zero right now
for letter in hangword: #For every letter in the word they're trying to guess 
    if guess == letter: #If their guess is equal to that letter
        correct += 1    #Add one to 'correct'

if correct > 0:         #Their guess is in there at least once
    print guess,"is in the word",correct,"time(s)."
else:                   #'correct' is still zero. No letters match the guess
    print "Sorry, that letter is not in the word."
WildBamaBoy 19 Junior Poster

You don't have to open Notepad or use extra modules to write and save a text file. It's all built in.

# Opens a file called Hello.txt for writing.
f = open("Hello.txt", "w")
          #Filename  #Mode

# Write the text to the file.
f.write("Hello world!")

# Close the file
f.close()

This will work just fine unless you absolutely have to use Notepad for some reason.

WildBamaBoy 19 Junior Poster

Solved. Thank you

WildBamaBoy 19 Junior Poster

I'm coming from Python to Visual Basic and it's really playing with my head. This program is intended to scan a list of directories (only have one directory so far) and see if they contain any files. If they do, their directory is added to a list (DirtyFolders) and all files in those folders will be deleted when a button is pressed.

When I try to add the folder's directory to the list it throws an exception, "Object reference not set to an instance of an object."
That might as well be Japanese as I have no clue what it is trying to tell me.

Public Class Engine
    Shared DirtyFolders As List(Of String)

    Public Shared Sub Scan()
        Dim folder = "C:\Tester"

        If HasFiles(folder) Then
            Show("Files found in " & folder)
            DirtyFolders.Add(folder) '<-- Error happens here
        Else
            Show("No files in " & folder)
        End If
    End Sub
WildBamaBoy 19 Junior Poster

You're very welcome.

WildBamaBoy 19 Junior Poster

Perhaps not the best way to do it, but maybe something like this?

import random

tries = 0
keys='abcdefghijklmnopqrstuvwxyz '
key = random.choice(keys)

while key != "m":             #While key is not equal to 'm'
    tries += 1                #Add one to tries
    key = random.choice(keys) #Choose another key

if key == "m":                #Key 'm' was chosen
    print "Tried %s times until we got m." % tries
dustbunny000 commented: geat post +1
WildBamaBoy 19 Junior Poster

I had given up on this now I'm trying again.
Your code works fine, but could someone please explain the code to me?

def async(func):
    @wraps(func)  #Purpose of this? @ sign?
    def async_func(*args, **kwargs):
        func_handler = Thread(target=func, args=args, kwargs=kwargs)
        func_handler.start()
        return func_handler
    return async_func

@async #And this? What does the @ sign mean?
def listener():
    print "Initializing Listener..."
    Listener.Listen(server_ip, int(server_port))