PyHeek1.7d


This is a program that consists of three modules and two programs (client and server) and was my first attempt at networked programming (written in mid-2008). It implements, or tries to implement, an in-game game from MystOnline.
Note: if this code is missing essential parts I’m sorry. In addition to that, if there are random functions that are not used, I am also sorry. I have forbidden myself from changing the past. This website is kinda meant to be an exposé (like Facebook timeline).

PyHeek1.7d.py

import socket
import threading
import thread
import time
import heek_defs
import string

Version = '1.7'
Port = 1813

global Status
Status = 'Server is currently not running'

global connections
connections = []

global Received
Received = '','',''

global isStartGame
isStartGame = 0


global init_player
init_player = []

global Viewer_connections
Viewer_connections = []

global isVerbose
isVerbose = 0

global isStop
isStop = 0

def VerbosePrint(content):
	if isVerbose == 1:
		print content
	else:
		pass

def ConnectLoop(isStop, Port):
	host = ''
	listenSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	listenSock.bind((host, Port))
	while isStop == 0:
		listenSock.listen(1)
		(sock, address) = listenSock.accept()
		VerbosePrint(( 'accepted connection from: ', address))
		sock.setblocking(0)
		init_player.append((sock,address,address,''))
#		print connections

def Receive5SeatedPlayerLoop(isStop):
	while isStop == 0:
		time.sleep(0.1)
		for Entry in connections:
			data = ''
			Conn, Name, address, seat = Entry
			try:
				data = Conn.recv(1024)
			except:
				pass
			if data != '' or data.startswith('i:'):
				VerbosePrint((data,'     (Name: "',Name, '"   --FromGameSock)'))
				global Received
				Received = data, Name, seat
				if data.startswith('g:'):
					global isStartGame
					isStartGame = 1
			data = ''

def SendToAll(info):
	time.sleep(0.2)
	for Entry in connections:
		Conn, Name, address, seat = Entry
		try:
			Conn.send(info)
		except:
			pass
	for Entry in Viewer_connections:
		Conn, Name, address, seat = Entry
		try:
			Conn.send(info)
		except:
			pass

def DisconnectClient(Conn):
		Conn.close()
		
def RemoveClient(Conn):
		Conn.close()
		try:
			connections.remove(Conn)
		except:
			pass

def KickClient(input_name):
	for Entry in connections:
		Conn, Name, address, seat = Entry
		if Name == input_name:
			RemoveClient(Conn)
			print '%s kicked' % Name
			return
	for Entry in Viewer_connections:
		Conn, Name, address, seat = Entry
		if Name == input_name:
			RemoveClient(Conn)
			print '%s kicked' % Name
			return
	print 'User not found'
	
def GetSeatStatus():
	seats = [0,0,0,0,0]
	if connections != []:
		for Entry in connections:
			Conn, Name, address, seat = Entry
			if seat == '1':
				seats.__setitem__(0,1)
			if seat == '2':
				seats.__setitem__(1,1)
			if seat == '3':
				seats.__setitem__(2,1)
			if seat == '4':
				seats.__setitem__(3,1)
			if seat == '5':
				seats.__setitem__(4,1)
	VerbosePrint((seats,'  --Seats'))
	return seats
##		global Heek_seats
##		Heek_seats = seats
def AllocatePlayerSeats(GetSeatStatus):
	Heek_seats = GetSeatStatus
	if (Heek_seats.__getitem__(0)) == 0:
		return '1'
	if (Heek_seats.__getitem__(1)) == 0:
		return '2'
	if (Heek_seats.__getitem__(2)) == 0:
		return '3'
	if (Heek_seats.__getitem__(3)) == 0:
		return '4'
	if (Heek_seats.__getitem__(4)) == 0:
		return '5'
	else:
		return '0'

def GetNameStatus(in_name):
	seats = [0,0,0,0,0]
	if connections != []:
		for Entry in connections:
			Conn, Name, address, seat = Entry
			if in_name == Name:
				return '1'
	return '0'

def GetNameFromSeatNum(num):
	for Entry in connections:
		Conn, Name, address, seat = Entry
		if seat == num:
			return Name
	return ''
def CheckIfWin():
	global match_scores
	for Entry in connections:
		Conn, Name, address, seat = Entry
		player_score = match_scores[(int(seat)-1)]
		VerbosePrint(('player %s: ' % Name))
		##check scores;  This is a round-about way of doing it but, the other ways seemed buggy		
##		print "++++++++++TESTING_1_!!!!+++++++++"
		IND_score = player_score[0]
##		print IND_score
		if 2 < IND_score:
			VerbosePrint((Name+" wins a Pen"))
			match_scores = [[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0]]
			return Name+" wins a Pen"
##		print "++++++++++TESTING_2_!!!!+++++++++"
		IND_score = player_score[1]
##		print IND_score
		if 2 < IND_score:
			VerbosePrint((Name+" wins a Page",heek_defs.decode(loopTimes)))
			match_scores = [[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0]]
			return Name+" wins a Page"
##		print "++++++++++TESTING_3_!!!!+++++++++"
		IND_score = player_score[2]
##		print IND_score
		if 2 < IND_score:
			VerbosePrint((Name+" wins a Beetle"))
			match_scores = [[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0]]
			return Name+" wins a Beetle"
	return ''


def pingClient(Entry, Conn, Name):
		try:
			VerbosePrint('sending ping')
			Conn.send('ping')
		except:
			pass
		currtime = time.clock()
		start_time = time.clock()
		added_time = start_time + 8.00
		while 1:
			data, RCV_name, seat = Received
			time.sleep(0.2)
			VerbosePrint('.')
#			print added_time, currtime
			if Name == RCV_name:
				VerbosePrint(('received something from Client'))
				VerbosePrint((data,Name,'   -In_Ping'))
				VerbosePrint(("All's well with %s" % Name))
				return 0
#				break
			if currtime > added_time:
				VerbosePrint(("Disconnecting",Name))
				connections.remove(Entry)
				Conn.close()
				return 0
			currtime = time.clock()
#		print 'our business is done here'
			


def pingAll(isStop, pingClient):
	while isStop == 0:
		time.sleep(20)
		for Entry in connections:
			Conn, Name, address, seat = Entry
			pingClient(Entry, Conn, Name)
		for Entry in Viewer_connections:
			Conn, Name, address, seat = Entry
			pingClient(Entry, Conn, Name)
def PrintPlayerList():
	print 'nn#Players#n'
	for Entry in connections:
		Conn, Name, address, seat = Entry
		IP_Address, SockID = address
		print Name, IP_Address+'   '+seat
	print 'nn#Viewers#n'
	for Entry in Viewer_connections:
		Conn, Name, address, seat = Entry
		IP_Address, SockID = address
		print Name, IP_Address

def ScoreListAndSend(throwdown):
	print 'nn#Player Scores#n'
	numTimes = 0
	PlayList = []
	print 'thowDown > ',throwdown
	for Entry in connections:
		Conn, Name, address, seat = Entry
		IP_Address, SockID = address
		seatNumIndex = int(seat) -1
		print 'This is the index: ',seatNumIndex
		User_Score = throwdown[seatNumIndex]
		print User_Score
		Out = '%s :  %s' % (Name,str(User_Score))
		PlayList.append(Out)
		numTimes +=1
	return PlayList

def fillPlayerInfoVarsAndAppendMainList(isStop):
	while isStop == 0:
		time.sleep(1)
		for Entry in init_player:
			Conn, Name, address, seat = Entry
			try:
				Conn.send('i:name')
			except:
				pass
			currtime = time.clock()
			start_time = time.clock()
			added_time = start_time + 8.00
			receivedMessageFromClient = 0

