简体   繁体   中英

Error - ValueError: invalid literal for int() with base 10: ' '

I am making an online game using the sockets module and pygame in python.

def read_pos(str):
    if str is not None:
        string = str.split(",")
        return int(string[0]), int(string[1])
    else:
        pass

def make_pos(tup):
    return str(tup[0]) + "," + str(tup[1])


def redrawWindow(win,player, player2):
    win.fill((255,255,255))
    player.draw(win)
    player2.draw(win)
    pygame.display.update()


def main():
    run = True
    n = Network()
    startPos = read_pos(n.getPos())
    p = Player(startPos[0],startPos[1],100,100,(0,255,0))
    p2 = Player(0,0,100,100,(255,0,0))
    clock = pygame.time.Clock()

    while run:
        clock.tick(60)
        p2Pos = read_pos(n.send(make_pos((p.x, p.y))))
        p2.x = p2Pos[0]
        p2.y = p2Pos[1]
        p2.update()

This is the code I'm using in my client. in my server, the code is as follows

def convertPos(str):
    if str is not None:
        str = str.split(",")
        return int(str[0]), int(str[1])
    else:
        pass

def make_pos(tup):
    return str(tup[0]) + "," + str(tup[1])


pos = [(0,0),(100,100)]


def threaded_client(conn,player):
    conn.send(str.encode(make_pos(pos[player])))
    reply = " "
    while True:
        try:
            data = conn.recv(2048).decode()
            pos[player] = data

            if not data:
                print("Disconnected")
                break
            else:
                if player == 1:
                    reply = (pos[0])
                else:
                    reply = (pos[1])
                print("Received: ", data)
                print("Sending : ", reply)

            conn.sendall(str.encode(make_pos(reply)))
        except:
            break

    print("Lost connection")
    conn.close()

I am getting the error of ValueError: invalid literal for int() with base 10: ' '.

Can someone tell me why this is happening? The value of str in the function of convertPos() is coming in as a tuple which I am converting into a string and after that into an integer.

As you have converted it to string, the format you have is (x,y), you need to remove the brackets. You need to rewrite your convertPos function as:

def convertPos(str):
    if str is not None:
        str=str.strip("()")
        str = str.split(",")
        return int(str[0]), int(str[1])

EDIT You are not using the else part, so you can remove it.

And as @Azat Ibrakov says, you should not convert the tuple to an string, but if you need to do it, you can use ast.literal_eval like this:

import ast
def convertPos(str):
    return ast.literal_eval(str)

or use it directly in place of the convertPos function.

Obviously - as others have pointed out, the returned error is because you're trying to convert an empty string (or spaces) to an integer.

But the real issue is that the incoming co-ordinate is malformed. The code is not catching this error. You can write lots of code to determine what the error is, and report an accurate error. Or just plough-on as if everything is fine, but also catch any exception with a reasonable error message.

def convertPos(str):
    coord = None
    try:
        parts = str.split( ',', 2 )
        x = int( parts[0] )
        y = int( parts[1] )
        coord = ( x, y )
    except:
        raise ValueError( 'Malformed co-ordinate string [' + str.strip() + ']' )
    return coord

I suspect the socket code is not buffering a full packet, and maybe what's being processed is something like 122, , whereas the socket buffering needs to keep reading until a full co-ordinate has arrived.

So you could space-pad your co-ordinates to say a block of 11 characters - that way you know you must have received 11 characters to have a valid co-ordinate string. Alternatively use and end-of-coord marker, like a | , and then the socket code keeps buffing the input co-ordinate until that | arrives.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM