Initial commit

This commit is contained in:
pjht 2020-05-11 19:52:50 -05:00
commit 76c3665cc7
168 changed files with 1215 additions and 0 deletions

1
.gitignore vendored Normal file
View File

@ -0,0 +1 @@
__pycache__

BIN
animation/door/0.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 691 B

BIN
animation/door/1.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 717 B

BIN
animation/door/2.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 690 B

BIN
animation/door/3.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 616 B

BIN
animation/furnace/0.png Executable file

Binary file not shown.

After

Width:  |  Height:  |  Size: 219 B

BIN
animation/furnace/1.png Executable file

Binary file not shown.

After

Width:  |  Height:  |  Size: 204 B

BIN
animation/furnace/2.png Executable file

Binary file not shown.

After

Width:  |  Height:  |  Size: 187 B

BIN
basictiles.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

BIN
characters.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.7 KiB

BIN
nails/nails.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.0 KiB

1
nails/nails.png.txt Normal file
View File

@ -0,0 +1 @@
nails_0.png.png 2 4, nails_1.png.png 35 7, nails_2.png.png 69 8, nails_3.png.png 99 11, nails_4.png.png 3 39, nails_5.png.png 35 39, nails_6.png.png 68 42, nails_7.png.png 101 42, nails_8.png.png 2 68, nails_9.png.png 34 68, nails_10.png.png 66 68, nails_11.png.png 98 67, nails_12.png.png 8 101, nails_13.png.png 35 98, nails_14.png.png 73 100, nails_15.png.png 102 100.

BIN
nails/nails_0.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 338 B

BIN
nails/nails_1.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 327 B

BIN
nails/nails_10.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 302 B

BIN
nails/nails_11.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 298 B

BIN
nails/nails_12.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 288 B

BIN
nails/nails_13.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 372 B

BIN
nails/nails_14.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 309 B

BIN
nails/nails_15.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 333 B

BIN
nails/nails_2.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 231 B

BIN
nails/nails_3.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 251 B

BIN
nails/nails_4.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 374 B

BIN
nails/nails_5.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 375 B

BIN
nails/nails_6.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 319 B

BIN
nails/nails_7.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 320 B

BIN
nails/nails_8.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 294 B

BIN
nails/nails_9.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 300 B

4
old/.gitignore vendored Normal file
View File

@ -0,0 +1,4 @@
__pycache__
map_*.pkl
serv
client

240
old/blocks.py Normal file
View File

@ -0,0 +1,240 @@
import pygame
import os
import lib.constants as constants
from lib.gameregistry import GameRegistry
from lib.block import Block
from lib.inventory import Inventory
dy_blocks={}
def make_block(klass_name,name,clear=False,drops=False):
def blk_init():
pass
def init(self,x,y,screen):
Block.__init__(self,x,y,screen)
self.setTextureName(name)
self.clear=clear
self.drops=drops
self.unlocalisedName=name
attr_table={
"unlocalisedName":name,
"__init__":init,
"init":blk_init,
}
klass=type(klass_name,(Block,),attr_table)
GameRegistry.registerBlock(klass,name)
Block.registerTexture(name)
glob=globals()
glob[klass_name]=klass
global dy_blocks
dy_blocks[klass_name]=name
return klass
make_block("BlockStone","stone")
make_block("BlockTree","tree",False,("wood",8))
make_block("BlockGrass","grass",True)
make_block("BlockWood","wood")
make_block("BlockCoal","coal_ore")
GameRegistry.registerFuel("coal_ore",8)
make_block("BlockIron","iron_ore")
make_block("ItemIronIngot","iron_ingot",False)
#make_block("ItemCoal","coal",False)
class BlockDoor(Block):
unlocalisedName="door"
openDoor=pygame.image.load(os.path.join("tiles","door_open.png"))
@classmethod
def init(cls):
GameRegistry.registerBlock(cls,cls.unlocalisedName)
Block.registerTexture(cls.unlocalisedName)
def __init__(self,x,y,screen):
Block.__init__(self,x,y,screen)
self.setTextureName(BlockDoor.unlocalisedName)
self.unlocalisedName=BlockDoor.unlocalisedName
def interact(self,inv):
self.clear=not self.clear
pygame.mixer.Sound("door.ogg").play().set_volume(0.2)
def getTexture(self):
if self.clear:
return BlockDoor.openDoor
else:
return False
def interactData(self):
return {"clear":self.clear}
def loadData(self,data):
self.clear=data["clear"]
class BlockWorkbench(Block):
unlocalisedName="workbench"
@classmethod
def init(cls):
GameRegistry.registerBlock(cls,cls.unlocalisedName)
Block.registerTexture(cls.unlocalisedName)
def __init__(self,x,y,screen):
Block.__init__(self,x,y,screen)
self.setTextureName(BlockWorkbench.unlocalisedName)
self.unlocalisedName=BlockWorkbench.unlocalisedName
self.inv=Inventory()
def interact(self,inv):
selected=inv.selected
if selected!="":
inv.remove(selected)
self.inv.addTile(selected,1)
else:
if self.inv.inv in GameRegistry.recipes.values():
out=""
for outp,reqs in GameRegistry.recipes.items():
if self.inv.inv==reqs:
out=outp
break
inv.addTile(out,1)
self.inv.clear()
def interactData(self):
return {"inv":self.inv}
def loadData(self,data):
self.inv=data["inv"]
class BlockFurnace(Block):
unlocalisedName="furnace"
frames=[]
@classmethod
def init(cls):
GameRegistry.registerBlock(cls,cls.unlocalisedName)
Block.registerTexture(cls.unlocalisedName)
for i in range(3):
path=os.path.join("animation",cls.unlocalisedName,"{}.png".format(i))
img=pygame.image.load(path)
cls.frames.append(img)
def __init__(self,x,y,screen):
Block.__init__(self,x,y,screen)
self.setTextureName(BlockFurnace.unlocalisedName)
self.unlocalisedName=BlockFurnace.unlocalisedName
self.frameno=0
self.forward=True
self.burn=False
self.count=0
self.inp=""
self.inp_amount=0
self.outp=""
self.outp_amount=0
self.fuel=""
self.fuel_amount=0
self.fuel_num=0
self.originator=True
def interact(self,inv):
sel=inv.selected
if sel!="":
if sel in GameRegistry.fuels.keys():
if self.fuel!="" and sel!=self.fuel:
return
self.fuel=sel
self.fuel_num=GameRegistry.fuels[sel]
self.fuel_amount+=1
if self.inp!="":
if self.burn==False:
self.fuel_amount-=1
self.burn=True
else:
if self.inp!="" and sel!=self.inp:
return
if not sel in GameRegistry.smelting.keys():
return
self.inp_amount+=1
self.inp=sel
if self.burn==False and self.fuel!="":
self.fuel_amount-=1
self.burn=True
inv.remove(sel)
else:
if self.outp!="":
inv.addTile(self.outp,self.outp_amount)
self.outp=""
self.outp_amount=0
self.originator=True
def getTexture(self):
if self.burn:
self.count+=1
if self.count==10:
self.update()
self.count=0
img=BlockFurnace.frames[self.frameno]
if self.forward:
self.frameno+=1
if self.frameno>2:
self.frameno=1
self.forward=False
else:
self.frameno-=1
if self.frameno<0:
self.frameno=1
self.forward=True
return img
else:
return False
self.mp_upd=True
def update(self):
self.fuel_num-=1
if self.inp=="":
self.burn=False
return
if self.fuel_num<=0:
if self.fuel_amount<=0:
self.burn=False
self.fuel=""
return
else:
self.fuel_amount-=1
self.fuel_num=GameRegistry.fuels[self.fuel]
if self.inp!="":
if self.inp in GameRegistry.smelting:
self.inp_amount-=1
self.outp=GameRegistry.smelting[self.inp]
self.outp_amount+=1
if self.inp_amount<=0:
self.inp=""
if self.originator:
self.mp_upd=True
def loadData(self,data):
self.frameno=data["frameno"]
self.forward=data["forward"]
self.burn=data["burn"]
self.count=data["count"]
self.inp=data["inp"]
self.inp_amount=data["inp_amount"]
self.outp=data["outp"]
self.outp_amount=data["outp_amount"]
self.fuel=data["fuel"]
self.fuel_amount=data["fuel_amount"]
self.fuel_num=data["fuel_num"]
self.originator=False
def interactData(self):
self.mp_upd=False
return {
"frameno":self.frameno,
"forward":self.forward,
"burn":self.burn,
"count":self.count,
"inp":self.inp,
"inp_amount":self.inp_amount,
"outp":self.outp,
"outp_amount":self.outp_amount,
"fuel":self.fuel,
"fuel_amount":self.fuel_amount,
"fuel_num":self.fuel_num
}

292
old/client.py Normal file
View File

@ -0,0 +1,292 @@
import pygame
import os
import random
import recipes
import sys
import select
import blocks
import socket
import pickle
import lib.constants as constants
from lib.gameregistry import GameRegistry
from lib.map import Map
from lib.character import Character
from lib.block import Block
from lib.player import Player
from lib.player_img import PlayerImg
from showstep import show_step
from time import sleep
import pprint
pp=pprint.PrettyPrinter(indent=2)
def recv_str(sock,print_str=True):
str=""
ch=""
while True:
ch=sock.recv(1).decode("utf-8")
if ch=="\n":
break
str+=ch
if print_str:
pass
# print("Got string: "+str)
return str
def send_str(sock,str):
# print("Sending string: "+str)
sock.send((str+"\n").encode("utf-8"))
def recv_hash(sock):
hash={}
len=int(recv_str(sock,False))
for _ in range(len):
key=recv_str(sock,False)
val=recv_str(sock,False)
hash[key]=val
# print("Got hash: "+pp.pformat(hash))
return hash
def recvall(sock):
BUFF_SIZE=4096
data=b''
while True:
part=sock.recv(BUFF_SIZE)
data+=part
if len(part)<BUFF_SIZE:
break
# print("Got data: "+pp.pformat(pickle.loads(data)))
return data
UNAME=input("UNAME:")
pygame.init()
Block.init()
recipes.init()
pygame.display.set_caption(UNAME)
screen=pygame.display.set_mode((constants.WINDWIDTH,constants.WINDHEIGHT))
sock=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# show_step("Connecting to game server")
sock.connect(("localhost",2000))
# show_step("Adding user to server (Sending ADD_USR {})".format(UNAME))
send_str(sock,"ADD_USR")
send_str(sock,UNAME)
# show_step("Recieving UID")
my_uid=int(recv_str(sock))
# show_step("Got UID {}".format(my_uid))
# show_step("Initializing UID map")
uid_map={}
# show_step("Initializing level map")
map=Map(screen,sock,my_uid)
map.tiles={}
# show_step("Retreiving player position and facing (Sending GET_POS_FOR_UID {})".format(my_uid))
send_str(sock,"GET_POS_FOR_UID")
send_str(sock,str(my_uid))
x=int(recv_str(sock))
y=int(recv_str(sock))
fac=recv_str(sock)
# show_step("Got position ({},{}), facing {}".format(x,y,fac))
# show_step("Initializing player")
player=Player(x,y,map,screen,UNAME,"player_local")
player.dir=fac
# show_step("Adding workbench to inventory")
player.inv.addTile("workbench",1)
# show_step("Initializing misc game variables")
others={}
running=True
move=False
inv=False
helvetica_neue=pygame.font.SysFont('Helvetica Neue',constants.FONTSIZE)
key_to_dir={
pygame.K_UP:"up",
pygame.K_DOWN:"down",
pygame.K_LEFT:"left",
pygame.K_RIGHT:"right"
}
while running:
# show_step("Updating game and drawing frame")
send_str(sock,"GET_UID_MAP")
uid_map=recv_hash(sock)
# Will be filled with usernames of connected players
connected=[]
for uname,uid in uid_map.items():
if uname!=UNAME:
send_str(sock,"GET_POS_FOR_UID")
send_str(sock,uid)
x=int(recv_str(sock))
y=int(recv_str(sock))
fac=recv_str(sock)
if uname in others:
others[uname].x=x
others[uname].y=y
else:
others[uname]=PlayerImg(x,y,screen,"player")
others[uname].dir=fac
connected.append(uname)
# Remove all disconnected players
others_copy=others.copy()
for uname,uid in others_copy.items():
if not uname in connected:
del others[uname]
send_str(sock,"GET_CHANGES_FOR")
send_str(sock,str(my_uid))
data=recvall(sock)
changes=pickle.loads(data)
for change in changes:
if change["type"]=="break":
x=change["x"]
y=change["y"]
tile=map.tileAt(x,y)
name=tile.unlocalisedName
if name=="grass":
continue
map.tiles[(x,y)]=None
map.addTile("grass",x,y)
if change["type"]=="place":
x=change["x"]
y=change["y"]
block=change["block"]
map.tiles[(x,y)]=None
map.addTile(block,x,y)
if change["type"]=="interact":
x=change["x"]
y=change["y"]
block_data=change["block_data"]
tile=map.tileAt(x,y)
tile.loadData(block_data)
for s in map.tiles.values():
if s.mp_upd:
data=s.interactData()
send_str(sock,"INTERACT_BLOCK_AT")
send_str(sock,str(my_uid))
send_str(sock,str(s.x))
send_str(sock,str(s.y))
data_string=pickle.dumps(data)
sock.send(data_string)
if select.select([sys.stdin],[],[],0.0)[0]:
cmd=input()
cmd=cmd.split()
if len(cmd)==1:
if cmd[0]=="give":
if len(cmd)==2:
item=cmd[1]
player.inv.addTile(item,1)
elif len(cmd)==3:
item=cmd[1]
count=int(cmd[2])
player.inv.addTile(item,count)
else:
print("give <item> [count]")
for event in pygame.event.get():
if event.type==pygame.QUIT:
running=False
elif event.type==pygame.KEYDOWN:
print("DOWN")
print(event.key)
if event.key==pygame.K_PERIOD:
coords=player.facingTile()
if coords!=False:
tile=map.tileAt(coords[0],coords[1])
name=tile.unlocalisedName
if name=="grass":
to_place=player.inv.selected
if to_place!="":
send_str(sock,"PLACE_BLOCK_AT")
send_str(sock,str(my_uid))
send_str(sock,str(coords[0]))
send_str(sock,str(coords[1]))
send_str(sock,str(to_place))
player.interact()
else:
player.interact()
tile=map.tileAt(coords[0],coords[1])
data=tile.interactData()
if data!=None:
send_str(sock,"INTERACT_BLOCK_AT")
send_str(sock,str(my_uid))
send_str(sock,str(coords[0]))
send_str(sock,str(coords[1]))
data_string=pickle.dumps(data)
sock.send(data_string)
if event.key==pygame.K_SLASH:
player.attack()
facing=player.facingTile()
print(facing)
if facing!=False:
print("BREAK")
x=facing[0]
y=facing[1]
send_str(sock,"BREAK_BLOCK_AT")
send_str(sock,str(my_uid))
send_str(sock,str(x))
send_str(sock,str(y))
if event.key==pygame.K_j:
player.inv.selPrev()
if event.key==pygame.K_k:
player.inv.clearSel()
if event.key==pygame.K_l:
player.inv.selNext()
if event.key==pygame.K_e:
inv=not inv
if event.key==pygame.K_i:
dy_blocks=blocks.dy_blocks
Block.textures={}
Block.init()
for klass,unName in dy_blocks.items():
Block.registerTexture(unName)
elif event.key in key_to_dir.keys():
move=True
dir=key_to_dir[event.key]
elif event.type==pygame.KEYUP:
move=False
player.frame=1
if move:
player.move(dir)
send_str(sock,"SET_POS_FOR_UID")
send_str(sock,str(my_uid))
send_str(sock,str(player.x))
send_str(sock,str(player.y))
send_str(sock,player.dir)
if inv:
screen.fill([255,255,255])
text=[]
label=[]
for item, count in player.inv.inv.items():
text.append("{} {}".format(count,item))
for line in text:
label.append(helvetica_neue.render(line, True, (0,0,0)))
for line in range(len(label)):
screen.blit(label[line],(1,(line*constants.FONTSIZE)+(2*line)))
pygame.display.flip()
else:
screen.fill([0,0,0])
map.draw(player.x,player.y)
player.draw()
selected=player.inv.selected
if selected!="":
texture=Block.textures[selected]
screen.blit(texture,(0*constants.TILESIZE,constants.PORTHEIGHT*constants.TILESIZE))
topleftx=player.x-constants.CENTERX
toplefty=player.y-constants.CENTERY
x=topleftx
y=toplefty
while True:
other=None
for uname,o in others.items():
if o.x==x and o.y==y:
other=o
break
if other:
other.draw(x-topleftx,y-toplefty)
x+=1
if x==topleftx+constants.PORTWIDTH:
x=topleftx
y+=1
if y==toplefty+constants.PORTHEIGHT:
break
pygame.display.flip()
sleep(0.1)
send_str(sock,"CLOSE")
send_str(sock,UNAME)
sock.close()

3
old/dist_all Executable file
View File

@ -0,0 +1,3 @@
#!/usr/bin/env bash
./dist_client
./dist_serv

11
old/dist_client Executable file
View File

@ -0,0 +1,11 @@
#!/usr/bin/env bash
rm -rf client
mkdir client
mkdir client/code
cp -r lib sprites tiles animation blocks.py recipes.py showstep.py client/code
cp client.py client/code
echo "#!/usr/bin/env bash
cd code
python3 client.py
cd .." > client/run
chmod u+x client/run

10
old/dist_serv Executable file
View File

@ -0,0 +1,10 @@
#!/usr/bin/env bash
rm -rf serv
mkdir serv
mkdir serv/code
mkdir serv/worlds
cp -r lib blocks.py recipes.py serv/code
cp serv.py serv/code
echo "#!/usr/bin/env bash
python3 code/serv.py" > serv/run
chmod u+x serv/run

BIN
old/door.ogg Normal file

Binary file not shown.

2
old/lib/__init__.py Normal file
View File

@ -0,0 +1,2 @@
from . import block,constants,gameregistry,map,character,inventory,player,player_img
__all__=["block","gameregistry","map","character","inventory","player","player_img"]

55
old/lib/block.py Normal file
View File

@ -0,0 +1,55 @@
from pygame.sprite import Sprite
import pygame.image
import os
from time import sleep
from . import constants
class Block(Sprite):
textures={}
background=pygame.image.load(os.path.join("tiles","{}.png".format(constants.BACKGROUND)))
@classmethod
def init(cls):
subclasses=cls.__subclasses__()
for klass in subclasses:
klass.init()
def __init__(self,x,y,screen):
super().__init__()
self.x=x
self.y=y
self.screen=screen
self.tname=None
self.clear=False
self.unlocalisedName=""
self.drops=False
self.mp_upd=False
def draw(self,x,y):
# print("DRAW BLOCK")
if self.tname==None:
raise Exception("No texture name for block. Did you forget to call setTextureName()?".format())
self.screen.blit(Block.background,(x*constants.TILESIZE,y*constants.TILESIZE))
texture=self.getTexture()
if texture==False:
texture=Block.textures[self.tname]
self.screen.blit(texture,(x*constants.TILESIZE,y*constants.TILESIZE))
# sleep(0.05)
def setTextureName(self,name):
if not name in Block.textures.keys():
raise Exception("{} is not a valid texture. Did you forget to call registerTexture(\"{}\")?".format(name,name))
self.tname=name
@classmethod
def registerTexture(cls,name):
Block.textures[name]=pygame.image.load(os.path.join("tiles","{}.png".format(name)))
def interact(self,inv):
pass
def getTexture(self):
return False
def interactData(self):
return None
def loadData(self,data):
pass