##stuff			
			while added_time > currtime:
				time.sleep(0.2)
				data = ''
				try:
					data = Conn.recv(1024)
				except:
					pass
				if data != '':
					VerbosePrint((data,Name,'   -In_initPlayer'))
					receivedMessageFromClient = 1
					break

				currtime = time.clock()
			if receivedMessageFromClient == 0:
				VerbosePrint(("Disconnecting",Name))
				Conn.close()
				try:
					init_player.remove(Entry)
				except:
					pass
			if receivedMessageFromClient == 1:
				try:
					init_player.remove(Entry)
				except:
					pass


				ReceivedMessage_sheared = data[2:]
				VerbosePrint(ReceivedMessage_sheared)
				SeatStats = GetSeatStatus()
				VerbosePrint(SeatStats)
				seat2SitIn = AllocatePlayerSeats(SeatStats)
				new_entry = (Conn,ReceivedMessage_sheared,address,seat2SitIn)
				takenName = GetNameStatus(ReceivedMessage_sheared)
				##print takenName
				if takenName == '1':
					Conn.send('m:"%s" already taken, please pick a different name' % ReceivedMessage_sheared)
					VerbosePrint('Name Taken')
					DisconnectClient(Conn)
				if takenName == '0':
					VerbosePrint('Name Not Taken')
					if seat2SitIn == '0':
						Conn.send('m:All seats filled; joining as a viewer')
						#add to viewer list
						Viewer_connections.append(new_entry)
					if seat2SitIn != '0':
						#add to player list
						Conn.send('m:Joining to seat %s' % seat2SitIn)
						connections.append(new_entry)

				VerbosePrint(connections)
				
#def isStillConnected(Conn):
#	connection.status = 0
#	connection.sock.close()

def MainStart(isStop, CheckIfWin):
	global isStartGame
	while isStop == 0:
	    if isStartGame == 0:
	        #wait and try again later
	        time.sleep(0.1)
	#        print "Still at 0, trying again"
		if isStartGame == 1:
			throwdown = ['', '', '', '', '']
			SendToAll('m:Waiting 8 seconds (tick, tick, etc.)')
			VerbosePrint("Waiting 8 seconds")
	##timer stuff
			currtime = time.clock()
			start_time = time.clock()
			added_time = start_time + 8.00
			while added_time > currtime:
				time.sleep(0.1)
				currtime = time.clock()        
				Rcv, Name, seat = Received
				if Rcv.startswith('g:'):
##					print 'adding "' + Rcv[2:] + '" to the list'
					throwdown.__setitem__((int(seat)-1),(heek_defs.decode(Rcv[2:3])))
			VerbosePrint(throwdown)
			score = heek_defs.score_round(throwdown)
			win = heek_defs.award_Score(score, throwdown)
			score2 = heek_defs.keep_match_score(win, match_scores)
			VerbosePrint(match_scores)
			VerbosePrint(win)
			PlayList = ScoreListAndSend(throwdown)
			print PlayList
			SendToAll('m:'+str(PlayList))
			SendToAll('m:MatchScores- >  '+str(match_scores))
			SendToAll('m:'+CheckIfWin())
			isStartGame = 0


#UI

print 'Welcome to the PyHeek server v. %sn Type "help" to list all commands' % Version

while 1:
	console = raw_input('HeekServer: ')

	
	if console == 'help':
		helpMessage = '''the availible commands are:

start        - starts the server
end          - ends the server(currently not working)
v+           - verbose mode
v-           - sets to normal mode
ping         - to ping all clients
kick '<user>'- kicks user
list         - prints a list of users currently on this server
status       - gets the current status of the server
help         - shows this message
'''
		print helpMessage

		
	if console == 'start':
		if Status == 'Server is running':
			print 'Server is already running'
		else:
			global match_scores	
			match_scores = [[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0]]
			print 'nServer v. %s starting...' % Version
			thread1 = threading.Thread( target=ConnectLoop, args=( isStop, Port) )
			thread1.start()
			print 'ConnectServe started'
			thread2 = threading.Thread( target=Receive5SeatedPlayerLoop, args=( isStop,) )
			thread2.start()
			print 'Receive started'
			thread3 = threading.Thread( target=fillPlayerInfoVarsAndAppendMainList, args=( isStop,) )
			thread3.start()
			print 'Welcome Serve started'
			thread4 = threading.Thread( target=pingAll, args=( isStop, pingClient) )
			thread4.start()
			print 'Ping Serve started'
			thread5 = threading.Thread( target=MainStart, args=( isStop, CheckIfWin) )
			thread5.start()
			print 'MainGameLogic started'
			print 'Server v.%s startedn' % Version
			
			Status = 'Server is running'

			
	if console == 'end':
		print 'currently not working'
