work_5
第五次作业对我个人来说是很难的,因为之前没怎么接触过这方面的内容,有幸能跟宗毅组成一队,我也仔细看了他的Python代码,因为对于Python也是第一次接触,所以我感觉在有限的时间里学会并且灵活运用还是很困难的,所以虽然付出了一些努力,还是一直处于学习的状态,没有得到想象中的结果,但是也理清了思路,实践了一些东西,还是很有收获,我相信通过我的努力一定会越来越好。下面附上代码和截图:
服务器程序:
# -*- coding: utf-8 -*-
import socket
import thread
import random
import hashlib
import urllib, urlparse
import time connLock = 0
def sendMsg(conn, msg):
global connLock
while connLock == 1:
continue
connLock = 1
conn.send(msg)
connLock = 0 class player():
username = ''
token = ''
point = 0
guess = 0
conn = None
timeoutCount = 0
def __init__(self, username, conn):
self.username = username
self.token = hashlib.md5(str(random.randint(1, 2**256))).hexdigest()
self.point = 0
self.timeoutCount = 0
self.conn = conn
def getToken(self):
return self.token
def win(self):
self.point = self.point + 10
def lose(self):
self.point = self.point - 5
def timeout(self):
self.point = self.point - 10
self.timeoutCount = self.timeoutCount + 1
def submit(self, guess):
self.guess = guess
def getGuess(self):
return self.guess
def getUsername(self):
return self.username
def getPoint(self):
return self.point
def newRound(self, timeout, count):
req = {
'cmd': 'newround',
'count': count,
'timeout': str(timeout),
'yourpoint': str(self.getPoint())
}
sendMsg(conn, urllib.urlencode(req)) class game():
roundTime = 30
lastWinner = ''
lastLosers = []
lastG = 0
players = []
waiting = 0
roundCount = 0
def __init__(self):
self.roundTime = 5
def newRound(self):
print 'users:'
for i in self.players:
print i.getUsername(), i.point
#compute G
self.waiting = 0
i = [i.getGuess() for i in self.players]
if len(i) != 0:
self.lastG = sum(i)*0.618/len(i)
if len(self.players) > 0:
minabs = abs(self.players[0].getGuess() - self.lastG)
maxabs = abs(self.players[0].getGuess() - self.lastG)
#calculate winner point
for i in self.players[1:]:
#calculate timeouts
if i.getGuess == 0:
i.timeout()
if i.timeoutCount >= 3:
players.remove(i)
continue
if abs(i.getGuess() - self.lastG) < minabs:
self.lastWinner = i.getUsername()
minabs = abs(i.getGuess() - self.lastG)
if abs(i.getGuess() - self.lastG) > maxabs:
maxabs = abs(i.getGuess() - self.lastG)
i.guess = 0
#calculate losers
self.lastLosers = [i.getUsername for i in self.players if abs(i.getGuess() - self.lastG) == maxabs]
#add or minus points
self.roundCount = self.roundCount + 1
for i in self.players:
if i.getUsername() == self.lastWinner:
i.win()
elif i.getUsername() in self.lastLosers:
i.lose()
i.newRound(self.roundTime, self.roundCount)
self.waiting = 1
def newPlayer(self, username, conn):
t = player(username, conn)
self.players.append(t)
return t def getPara(d, p):
if d.has_key(p):
return d[p][0]
return None
def dealWithClient(conn, g):
p = None
while True:
buf = conn.recv(1024)
d = urlparse.parse_qs(buf)
cmd = getPara(d, 'cmd')
if (cmd == 'newplayer'):
username = getPara(d, 'username')
p = g.newPlayer(username, conn)
req = {
'cmd': 'confirmplayer',
'username': username,
'token': p.getToken()
}
sendMsg(conn, urllib.urlencode(req))
elif (cmd == 'submit'):
point = int(getPara(d, 'point'))
print 'submit from ',p.getUsername(), 'point=',point
p.submit(point)
req = {
'cmd': 'confirmsubmit',
'point': point
}
sendMsg(conn, urllib.urlencode(req))
elif (cmd == 'query'):
yourpoint = str(p.getPoint())
lastg = str(g.lastG)
lastwinner = g.lastWinner
req = {
'cmd': 'confirmquery',
'yourpoint': yourpoint,
'lastg': lastg,
'lastwinner': lastwinner
}
sendMsg(conn, urllib.urlencode(req)) def timer(g):
while True:
timeout = g.roundTime
time.sleep(timeout)
g.newRound() if __name__ == '__main__':
g = game()
thread.start_new_thread(timer, (g, ))
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('localhost', 9210))
sock.listen(5)
while True:
conn,address = sock.accept()
print 'New client connected.'
thread.start_new_thread(dealWithClient, (conn, g))
server
客户端程序:
# -*- coding: utf-8 -*- import urllib, urlparse
import thread
import socket
import time class player:
username = ''
token = ''
point = 0
guess = 0
conn = None
timeout = 0
roundCount = 0
def __init__(self, conn):
self.username = ''
self.token = ''
self.point = 0
self.guess = 0
self.conn = conn
def submit(self, guess):
req = {
'cmd': 'submit',
'point': str(guess)
}
self.conn.send(urllib.urlencode(req))
def query(self):
req = {
'cmd': 'query'
}
self.conn.send(urllib.urlencode(req))
def newPlayer(self, username):
req = {
'cmd': 'newplayer',
'username': username
}
self.conn.send(urllib.urlencode(req)) def getPara(d, p):
if d.has_key(p):
return d[p][0]
return None def dealWithServer(conn, p):
while True:
buf = conn.recv(1024)
d = urlparse.parse_qs(buf)
cmd = getPara(d, 'cmd')
if cmd == 'newround':
timeout = getPara(d, 'timeout')
count = getPara(d, 'count')
yourpoint = getPara(d, 'yourpoint')
p.timeout = int(timeout)
p.roundCount = int(count)
p.point = int(yourpoint)
print 'newround, timeout:',timeout
elif cmd == 'confirmplayer':
username = getPara(d, 'username')
token = getPara(d, 'token')
p.username = username
p.token = token
print 'confirmplayer'
elif cmd == 'confirmsubmit':
point = getPara(d, 'point')
p.guess = point
print 'confirm submit'
elif cmd == 'confirmquery':
yourpoint = int(getPara(d, 'yourpoint'))
lastg = getPara(d, 'lastg')
lastwinner = getPara(d, 'lastwinner')
p.point = yourpoint
print 'Query result:\nyourpoint:', yourpoint, '\nlastG:', lastg, '\nlastWinner:', lastwinner, '\n' if __name__ == '__main__':
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('localhost', 9210))
p = player(sock)
thread.start_new_thread(dealWithServer, (sock, p))
while True:
time.sleep(1)
print '1. newplayer\n2.submit\n3.query'
cmd = raw_input('choice:')
if cmd == '':
username = raw_input('username:')
p.newPlayer(username)
if cmd == '':
point = raw_input('point:')
p.submit(int(point))
if cmd == '':
p.query()
client
代码还在完善当中,包括用户界面,黄金点曲线等等,有了改动我会继续上传到Github和博客中。
work_5的更多相关文章
- Java常用工具类练习题
1.请根据控制台输入的特定日期格式拆分日期 如:请输入一个日期(格式如:**月**日****年) 经过处理得到:****年**月**日 提示:使用String的方法indexOf.lastIndexO ...
- .NET下集中实现AOP编程的框架
一.Castle 使用这个框架呢,首先是需要安装NuGet包. 先建立一个控制台项目,然后在NuGet中搜索Castle.Windsor,不出意外的话应该能找到如下的包 然后安装,会自动的安装包Cas ...
随机推荐
- YUV到RGB的转换
以下内容来源于网络,下面三个链接里的内容是比较好的,感谢博主的分享. http://blog.csdn.net/housisong/article/details/1859084 http://blo ...
- Ubuntu使用总结
错误 鼠标闪烁解决 系统设置->显示—>未知显示器->关闭->应用->选择当前配置 提示sudo: unable to resolve host ,亦即无法解析主机. 原 ...
- git终端提示符
最近使用git bash的时候,看到默认的终端提示符不爽,主要是太长了.所以想对git终端提示符进行优化 默认git的终端提示符会是 用户名@设备名称 ,我想改成更短的来查看. 提示符是由一个环境变 ...
- mysql定时计划任务,ON COMPLETION [NOT] PRESERVE 当单次计划任务执行完毕后或当重复性的计划任务执行到了ENDS阶段。而声明PRESERVE的作用是使事件在执行完毕后不会被Drop掉
当为on completion preserve 的时候,当event到期了,event会被disable,但是该event还是会存在当为on completion not preserve的时候,当 ...
- 如何使用 Java 测试 IBM Systems Director 的 REST API
转自: http://www.ibm.com/developerworks/cn/aix/library/au-aix-systemsdirector/section2.html 如何使用 Java ...
- Codeforces Round #259 (Div. 2) C - Little Pony and Expected Maximum
题目链接 题意:一个m个面的骰子,抛掷n次,求这n次里最大值的期望是多少.(看样例就知道) 分析: m个面抛n次的总的情况是m^n, 开始m==1时,只有一种 现在增加m = 2, 则这些情况是新增 ...
- HDU 4906 状态压缩dp
Our happy ending Time Limit: 6000/3000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Other ...
- bzoj1486: [HNOI2009]最小圈
二分+dfs. 这道题求图的最小环的每条边的权值的平均值μ. 这个平均值是大有用处的,求它我们就不用记录这条环到底有几条边构成. 如果我们把这个图的所有边的权值减去μ,就会出现负环. 所以二分求解. ...
- Flexigrid自定义显示数据列
近期在搞ExtJs,发现ExJs的Grid相当的强大,后来又搞Jquery时,就对原来的表格不怎么满意了,于是,花了点时间,从网上找了个Grid插件,这个插件功能是比较强大,什么行排序.筛选.分页都有 ...
- CodeForces Round #279 (Div.2)
A: 题意: 有三个项目和n个学生,每个学生都擅长其中一个项目,现在要组成三个人的队伍,其中每个人恰好擅长其中一门,问能组成多少支队伍. 分析: 最多能组成的队伍的个数就是擅长项目里的最少学生. #i ...