import socket
from inspect import Traceback
import pygame
import random
import math
from lib_2048 import *
from socket import *
import json
"""계 획:
소켓을 활용하여 대기실 + 연동돼는 플레이 만들기.
대기실:
미루기.
연동플:
데이터(숫자 배열 1개와 공격 배열)를 받아 적용시키기..
temp
data = cls.recv(1024)
print(data.decode('utf-8'))
"""
# pygame setup
pygame.init()
screen_size = (1720, 1000)
screen = pygame.display.set_mode(screen_size)
clock = pygame.time.Clock()
running = True
curr_state = ''
state = 'lobby'
currpl = 1
box = pygame.Rect(0, 0, 600, 600)
box.center = (1720 / 4, 1000 / 2)
you = [[0 for i in range(4)] for i in range(4)]
other = [[0 for i in range(4)] for i in range(4)]
sp = [2, 2, 2, 2, 2, 2, 2, 2, 2, 4]
myatt = []
normalFont = pygame.font.SysFont(None, 50)
box_color = ["#CCCC77", "#DDDD88", "#EEEE99", "#FFFFAA", "#FFFFBB", "#FFFFCC", "#FFFFDD", "#FFFFEE", "#FFFFFF",
"#777777", "#666666", "#555555", "#444444", "#333333", "#222222", "#111111", "#000000", "#FFEEFF",
"#FFFFFF"]
text_color = ["#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000",
"#FFFFFF", "#FFFFFF", "#FFFFFF", "#FFFFFF", "#FFFFFF", "#FFFFFF", "#FFFFFF", "#FFFFFF", "#FF55FF",
"#999999"]
key_hold = 0
# socket
yclisoc_copy = socket(AF_INET,SOCK_DGRAM)
yclisoc = yclisoc_copy
att = None
data = None
HOST = '127.0.0.1'
con_ip = 'localhost'
con_port = ''
host_port = ''
PORT = 15785
user_name = ''
cliconaddr = None
hostaddr = None
# Host only
names = []
cnn = []
finalgap = []
connecting = False
max_pl = ''
errorMsg = ''
client_freeze = False
attackQueue = []
otherCells = [[] for i in range(99)]
def events(event):
global running
if event.type == pygame.QUIT:
running = False
def gamestart():
for i in range(2):
randomSpawn(you)
def drawtext(font,size,text,color,center):
main_text = pygame.font.SysFont(font, size).render(text, True, color)
mtc = main_text.get_rect()
mtc.center = center
screen.blit(main_text, mtc)
def drawrect(color,x,y,sizex,sizey,outlineEnable,out_color,Outwidth,brr):
box = pygame.draw.rect(screen, color,(x - sizex / 2, y - sizey / 2, sizex, sizey), 0,brr)
if outlineEnable:
out = pygame.draw.rect(screen, out_color, (x - sizex / 2, y - sizey / 2, sizex, sizey), Outwidth, brr)
return box
def drawOther(ve,pos,Size):
drawrect("#FFFFAA",pos[0],pos[1],int(600*Size),int(600*Size),True,"#000000",1,int(10*Size))
for i in range(4):
for j in range(4):
center = (int((pos[0]-(300-10-138/2)*Size)+((10+138)*Size) * j),
int((pos[1]-(300-10-138/2)*Size)+((10+138)*Size) * i))
rects = int(140 * Size)
if ve[i][j] == 0:
drawrect("#EEEEAA", center[0], center[1],rects, rects, True, "#000000", 1,
int(10 * Size))
drawtext(None, int(50 * Size), "0","#000000", center)
else:
if ve[i][j] > 262144:
drawrect(box_color[18],center[0],center[1],rects,rects,True,"#000000",1,int(10*Size))
else:
drawrect(box_color[int(math.log2(ve[i][j]) - 1)],center[0],center[1],rects,rects,True,"#000000",1,int(10*Size))
if ve[i][j] > 262144:
drawtext(None,int(50*Size),str(ve[i][j]),text_color[18],center)
elif ve[i][j] == 262144:
drawtext(None,int(50*Size),"MAX",text_color[int(math.log2(ve[i][j]) - 1)],center)
else:
drawtext(None,int(50*Size),str(ve[i][j]),text_color[int(math.log2(ve[i][j]) - 1)],center)
"""
state
lobby
connecting_ip/port
ingame
gameStarting
gameEnded
host_port
waiting_room
"""
while running:
# poll for events
# pygame.QUIT event means the user clicked X to close your window
for event in pygame.event.get():
events(event)
if event.type == pygame.KEYDOWN:
if state == 'connecting_ip':
if event.key == pygame.K_ESCAPE:
state = 'lobby'
con_ip = ''
elif event.key == pygame.K_BACKSPACE:
if len(con_ip) > 0:
con_ip = con_ip[:-1]
elif event.key == pygame.K_RETURN:
state = 'connecting_port'
client_freeze = True
elif len(con_ip) < 50:
con_ip += event.unicode
elif state == 'connecting_port':
if not client_freeze:
if event.key == pygame.K_ESCAPE:
state = 'connecting_ip'
con_port = ''
elif event.key == pygame.K_BACKSPACE:
if len(con_port) > 0:
con_port = con_port[:-1]
elif event.key == pygame.K_RETURN and len(con_port) > 0:
state = 'connecting_name'
elif len(con_port) < 5:
con_port += event.unicode
if not con_port.isdigit():
con_port = con_port[:-1]
else:
client_freeze = False
elif state == 'connecting_name':
if event.key == pygame.K_ESCAPE:
state = 'connecting_port'
user_name = ''
elif event.key == pygame.K_BACKSPACE:
if len(user_name) > 0:
user_name = user_name[:-1]
elif event.key == pygame.K_RETURN and len(user_name) > 0:
try:
state = 'waiting_room'
curr_state = 'cilent'
gap = {
"dis_name": user_name
}
cliconaddr = (con_ip,int(con_port))
yclisoc.sendto(json.dumps(gap).encode(),cliconaddr)
except Exception as e:
yclisoc = yclisoc_copy
state = 'lobby'
print(e)
errorMsg = f"Wrong Ip input {e}"
elif len(user_name) < 50:
user_name += event.unicode
if state == 'host_port':
if event.key == pygame.K_ESCAPE:
state = 'lobby'
host_port = ''
elif event.key == pygame.K_BACKSPACE:
if len(host_port) > 0:
host_port = host_port[:-1]
elif event.key == pygame.K_RETURN:
if len(host_port) > 0:
state = 'host_name'
elif len(host_port) < 5:
host_port += event.unicode
if not host_port.isdigit():
host_port = host_port[:-1]
elif state == 'host_name':
if event.key == pygame.K_ESCAPE:
state = 'host_port'
user_name = ''
elif event.key == pygame.K_BACKSPACE:
if len(user_name) > 0:
user_name = user_name[:-1]
elif event.key == pygame.K_RETURN and len(user_name) > 0:
names.append(user_name)
state = 'host_maxpl'
elif len(user_name) < 50:
user_name += event.unicode
elif state == 'host_maxpl':
if event.key == pygame.K_ESCAPE:
state = 'host_port'
max_pl = 0
elif event.key == pygame.K_BACKSPACE:
if len(max_pl) > 0:
max_pl = max_pl[:-1]
elif event.key == pygame.K_RETURN and len(max_pl) and int(max_pl) > 1:
yclisoc.bind(('', int(host_port)))
curr_state = 'host'
state = 'waiting_room'
yclisoc.setblocking(False)
elif len(max_pl) < 2:
max_pl += event.unicode
if not max_pl.isdigit():
max_pl = max_pl[:-1]
if state == 'ingame' and curr_state == 'host':
w1 = banghyang_host(event.key, you, attackQueue)
if not w1:
randomSpawn(you)
elif state == 'ingame' and curr_state == 'client':
w1 = banghyang(event.key, you,yclisoc,hostaddr)
if not w1:
randomSpawn(you)
screen.fill("#DDDD77")
if state == 'ingame':
if curr_state == 'host':
try:
print(attackQueue)
att , conn= yclisoc.recvfrom(4096)
data = json.loads(att.decode())
if data["cells"] is not None:
otherCells[0] = you
otherCells[cnn.index(conn)+1] = data["cells"]
gap = {
"cells":otherCells
}
for connected in cnn:
yclisoc.sendto(json.dumps(gap).encode(),connected)
if data["attack"] is not None:
attackQueue.append(int(data["attack"]))
if len(attackQueue) > 0:
victim = random.randrange(0,currpl)
if victim == 0:
randomAttack(you,data["attack"])
else:
gap = {
"attack": attackQueue[0]
}
yclisoc.sendto(json.dumps(gap).encode(),cnn[victim-1])
except Exception as e:
#print(e)
pass
if currpl == 2:
drawOther(you, (1720 / 4, 1000 / 2), 1)
drawOther()
#elif currpl > 2:
v = Lose(you)
if not v:
print('L0S3')
elif curr_state == 'client':
try:
att, hostadd = yclisoc.recvfrom(4096)
data = json.loads(att.decode())
if not data["attack"] is None:
randomAttack(you,int(data["attack"]))
except Exception as e:
print(e)
pass
if currpl == 2:
drawOther(you,(1720/4,1000/2),1)
else:
if state == 'game_start':
gamestart()
gap = {
"state":"game_starting",
"plstate": [currpl, max_pl],
"names": names,
}
for cls in cnn:
yclisoc.sendto(json.dumps(gap).encode(),cls)
state = 'ingame'
if state == 'lobby':
drawtext(None,55,errorMsg,(0,0,0),(1720/2,800))
drawtext("britannic",75,"tmc 2048",(0,0,0),(1720/2,100))
#connect
cn_box = drawrect((255,255,255),1720/2,1000/2-100,600,75,True,(0,0,0),4,10)
drawtext(None,45,"connect",(0,0,0),(1720/2,1000/2-100))
if cn_box.collidepoint(pygame.mouse.get_pos()):
if pygame.mouse.get_pressed()[0] == 1:
errorMsg = ''
state = 'connecting_ip'
#Host
hs_box = drawrect((255, 255, 255), 1720 / 2, 1000 / 2 + 25, 600, 75, True, (0, 0, 0), 4,10)
drawtext(None, 45, "Host", (0, 0, 0), (1720 / 2, 1000 / 2 + 25))
if hs_box.collidepoint(pygame.mouse.get_pos()):
if pygame.mouse.get_pressed()[0] == 1:
errorMsg = ''
state = 'host_port'
if state == 'waiting_room' and curr_state == 'host':
currpl = len(cnn) + 1
try:
att , conn= yclisoc.recvfrom(4096)
data = json.loads(att.decode())
if cnn.count(conn) < 1 and len(cnn) < int(max_pl):
cnn.append(conn)
names.append(data["dis_name"])
except Exception as e:
print(e)
pass
drawrect("#CCCC66",1720/2,1000/2,700,600,True,"#AAAA55",3,0)
drawrect("#BBBB55", 1720 / 2, 1000 / 2-260, 700, 90, True, "#AAAA55", 3, 0)
Start_button = drawrect("#BBBB55", 1720 / 2 + 460, 1000 / 2-150, 225, 75, True, "#AAAA55", 3, 0)
drawtext(None,45,"Force Start","#000000",(1720/2+460,1000/2-150))
if Start_button.collidepoint(pygame.mouse.get_pos()):
if pygame.mouse.get_pressed()[0] == 1:
state = "game_start"
gap = {
"plstate": [currpl, max_pl],
"names": names,
"state": "waiting",
}
for conncl in cnn:
yclisoc.sendto(json.dumps(gap).encode(), conncl)
for i in range(len(names)):
drawtext(None,int(55 - 1.4 * len(names[i])/2),names[i],(0,0,0),(1720/2-250 + 250 * int(i/10) ,1000/2-165 + 45*(i%10)))
drawtext(None,45,"players","#000000",(1720/2-250,1000/2-260))
drawtext(None, 45, "%d/%d" % (currpl, int(max_pl)), "#000000", (1720 / 2+250, 1000 / 2 - 260))
elif curr_state == 'cilent' and state == 'waiting_room':
drawrect("#CCCC66", 1720 / 2, 1000 / 2, 700, 600, True, "#AAAA55", 3, 0)
drawrect("#BBBB55", 1720 / 2, 1000 / 2 - 260, 700, 90, True, "#AAAA55", 3, 0)
drawtext(None,45,"players","#000000",(1720/2-250,1000/2-260))
try:
att, hostadd = yclisoc.recvfrom(4096)
data = json.loads(att.decode())
hostaddr = hostadd
currpl = data["plstate"][0]
except Exception as e:
if e == ConnectionResetError:
state = 'lobby'
yclisoc = yclisoc_copy
print(e)
pass
if data["state"] == "game_starting":
gamestart()
state = "ingame"
#yclisoc.sendto(json.dumps(gap).encode(),hostaddr)
for i in range(len(data["names"])):
drawtext(None, int(55 - 1.4 * len(data["names"][i]) / 2), data["names"][i], (0, 0, 0),
(1720 / 2 - 250 + 250 * int(i / 10), 1000 / 2 - 165 + 45 * (i % 10)))
if not data["plstate"] is None:
drawtext(None, 45, "%d/%d" % (data["plstate"][0], int(data["plstate"][1])), "#000000", (1720 / 2 + 250, 1000 / 2 - 260))
if state == 'connecting_ip':
text_input_ip = drawrect((255,255,255),1720/ 2,1000/2 - 100,800,75,True,(0,0,0),10,0)
drawtext(None,55,"Enter Host Ip",(0,0,0),(1720/2,1000/2))
drawtext(None,45,con_ip,(0,0,0),(1720/2,1000/2-100))
elif state == 'connecting_port':
text_input_port = drawrect((255, 255, 255), 1720 / 2, 1000 / 2 - 100, 800, 75, True, (0, 0, 0), 10, 0)
drawtext(None, 55, "Enter Host port", (0, 0, 0), (1720 / 2, 1000 / 2))
drawtext(None, 45, con_port, (0, 0, 0), (1720 / 2, 1000 / 2 - 100))
elif state == 'connecting_name':
text_input_port = drawrect((255, 255, 255), 1720 / 2, 1000 / 2 - 100, 800, 75, True, (0, 0, 0), 10, 0)
drawtext(None, 55, "Enter your display name", (0, 0, 0), (1720 / 2, 1000 / 2))
drawtext('굴림', 45, user_name, (0, 0, 0), (1720 / 2, 1000 / 2 - 100))
if state == 'host_port':
text_input_host = drawrect((255, 255, 255), 1720 / 2, 1000 / 2 - 100, 800, 75, True, (0, 0, 0), 10, 0)
drawtext(None, 55, "Enter port", (0, 0, 0), (1720 / 2, 1000 / 2))
drawtext(None, 45, host_port, (0, 0, 0), (1720 / 2, 1000 / 2 - 100))
elif state == 'host_name':
text_input_host = drawrect((255, 255, 255), 1720 / 2, 1000 / 2 - 100, 800, 75, True, (0, 0, 0), 10, 0)
drawtext(None, 55, "display name", (0, 0, 0), (1720 / 2, 1000 / 2))
drawtext(None, 45, user_name, (0, 0, 0), (1720 / 2, 1000 / 2 - 100))
elif state == 'host_maxpl':
text_input_host = drawrect((255, 255, 255), 1720 / 2, 1000 / 2 - 100, 800, 75, True, (0, 0, 0), 10, 0)
drawtext(None, 55, "max players", (0, 0, 0), (1720 / 2, 1000 / 2))
drawtext(None, 45, str(max_pl), (0, 0, 0), (1720 / 2, 1000 / 2 - 100))
#if state == 'gameEnded':
# cls.close()
pygame.display.flip()
clock.tick(60) # limits FPS to 60
pygame.quit()
import pygame
import random
import math
import socket
from socket import *
import json
HOST = '127.0.0.1'
PORT = 15785
"""계 획:
소켓을 활용하여 대기실 + 연동돼는 플레이 만들기.
대기실:
미루기.
연동플:
데이터(숫자 배열 1개와 공격 배열)를 받아 적용시키기..
temp
data = cls.recv(1024)
print(data.decode('utf-8'))
"""
# pygame setup
pygame.init()
box = pygame.Rect(0, 0, 600, 600)
box.center = (1720 / 4, 1000 / 2)
you = [[0 for i in range(4)] for i in range(4)]
other = [[0 for i in range(4)] for i in range(4)]
normalFont = pygame.font.SysFont(None, 50)
box_color = ["#CCCC77", "#DDDD88", "#EEEE99", "#FFFFAA", "#FFFFBB", "#FFFFCC", "#FFFFDD", "#FFFFEE", "#FFFFFF",
"#777777", "#666666", "#555555", "#444444", "#333333", "#222222", "#111111", "#000000", "#FFEEFF",
"#FFFFFF"]
text_color = ["#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000",
"#FFFFFF", "#FFFFFF", "#FFFFFF", "#FFFFFF", "#FFFFFF", "#FFFFFF", "#FFFFFF", "#FFFFFF", "#FF55FF",
"#999999"]
sp = [2,2,2,2,2,2,2,2,2,4]
def randomSpawn(who):
y = random.randrange(0, 4)
x = random.randrange(0, 4)
if who[y][x] == 0:
who[y][x] = random.choice(sp)
else:
return randomSpawn(who)
def full(who):
v = True
for i in range(4):
for j in range(4):
if who[i][j] == 0:
v = False
return v
def attm(who):
for i in range(4):
for j in range(4):
if who[i][j] < 0:
who[i][j] += 1
def Lose(who):
v = False
for i in range(4):
for j in range(4):
if j != 3 and (who[i][j] == who[i][j + 1] or who[i][j + 1] == 0):
v = True
if j != 0 and (who[i][j] == who[i][j - 1] or who[i][j - 1] == 0):
v = True
if i != 3 and (who[i][j] == who[i + 1][j] or who[i + 1][j] == 0):
v = True
if i != 0 and (who[i][j] == who[i - 1][j] or who[i - 1][j] == 0):
v = True
return v
def banghyang(bv, you, send,sendaddr):
x = 6
bl = True
for i in range(4):
for j in range(3):
if bv == pygame.K_UP or bv == pygame.K_w:
if you[j][i] != 0:
for k in range(3 - j):
if you[j + (k + 1)][i] == you[j][i]:
you[j][i] *= 2
you[j + (k + 1)][i] = 0
bl = False
if you[j][i] > 64:
gaps = {
"attack":sangsae(you, (math.log2(you[j][i]) + x))
}
send.sendto(json.dumps(gaps).encode(),sendaddr)
break
elif you[j + (k + 1)][i] != 0:
break
if bv == pygame.K_DOWN or bv == pygame.K_s:
if you[3 - j][i] != 0:
for k in range(j + 1, 4):
if you[3 - k][i] == you[3 - j][i]:
you[3 - j][i] *= 2
you[3 - k][i] = 0
bl = False
if you[3 - j][i] > 64:
gaps = {
"attack":sangsae(you,(math.log2(you[3 - j][i]) + x)).encode()
}
send.sendto(json.dumps(gaps).encode(), sendaddr)
break
elif you[3 - k][i] != 0:
break
if bv == pygame.K_LEFT or bv == pygame.K_a:
if you[i][j] != 0:
for k in range(3 - j):
if you[i][j + (k + 1)] == you[i][j]:
you[i][j] *= 2
you[i][j + (k + 1)] = 0
bl = False
if you[i][j] > 64:
gaps = {
"attack":sangsae(you,(math.log2(you[i][j])+x)).encode()
}
send.sendto(json.dumps(gaps).encode(), sendaddr)
break
elif you[i][j + (k + 1)] != 0:
break
if bv == pygame.K_RIGHT or bv == pygame.K_d:
if you[i][3 - j] != 0:
for k in range(j + 1, 4):
if you[i][3 - k] == you[i][3 - j]:
you[i][3 - j] *= 2
you[i][3 - k] = 0
bl = False
if you[i][3 - j] > 64:
gaps = {
"attack":sangsae(you,(math.log2(you[i][3 - j])+x)).encode()
}
send.sendto(json.dumps(gaps).encode(), sendaddr)
break
elif you[i][3 - k] != 0:
break
if not bl:
attm(you)
bl = sort(you,bv,bl)
return bl
def banghyang_host(bv, you, attqueue):
x = 6
bl = True
for i in range(4):
for j in range(3):
if bv == pygame.K_UP or bv == pygame.K_w:
if you[j][i] != 0:
for k in range(3 - j):
if you[j + (k + 1)][i] == you[j][i]:
you[j][i] *= 2
you[j + (k + 1)][i] = 0
bl = False
if you[j][i] > 64:
attqueue.append(sangsae(you, (math.log2(you[j][i]) + x)))
break
elif you[j + (k + 1)][i] != 0:
break
if bv == pygame.K_DOWN or bv == pygame.K_s:
if you[3 - j][i] != 0:
for k in range(j + 1, 4):
if you[3 - k][i] == you[3 - j][i]:
you[3 - j][i] *= 2
you[3 - k][i] = 0
bl = False
if you[3 - j][i] > 64:
attqueue.append(sangsae(you,(math.log2(you[3 - j][i]) + x)))
break
elif you[3 - k][i] != 0:
break
if bv == pygame.K_LEFT or bv == pygame.K_a:
if you[i][j] != 0:
for k in range(3 - j):
if you[i][j + (k + 1)] == you[i][j]:
you[i][j] *= 2
you[i][j + (k + 1)] = 0
bl = False
if you[i][j] > 64:
attqueue.append(sangsae(you,(math.log2(you[i][j])+x)))
break
elif you[i][j + (k + 1)] != 0:
break
if bv == pygame.K_RIGHT or bv == pygame.K_d:
if you[i][3 - j] != 0:
for k in range(j + 1, 4):
if you[i][3 - k] == you[i][3 - j]:
you[i][3 - j] *= 2
you[i][3 - k] = 0
bl = False
if you[i][3 - j] > 64:
attqueue.append(sangsae(you,(math.log2(you[i][3 - j])+x)))
break
elif you[i][3 - k] != 0:
break
if not bl:
attm(you)
bl = sort(you,bv,bl)
return bl
def randomAttack(victim, att):
y = random.randrange(0, 4)
x = random.randrange(0, 4)
if victim[y][x] == 0:
victim[y][x] = -att[0]
att.pop(0)
else:
return randomAttack(victim, att)
def sort(who,bv,bl):
for i in range(4):
for j in range(3):
if bv == pygame.K_UP or bv == pygame.K_w:
if who[j][i] == 0:
for k in range(j + 1, 4):
if who[k][i] != 0:
who[j][i] = who[k][i]
who[k][i] = 0
bl = False
break
if bv == pygame.K_DOWN or bv == pygame.K_s:
if who[3 - j][i] == 0:
for k in range(j + 1, 4):
if who[3 - k][i] != 0:
who[3 - j][i] = who[3 - k][i]
who[3 - k][i] = 0
bl = False
break
if bv == pygame.K_LEFT or bv == pygame.K_a:
if who[i][j] == 0:
for k in range(j + 1, 4):
if who[i][k] != 0:
who[i][j] = who[i][k]
who[i][k] = 0
bl = False
break
if bv == pygame.K_RIGHT or bv == pygame.K_d:
if who[i][3 - j] == 0:
for k in range(j + 1, 4):
if who[i][3 - k] != 0:
who[i][3 - j] = who[i][3 - k]
who[i][3 - k] = 0
bl = False
break
return bl
def sangsae(w,n):
for i in range(4):
for j in range(4):
if w[i][j] < 0 and n!=0:
if w[i][j] + n >= 0:
n += w[i][j]
else:
w[i][j] += n
return 0
return n
def Lose(who):
v = False
for i in range(4):
for j in range(4):
if j != 3 and (who[i][j] == who[i][j + 1] or who[i][j + 1] == 0):
v = True
if j != 0 and (who[i][j] == who[i][j - 1] or who[i][j - 1] == 0):
v = True
if i != 3 and (who[i][j] == who[i + 1][j] or who[i + 1][j] == 0):
v = True
if i != 0 and (who[i][j] == who[i - 1][j] or who[i - 1][j] == 0):
v = True
return v
def gamestart():
for i in range(2):
randomSpawn(you)