#		if Status != 'Server is running':
#			print 'Server is already stopped'
#		else:
#			print 'nServer v. %s stopping...' % Version
#			isStop = 1
#			print 'Server v.%s stoppedn' % Version
#			Status = 'Server is currently not running'
#			isStop = 0
	if console == 'status':
		print Status
	if console == 'v+':
		if Status == 'Server is running':
			isVerbose = 1
			print 'set to verbose mode'
		else:
			print 'Server is not running, can not apply commands to it'

	if console == 'v-':
		if Status == 'Server is running':
			isVerbose = 0
			print 'set to normal mode'
		else:
			print 'Server is not running, can not apply commands to it'
	if console.startswith('kick '):
		if Status == 'Server is running':
			splitItem = console.split("'")
			user = splitItem[1]
			KickClient(user)
		else:
			print 'Server is not running, can not apply commands to it'
	if console == 'list':
		if Status == 'Server is running':
			PrintPlayerList()
		else:
			print 'Server is not running, can not apply commands to it'

test_client4.py
from socket import *
import string
import time
import thread
import heek_defs

Name = raw_input('Your Name: ')
ipAddr = raw_input('Server IP: ')

#this is like speed-dial
if ipAddr == '1':
    ipAddr = '192.168.1.47'

global RCVD
RCVD = ''
NadPort = 1813
Port = 5000

global sock
sock = socket(AF_INET, SOCK_STREAM)
sock.connect((ipAddr, NadPort))
##sock.send('Test')

def Recv_loop():
    while 1:
        time.sleep(0.2)
        global RCVD
        if RCVD == 'ping':
            sock.send('pong')
        RCVD = sock.recv(1024)
        if RCVD.startswith('m:'):
            print RCVD[2:]


thread.start_new_thread(Recv_loop,())

sentWelcomeMessage = 0
print 'Choose;  pen, page or beetle'
while 1:
    if sentWelcomeMessage == 1:
        input = raw_input('Input: ')
        encoded_input = heek_defs.encode(input)
        if encoded_input != '':
            sock.send('g:'+encoded_input)
    if RCVD == 'i:name' and sentWelcomeMessage == 0:
        print 'sending the Name'
        sock.send('i:%s' %(Name))
        sentWelcomeMessage = 1


heek_defs.py
import time
import md5

def CalcMd5(string):
    myMd5 = md5.new()
    myMd5.update(string)
    calcMd5 = myMd5.digest()
    return calcMd5


def decode(data1):
    if data1 == '1':
        return 'pen'
    if data1 == '2':
        return 'page'
    if data1 == '3':
        return 'beetle'
    else:
        return ''
        
def encode(data2):
    if data2 == 'pen':
        return '1'
    if data2 == 'page':
        return '2'
    if data2 == 'beetle':
        return '3'
    else:
        return ''

def score_round(throwdown):
	roundpointlist = []
	for play in throwdown:
		otherplays = throwdown[:]
		otherplays.remove(play)
		score = 0
		if play == 'pen':
			for each in otherplays:
				if each == 'page': score += 1
				elif each == 'beetle': score -= 1
				else: pass
		elif play == 'page':
			for each in otherplays:
				if each == 'beetle': score += 1
				elif each == 'pen': score -= 1
				else: pass
		elif play == 'beetle':
			for each in otherplays:
				if each == 'pen': score += 1
				elif each == 'page': score -= 1
				else: pass
		else: pass
		roundpointlist.append(score)
	return roundpointlist

def award_Score(roundpointlist,throwdown):
	highest = 0
	counter = 0
	winningplayers=[]
	winnings = ''
	for each in roundpointlist:
		if each > highest:
			highest = each
		else: pass
	for each in roundpointlist:
		if each == highest:
			winningplayers.append(counter)
		else: pass
		counter += 1
	for player in winningplayers:
		winnings = throwdown[player]
	win = [winningplayers, winnings]
	return win

def keep_match_score(win, match_scores):
	if win[1] == 'pen':
		for each in win[0]:
			match_scores[each][0] += 1
	if win[1] == 'page':
		for each in win[0]:
			match_scores[each][1] += 1
	if win[1] == 'beetle':
		for each in win[0]:
			match_scores[each][2] += 1

Posted in: Code by nsundin
Copyright © 2011-2025 Programmatic Verse · RSS Feed
Built on Skeleton
Powerered by Wordpress