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 = socket(AF_INET,SOCK_STREAM)
HOST = '127.0.0.1'
cls = ''
con_ip = 'localhost'
con_port = ''
host_port = ''
PORT = 15785
user_name = ''
# Host only
names = []
cnn = []
finalgap = []
max_pl = ''
# #def draw(who,vs1):
# p_rect = ((1720/4 - 300 + 10) + 146 * j, (1000/2 - 300 + 10) + 146 * i, 142, 142)
# if who[i][j] == 0:
# pygame.draw.rect(screen, "#EEEEAA", p_rect, 0, 5)
# else:
# if who[i][j] < 0:
# pygame.draw.rect(screen, "#888888", p_rect, 0, 5)
# text = normalFont.render("%d" % who[i][j], True, "#444444")
# else:
# if who[i][j] > 262144:
# pygame.draw.rect(screen, box_color[19 - 1], p_rect, 0, 5)
# else:
# pygame.draw.rect(screen, box_color[int(math.log2(who[i][j]) - 1)], p_rect, 0, 5)
# if who[i][j] > 262144:
# text = normalFont.render("%d" % who[i][j], True, text_color[19 - 1])
# elif who[i][j] == 262144:
# text = normalFont.render("Max", True, text_color[int(math.log2(who[i][j]) - 1)])
# else:
# text = normalFont.render("%d" % who[i][j], True, text_color[int(math.log2(who[i][j]) - 1)])
# text_r = text.get_rect()
# cen = (211+146*j,242+146*i)
# text_r.center = cen
# screen.blit(text, text_r)
errorResulted = False
errorMsg = ''
client_freeze = False
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 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
"""
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 == 'Hosting'
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:
yclisoc.connect((con_ip, int(con_port)))
state = 'waiting_room'
curr_state = 'cilent'
except Exception as e:
state = 'lobby'
curr_state = ''
con_ip = ''
con_port = ''
errorResulted = True
errorMsg = "Wrong Ip input"
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:
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:
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 int(max_pl) > 1:
yclisoc.bind(('', int(host_port)))
curr_state = 'host'
state = 'waiting_room'
yclisoc.listen(int(max_pl)-1)
elif len(max_pl) < 2:
max_pl += event.unicode
if not max_pl.isdigit():
max_pl = max_pl[:-1]
if state == 'ingame':
w1 = banghyang(event.key, you, cls)
if not w1:
randomSpawn(you, sp)
screen.fill("#DDDD77")
if state == 'ingame':
att = cls.recv(1024)
print(att)
if att < 0:
myatt.append(att)
if len(att) > 0 and not full(you):
randomAttack(you, myatt)
v = Lose(you)
# fill the screen with a color to wipe away anything from last frame
pygame.draw.rect(screen, "#FFFFAA", box, 0, 10)
for i in range(4):
for j in range(4):
draw(you)
# flip() the display to put your work on screen
if not v:
t = pygame.font.SysFont("Lucida Console", 140).render("Defeat", True, (0, 0, 0))
t_r = t.get_rect()
t_r.center = (1720/2,1000/2)
screen.blit(t, t_r)
else:
if state == 'lobby':
if errorResulted:
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:
errorResulted = False
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:
errorResulted = False
state = 'host_port'
if state == 'waiting_room' and curr_state == 'host':
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)
try:
att = yclisoc.recv(1024).decode("utf-8")
data = json.loads(att)
if names.index(data["dis_name"]) < 1:
names.append(data["dis_name"])
except BlockingIOError:
pass
except OSError:
pass
try:
currpl += 1
conn, addr = yclisoc.accept()
conn.setblocking(False)
cnn.append(conn)
print(f"새 클라이언트 접속: {conn}.{addr}")
except BlockingIOError:
pass
gap = {
"crpl":[currpl,max_pl],
"names": names
}
for cl in cnn:
cl.sendall(json.dumps(gap).encode("utf-8"))
for i in range(len(names)):
drawtext(None,55,names[i],(0,0,0),(1720/2-250,1000/2-360*i))
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)
try:
att = yclisoc.recv(1024).decode("utf-8")
data = json.loads(att)
except BlockingIOError:
pass
except ConnectionResetError:
yclisoc.close()
state = 'lobby'
gap = {
"dis_name":user_name
}
drawtext(None,45,"players","#000000",(1720/2-250,1000/2-290))
try:
drawtext(None, 45, "%d/%d" % (int(data["crpl"][0]), int(data["crpl"][1])), "#000000",(1720 / 2 + 250, 1000 / 2 - 260))
for i in range(len(data["names"])):
drawtext(None,55,data["names"][i],(0,0,0),(1720/2-250,1000/2-360*i))
except NameError:
pass
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()top of page

실제 작동 상태를 확인하려면 라이브 사이트로 이동하세요.
asds
asds
댓글 0개
좋아요
댓글(0)
더 이상 게시물에 대한 댓글 기능이 지원되지 않습니다. 자세한 사항은 사이트 소유자에게 문의하세요.
bottom of page