53
old/lib/character.py Normal file
View File

@ -0,0 +1,53 @@
from pygame.sprite import Sprite
import pygame.image
import os
from . import constants
class Character(Sprite):
@staticmethod
def loadFrames(type):
frames={}
dirs=["up","down","left","right"]
num_frames=3
for dir in dirs:
frame_array=[0,0,0]
i=0
while i<num_frames:
img_name="{}_{}.png".format(dir,i)
frame_array[i]=pygame.image.load(os.path.join("sprites",type,img_name))
i+=1
frames[dir]=frame_array
return frames
def __init__(self,x,y,type,map,screen,*groups):
super().__init__(groups)
self.x=x
self.y=y
self.screen=screen
self.frames=self.loadFrames(type)
self.frame=1
self.dir="right"
self.map=map
def draw(self):
img=self.frames[self.dir][self.frame]
self.screen.blit(img,(self.x*constants.TILESIZE,self.y*constants.TILESIZE))
def move(self,dir):
old_x=self.x
old_y=self.y
self.dir=dir
if dir=="up":
self.y-=1
elif dir=="down":
self.y+=1
elif dir=="left":
self.x-=1
elif dir=="right":
self.x+=1
self.frame+=1
if self.frame>2:
self.frame=0
tile=self.map.tileAt(self.x,self.y)
if not tile.clear:
self.x=old_x
self.y=old_y

12
old/lib/constants.py Normal file
View File

@ -0,0 +1,12 @@
TILESIZE=16
MAPWIDTH=64
MAPHEIGHT=64
PORTHEIGHT=32
PORTWIDTH=32
EXTRAROWS=1
CENTERX=15
CENTERY=15
WINDWIDTH=PORTWIDTH*TILESIZE
WINDHEIGHT=(PORTHEIGHT+EXTRAROWS)*TILESIZE
BACKGROUND="grass"
FONTSIZE=30

25
old/lib/gameregistry.py Normal file
View File

@ -0,0 +1,25 @@
class GameRegistry:
block_classes={}
recipes={}
smelting={}
fuels={}
@classmethod
def registerBlock(cls,klass,name):
if not klass in cls.block_classes.keys():
cls.block_classes[name]=klass
@classmethod
def registerCrafting(cls,reqs,result):
if not result in cls.recipes.keys():
cls.recipes[result]=reqs
@classmethod
def registerSmelting(cls,inp,outp):
if not inp in cls.smelting.keys():
cls.smelting[inp]=outp
@classmethod
def registerFuel(cls,name,amount):
if not name in cls.fuels.keys():
cls.fuels[name]=amount

51
old/lib/inventory.py Normal file
View File

@ -0,0 +1,51 @@
class Inventory:
def __init__(self):
self.inv={}
self.selected=""
def addTile(self,name,amount):
if name in self.inv.keys():
self.inv[name]+=amount
else:
self.inv[name]=amount
self.selected=name
def remove(self,name,num=1):
if not name in self.inv:
raise Exception("No {} in inventory".format(name))
amount=self.inv[name]
amount-=num
if amount<0:
raise Exception("Attempted to remove more {} than avalible".format(name))
self.inv[name]=amount
if amount==0:
del self.inv[name]
self.selected=""
def selPrev(self):
newsel=""
for item, count in self.inv.items():
if item==self.selected:
break
newsel=item
if newsel!="":
self.selected=newsel
def clearSel(self):
self.selected=""
def selNext(self):
newsel=""
ok_next=False
for item, count in self.inv.items():
if ok_next:
newsel=item
break
if item==self.selected:
ok_next=True
if newsel!="":
self.selected=newsel
def clear(self):
self.inv={}
self.selected=""

107
old/lib/map.py Normal file
View File

