Python Forum
Trying to strings of pos to int tuples
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Trying to strings of pos to int tuples
#1
I'm working on a multiplayer game and was watching a tutorial. For one of the functions I need to read info. I'm getting an error when trying to split the info, for when it sends info of a pos.

Here's the function - the if is to decide what type of info I'm sending
1
2
3
4
5
6
def read_info(str):
    if str != dict:
        str = string.split(",")
        return int(str[0]), int(str[1])
    else:
        return str
Error:
Traceback (most recent call last): File "C:\Users\Chadd\Desktop\Big Game\Client.py", line 187, in <module> SignIn() File "C:\Users\Chadd\Desktop\Big Game\Client.py", line 80, in SignIn username = read_info(n.getInfo) File "C:\Users\Chadd\Desktop\Big Game\Client.py", line 68, in read_info string = string.split(",") AttributeError: 'function' object has no attribute 'split'
For if you need it, I have 3 scripts

Client.py - What the function above was copied from
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
import pygame
import random
import time
from Network import Network
 
pygame.init()
#GameData
signInList = {'Sheepposu' : 'rachl032078', 'gg' : 'rachl1979'}
 
#Variables
 
#Colors
black = (0,0,0)
white = (255,255,255)
red = (255,0,0)
darker_red = (200,0,0)
green = (0,255,0)
blue = (0,0,255)
CustomColor1 = (48,150,140)
CustomColor2 = (36,112.5,105)
Unique_Color = (190,140,210)
ColorList = [black, red, green, blue]
Confirm = True
 
#Game Config
display_width = 1000
display_height = 800
pd = pygame.display
gD = pygame.display.set_mode((display_width,display_height))
fps = 60
pd.set_caption('Game')
clock = pygame.time.Clock()
gD.fill(blue)
clock.tick(15)
 
#functions/Classes
class Player():
    def __init__(self, x, y, width, height, color):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.rect = (x, y, width, height)
        self.color = color
 
    def draw():
        pygame.draw.rect(win, self.color, (self.rect))
 
    def move():
        keyed = pygame.key.get_pressed()
 
        if keyed[pygame.K.LEFT]:
            self.x -= 5
        if keyed[pygame.K.RIGHT]:
            self.x += 5
        if keyed[pygame.K.UP]:
            self.y -= 5
        if keyed[pygame.K.DOWN]:
            self.y += 5
 
        self.update()
 
    def update():
        self.rect = (self.x, self.y, self.width, self.height)
 
def read_info(string):
    if string != dict:
        string = string.split(",")
        return int(string[0]), int(string[1])
    else:
        return str
 
def make_pos(tup):
    return str(tup[0]) + "," + str(tup[1])
 
def SignIn():
    global signInList
    n = Network()
    user = n.getInfo()
    username = read_info(n.getInfo)
 
    if username == 'new':
        newUsername = input('Type your Username: ')
        newPassword = input('Type your Password: ')
        signInList = {'Sheepposu' : 'rachl032078',
                      newUsername : newPassword}
        n.send((newUsername, newPassword))
        Confirm_Screen(username)
         
    else:
        if username in signInList:
            password = input('Please type your password: ')
            if password == signInList[username]:
               Confirm_Screen(username)
            else:
                print('Invalid Password')
                SignIn()
        else:
            print('Invalid Username')
            SignIn()
 
def Button(Butx, Buty, Butx2, Buty2, Butcolor, ShadowColor, text, textsize, textcolor, textFont, command=None, command2=None):
    mouse = pygame.mouse.get_pos()
    click = pygame.mouse.get_pressed()
    smallText = pygame.font.SysFont(textFont, textsize)
    textSurf, textRect = text_objects(text, smallText)
    textRect.center = ((Butx + (Butx2/2)), Buty + (Buty2/2))
    pygame.draw.rect(gD, Butcolor, (Butx, Buty, Butx2, Buty2))
    gD.blit(textSurf, textRect)
    if Butx + Butx2 > mouse[0] > Butx and Buty + Buty2 > mouse[1] > Buty:
        pygame.draw.rect(gD, ShadowColor, (Butx, Buty, Butx2, Buty2))
        gD.blit(textSurf, textRect)
        if click[0] == 1:
            if command != None:
                command()
            if command2 != None:
                command2()
    else:
        pygame.draw.rect(gD, Butcolor, (Butx, Buty, Butx2, Buty2))
        gD.blit(textSurf, textRect)
 
