-
Notifications
You must be signed in to change notification settings - Fork 1
/
sample.py
126 lines (96 loc) · 3.22 KB
/
sample.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
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
import pygame
from network import Network
class Player():
width = height = 50
def __init__(self, startx, starty, color=(255,0,0)):
self.x = startx
self.y = starty
self.velocity = 2
self.color = color
def draw(self, g):
pygame.draw.rect(g, self.color ,(self.x, self.y, self.width, self.height), 0)
def move(self, dirn):
"""
:param dirn: 0 - 3 (right, left, up, down)
:return: None
"""
if dirn == 0:
self.x += self.velocity
elif dirn == 1:
self.x -= self.velocity
elif dirn == 2:
self.y -= self.velocity
else:
self.y += self.velocity
class Game:
def __init__(self, w, h):
self.net = Network()
self.width = w
self.height = h
self.player = Player(50, 50)
self.player2 = Player(100,100)
self.canvas = Canvas(self.width, self.height, "Testing...")
def run(self):
clock = pygame.time.Clock()
run = True
while run:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.K_ESCAPE:
run = False
keys = pygame.key.get_pressed()
if keys[pygame.K_RIGHT]:
if self.player.x <= self.width - self.player.velocity:
self.player.move(0)
if keys[pygame.K_LEFT]:
if self.player.x >= self.player.velocity:
self.player.move(1)
if keys[pygame.K_UP]:
if self.player.y >= self.player.velocity:
self.player.move(2)
if keys[pygame.K_DOWN]:
if self.player.y <= self.height - self.player.velocity:
self.player.move(3)
# Send Network Stuff
self.player2.x, self.player2.y = self.parse_data(self.send_data())
# Update Canvas
self.canvas.draw_background()
self.player.draw(self.canvas.get_canvas())
self.player2.draw(self.canvas.get_canvas())
self.canvas.update()
pygame.quit()
def send_data(self):
"""
Send position to server
:return: None
"""
data = str(self.net.id) + ":" + str(self.player.x) + "," + str(self.player.y)
reply = self.net.send(data)
return reply
@staticmethod
def parse_data(data):
try:
d = data.split(":")[1].split(",")
return int(d[0]), int(d[1])
except:
return 0,0
class Canvas:
def __init__(self, w, h, name="None"):
self.width = w
self.height = h
self.screen = pygame.display.set_mode((w,h))
pygame.display.set_caption(name)
@staticmethod
def update():
pygame.display.update()
def draw_text(self, text, size, x, y):
pygame.font.init()
font = pygame.font.SysFont("comicsans", size)
render = font.render(text, 1, (0,0,0))
self.screen.draw(render, (x,y))
def get_canvas(self):
return self.screen
def draw_background(self):
self.screen.fill((255,255,255))