@ -0,0 +1,107 @@
import pygame
import random
from pygame.sprite import Group
from . import block,gameregistry
from . import constants
from .gameregistry import GameRegistry
from .block import Block
import pickle
class Map:
def __init__(self,screen,sock=None,uid=None):
super().__init__()
self.tiles={}
self.screen=screen
self.sock=sock
self.uid=uid
self.generate()
def send_str(self,sock,str):
# print(str)
sock.send((str+"\n").encode("utf-8"))
def recvall(self,sock):
BUFF_SIZE=4096
data=b''
while True:
part=sock.recv(BUFF_SIZE)
data+=part
if len(part)<BUFF_SIZE:
break
#print(pickle.loads(data))
return data
def addTile(self,tname,x,y):
klass=GameRegistry.block_classes[tname]
tile=klass(x,y,self.screen)
self.tiles[(x,y)]=tile
def generate(self):
y=0
while y<constants.MAPHEIGHT:
x=0
while x<constants.MAPWIDTH:
num=random.randint(0,101)
if num<5:
num=random.randint(0,101)
if num<50:
self.addTile("tree",x,y)
else:
self.addTile("stone",x,y)
else:
self.addTile(constants.BACKGROUND,x,y)
x+=1
y+=1
def draw(self,centerx,centery):
topleftx=centerx-constants.CENTERX
toplefty=centery-constants.CENTERY
x=topleftx
y=toplefty
while True:
tile=self.tileAt(x,y)
if tile:
tile.draw(x-topleftx,y-toplefty)
x+=1
if x==topleftx+constants.PORTWIDTH:
x=topleftx
y+=1
if y==toplefty+constants.PORTHEIGHT:
break
def tileAt(self,x,y):
try:
return self.tiles[(x,y)]
except KeyError as e:
if self.sock:
self.send_str(self.sock,"BLOCK_AT_POS")
self.send_str(self.sock,str(x))
self.send_str(self.sock,str(y))
data=self.recvall(self.sock)
block=pickle.loads(data)
if block==None:
name=""
num=random.randint(0,101)
if num<5:
num=random.randint(0,101)
if num<50:
name="tree"
self.addTile("tree",x,y)
else:
name="stone"
self.addTile("stone",x,y)
else:
name=constants.BACKGROUND
self.addTile(constants.BACKGROUND,x,y)
self.send_str(self.sock,"PLACE_BLOCK_AT")
self.send_str(self.sock,str(self.uid))
self.send_str(self.sock,str(x))
self.send_str(self.sock,str(y))
self.send_str(self.sock,str(name))
else:
block.screen=self.screen
self.tiles[(x,y)]=block
else:
print("Cannot contact server. Exiting")
exit(1)
return self.tiles[(x,y)]

71
old/lib/player.py Normal file
View File

@ -0,0 +1,71 @@
from lib.character import Character
import lib.constants as constants
from lib.inventory import Inventory
class Player(Character):
def __init__(self,x,y,map,screen,uname,type,*groups):
super().__init__(x,y,type,map,screen,*groups)
self.inv=Inventory()
self.uname=uname
def facingTile(self):
x=self.x
y=self.y
if self.dir=="up":
y-=1
elif self.dir=="down":
y+=1
elif self.dir=="left":
x-=1
elif self.dir=="right":
x+=1
if x>constants.MAPWIDTH-1:
return False
if x<0:
return False
if y>constants.MAPHEIGHT-1:
return False
if y<0:
return False
return (x,y)
def interact(self):
coords=self.facingTile()
if coords==False:
return
tile=self.map.tileAt(coords[0],coords[1])
name=tile.unlocalisedName
if name=="grass":
to_place=self.inv.selected
if to_place=="":
return
self.map.tiles[(coords[0],coords[1])]=None
self.map.addTile(to_place,coords[0],coords[1])
self.inv.remove(to_place)
else:
tile.interact(self.inv)
def attack(self):
coords=self.facingTile()
if coords==False:
return
tile=self.map.tileAt(coords[0],coords[1])
name=tile.unlocalisedName
if name=="grass":
return
self.map.tiles[(coords[0],coords[1])]=None
self.map.addTile("grass",coords[0],coords[1])
if tile.drops==False:
self.inv.addTile(name,1)
else:
drop=tile.drops[0]
amount=tile.drops[1]
self.inv.addTile(drop,amount)
def draw(self):
oldx=self.x
oldy=self.y
self.x=constants.CENTERX
self.y=constants.CENTERY
super().draw()
self.x=oldx
self.y=oldy

33
old/lib/player_img.py Normal file
View File