def windowRedraw(win, player=None):
    pygame.display.update()
    if player != None:
        player.draw(win)
        player.update()
 
def message_display(text, size, centerX, centerY):
    font = pygame.font.SysFont('arial', size)
    textSurf, TextRect = text_objects(text, font)
    TextRect.center = ((centerX),(centerY))
    gD.blit(textSurf, TextRect)
 
def text_objects(text, font):
    textSurface = font.render(text, True, Unique_Color)
    return textSurface, textSurface.get_rect()
 
def Confirm_Screen(username):
    global Confirm
    clock.tick(60)
    while Confirm:
         
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()
        gD.fill(blue)
        message_display('You\'re %s, correct?' %username, round(display_width/17), round(display_width/2), display_height * .25)
        Button(round(display_width * .3), round(display_height * .7), round(display_width * .4), round(display_height * .2), CustomColor1, CustomColor2, 'Confirm!', round(display_width/20), blue, 'arial', Game_Func)
        Button(round(display_width * .75), round(display_height * .8), round(display_width * .2), round(display_height * .1), red, darker_red, "No!", round(display_width/50), blue, 'arial', SignIn)
 
        windowRedraw()
        clock.tick(15)
 
def Game_Func():
    global Confirm
    global fps
    Confirm = False
    windowRedraw()
    keyed = pygame.key.get_pressed()
    startPos = read_info(n.getPos())
    p = Player(startPos[0], startPos[1], 100, 100, (0, 0, 200))
    p2 = Player(0, 0, 100, 100, (0, 200, 0))
    while not Confirm:
        clock.tick(fps)
 
        p2Pos = read_info(n.send(make_pos((p.x, p.y))))
        p2.x = p2Pos[0]
        p2.y = p2Pos[1]
        p2.update()
 
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()
         
        p.move()
        redrawWindow(gD, p)
        redrawWindow(gD, p2)
    End_Game()
 
def End_Game():
    print(signInList)
 
message_display('Please fill in info on the console', round(display_width/20), round(display_width/2), round(display_height/2))
windowRedraw(gD)
time.sleep(2)
SignIn()
server.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import socket
from _thread import *
import sys
 
server = '192.168.1.96'
port = 5555
 
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 
try:
    s.bind((server, port))
except socket.error as e:
    str(e)
 
 
s.listen()
print('Waiting for connection, Server Started')
 
def read_info(str):
    if str != dict:
        str = str.split(",")
        return int(str[0]), int(str[1])
    else:
        return str
 
def make_pos(tup):
    return str(tup[0]) + "," + str(tup[1])
 
pos = [(0,0), (100,100)]
 
def threaded_client(conn, player):
    global pos
    conn.send(str.encode(make_pos(pos[player])))
    reply = ''
    while True:
        try:
            data = read_info(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()
 
currentPlayer = 0
while True:
    conn, addr = s.accept()
    print('Connected to: ', addr)
     
    start_new_thread(threaded_client, (conn, currentPlayer))
    print(currentPlayer)
    currentPlayer += 1
Network.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import socket
 
class Network():
    def __init__(self):
        self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.server = '192.168.1.96'
        self.port = 5555
        self.addr = (self.server, self.port)
        self.info = self.connect()
 
    def getPos(self):
        return self.info
 
    def getInfo(self):
        if type(self.info) == dict:
            return self.info
        else:
            self.getPos()
 
    def connect(self):
        try:
            self.client.connect(self.addr)
            return self.client.recv(2048).decode()
        except:
            pass
 
    def send(self, data):
        try:
            self.client.send(str.encode(data))
            return self.client.recv(2048).decode()
         
        except socket.error as e:
            print(e)
 
n = Network()
server.py output -
Output:
Waiting for connection, Server Started Connected to: ('192.168.1.96', 55912) 0 Connected to: ('192.168.1.96', 55913) 1
it reprints with 1 when I get the error from Client.py

I probably have a few more problems that aren't yet fixed.
Reply
#2
I think you need n.getInfo() (with parentheses) on line 80 of Client.py. Without the parentheses, you are passing the method and not the result of the method.

Two other tips: do not use str for a parameter/variable name (it's a built-in function that you lose access to when you do that), and you should try to replace the global variables with parameters, return values, and assignments. Or better yet classes. When using a framework like pygame, classes are a big help.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
Thx, I'll be sure to do that when I have time.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020