@ -0,0 +1,33 @@
from pygame.sprite import Sprite
import pygame.image
import os
import lib.constants as constants
class PlayerImg(Sprite):
@staticmethod
def loadFrames(type):
frames={}
dirs=["up","down","left","right"]
num_frames=3
for dir in dirs:
frame_array=[0,0,0]
i=0
while i<num_frames:
img_name="{}_{}.png".format(dir,i)
frame_array[i]=pygame.image.load(os.path.join("sprites",type,img_name))
i+=1
frames[dir]=frame_array
return frames
def __init__(self,x,y,screen,type,*groups):
super().__init__(groups)
self.x=x
self.y=y
self.screen=screen
self.frames=self.loadFrames(type)
self.frame=1
self.dir="right"
self.map=map
def draw(self,x,y):
img=self.frames[self.dir][self.frame]
self.screen.blit(img,(x*constants.TILESIZE,y*constants.TILESIZE))

7
old/recipes.py Normal file
View File

@ -0,0 +1,7 @@
from lib.gameregistry import GameRegistry
def init():
GameRegistry.registerCrafting({"wood":6},"door")
GameRegistry.registerCrafting({"wood":4},"workbench")
GameRegistry.registerCrafting({"stone":8},"furnace")
GameRegistry.registerSmelting("iron_ore","wood")

234
old/serv.py Normal file
View File

@ -0,0 +1,234 @@
import pygame
import sys
def my_load(path):
return None
mod=sys.modules["pygame.image"]
mod.load=my_load
sys.modules["pygame.image"]=mod
import os
import random
import recipes
import select
import socket
import _thread
import pickle
import signal
import glob
import os.path
import lib.constants as constants
from lib.gameregistry import GameRegistry
from lib.map import Map
from lib.character import Character
from lib.block import Block
from lib.player import Player
from time import sleep
uid_map={}
pos_map={}
map_changes={}
next_uid=0
import blocks
import pprint
pp=pprint.PrettyPrinter(indent=2)
def recv_str(sock):
str=""
ch=""
while True:
ch=sock.recv(1).decode("utf-8")
if ch=="\n":
break
str+=ch
# print("Got string: "+str)
return str
def send_str(sock,str,print_str=True):
if print_str:
pass
# print("Sending string: "+str)
sock.send((str+"\n").encode("utf-8"))
def send_hash(sock,hash):
# print("Sending hash: "+pp.pformat(hash))
send_str(sock,str(len(hash)),False)
for key,val in hash.items():
send_str(sock,str(key),False)
send_str(sock,str(val),False)
def recvall(sock):
BUFF_SIZE=4096
data=b''
while True:
part=sock.recv(BUFF_SIZE)
data+=part
if len(part)<BUFF_SIZE:
break
# print("Got data: "+pp.pformat(pickle.loads(data)))
return data
def on_new_client(sock):
global uid_map
global next_uid
global pos_map
global map
while True:
msg=recv_str(sock)
if msg=="CLOSE":
uname=recv_str(sock)
uid=uid_map[uname]
del uid_map[uname]
del pos_map[uid]
del map_changes[uid]
elif msg=="ADD_USR":
uname=recv_str(sock)
uid_map[uname]=next_uid
resp=str(next_uid)
send_str(sock,resp)
pos_map[next_uid]=(next_uid,0,"down")
map_changes[next_uid]=[]
next_uid+=1
elif msg=="GET_UID_MAP":
send_hash(sock,uid_map)
elif msg=="BLOCK_AT_POS":
x=int(recv_str(sock))
y=int(recv_str(sock))
block=None
try:
block=map.tiles[(x,y)]
except KeyError as e:
pass
data_string=pickle.dumps(block)
sock.send(data_string)
elif msg=="GET_POS_FOR_UID":
uid=recv_str(sock)
if not int(uid) in uid_map.values():
print("Invalid UID {}".format(uid))
sock.close()
return
pos=pos_map[int(uid)]
send_str(sock,str(pos[0]))
send_str(sock,str(pos[1]))
send_str(sock,pos[2])
elif msg=="SET_POS_FOR_UID":
uid=int(recv_str(sock))
if not int(uid) in uid_map.values():
print("Invalid UID {}".format(uid))
sock.close()
return
x=int(recv_str(sock))
y=int(recv_str(sock))
fac=recv_str(sock)
pos_map[uid]=(x,y,fac)
elif msg=="BREAK_BLOCK_AT":
ch_uid=int(recv_str(sock))
if not int(ch_uid) in uid_map.values():
print("Invalid UID {}".format(uid))
sock.close()
return
x=int(recv_str(sock))
y=int(recv_str(sock))
for uid,changes in map_changes.copy().items():
if ch_uid!=uid:
map_changes[uid].append({"type":"break","x":x,"y":y})
tile=map.tileAt(x,y)
name=tile.unlocalisedName
if name=="grass":
continue
map.tiles[(x,y)]=None
map.addTile("grass",x,y)
elif msg=="PLACE_BLOCK_AT":
ch_uid=int(recv_str(sock))
if not int(ch_uid) in uid_map.values():
print("Invalid UID {}".format(uid))
sock.close()
return
x=int(recv_str(sock))
y=int(recv_str(sock))
block=recv_str(sock)
for uid,changes in map_changes.copy().items():
if ch_uid!=uid:
map_changes[uid].append({"type":"place","x":x,"y":y,"block":block})
map.tiles[(x,y)]=None
map.addTile(block,x,y)
elif msg=="INTERACT_BLOCK_AT":
ch_uid=int(recv_str(sock))
if not int(ch_uid) in uid_map.values():
print("Invalid UID {}".format(uid))
sock.close()
return
x=int(recv_str(sock))
y=int(recv_str(sock))
data=recvall(sock)
block_data=pickle.loads(data)
tile=map.tileAt(x,y)
tile.loadData(block_data)
for uid,changes in map_changes.copy().items():
if ch_uid!=uid:
map_changes[uid].append({"type":"interact","x":x,"y":y,"block_data":block_data})
elif msg=="GET_CHANGES_FOR":
uid=int(recv_str(sock))
if not int(uid) in uid_map.values():
print("Invalid UID {}".format(uid))
sock.close()
return
changes=map_changes[uid]
data_string=pickle.dumps(changes)
sock.send(data_string)
map_changes[uid]=[]
clientsocket.close()
def handle_cmds():
while True:
if select.select([sys.stdin],[],[],0.0)[0]:
cmd=input()
cmd=cmd.split()
if len(cmd)>0:
if cmd[0]=="stop":
s.close()
f=open("worlds/map_{}.pkl".format(map_name),"wb")
pickle.dump(map,f)
f.close()
exit(1)
def exit_cleanup(signal,frame):
s.close()
f=open("worlds/map_{}.pkl".format(map_name),"wb")
pickle.dump(map,f)
f.close()
Block.init()
files=glob.glob("worlds/map_*.pkl")
if len(files)==0:
new="y"
else:
new=input("New world?").lower()
if new=="n" or new=="no":
i=1
map_map=[]
for name in files:
name=name.split("_")
name.pop(0)
name="_".join(name)
name,_=os.path.splitext(name)
print("{}. {}".format(i,name))
map_map.append(name)
i+=1
map_name=map_map[int(input("Which world?"))-1]
f=open("worlds/map_{}.pkl".format(map_name),"rb")
map=pickle.load(f)
f.close()
else:
map_name=input("World name:")
map=Map(None)
s=socket.socket()
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
host="localhost"
port=2000
s.bind((host, port))
s.listen(5)
_thread.start_new_thread(handle_cmds,())
signal.signal(signal.SIGINT, exit_cleanup)
while True:
c,addr=s.accept()
_thread.start_new_thread(on_new_client,(c,))

3
old/showstep.py Normal file
View File

@ -0,0 +1,3 @@
def show_step(step):
print(step)
input("Press enter to proceed")

BIN
sprites/player/down_0.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 263 B

BIN
sprites/player/down_1.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 257 B

BIN
sprites/player/down_2.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 269 B

BIN
sprites/player/left_0.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 263 B

BIN
sprites/player/left_1.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 251 B

BIN
sprites/player/left_2.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 262 B

BIN
sprites/player/right_0.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 268 B

BIN
sprites/player/right_1.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 251 B

BIN
sprites/player/right_2.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 262 B

BIN
sprites/player/up_0.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 254 B

BIN
sprites/player/up_1.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 254 B

BIN
sprites/player/up_2.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 255 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 299 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 292 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 299 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 296 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 280 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 306 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 305 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 279 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 299 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 286 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 281 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 289 B

BIN
sprites/slime/down_0.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 232 B

BIN
sprites/slime/down_1.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 235 B

BIN
sprites/slime/down_2.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 235 B

BIN
sprites/slime/left_0.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 232 B

BIN
sprites/slime/left_1.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 229 B

BIN
sprites/slime/left_2.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 233 B

BIN
sprites/slime/right_0.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 228 B

BIN
sprites/slime/right_1.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 232 B

BIN
sprites/slime/right_2.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 225 B

BIN
sprites/slime/up_0.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 224 B

BIN
sprites/slime/up_1.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 225 B

BIN
sprites/slime/up_2.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 229 B

BIN
things.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.7 KiB

BIN
tiles/bed_bot.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 696 B

BIN
tiles/bed_top.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

BIN
tiles/brick.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 721 B

BIN
tiles/chest.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 771 B

BIN
tiles/chest_open.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 747 B

BIN
tiles/coal_ore.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

BIN
tiles/cobblestone.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 713 B

BIN
tiles/door.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

BIN
tiles/door_open.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

BIN
tiles/furnace.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 696 B

BIN
tiles/grass.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 101 B

BIN
tiles/iron_ingot.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

BIN
tiles/iron_ore.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

BIN
tiles/stone.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

BIN
tiles/texture10.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 101 B

BIN
tiles/texture11.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 704 B

Some files were not shown because too many files have changed in this diff Show More