抓阄的游戏脚本


之前看oldboy的博客时看到的一道题目,虽然当时我没有做,但是收集了在文章评论中比较好的shell/Python脚本,然后自己经过修改、调试,整理出了下面的6个脚本,比较好玩,就分享出来了:

需要一个抓阄的程序,要求:
1、执行脚本后,输入用户名,随机产生01-99之间的数字,前面已经抓到的数字,下次不能再出现
2、第一个输入用户名后,屏幕输出信息,并将名字和数字记录到文件里,程序不能退出,继续等待别的学生输入


参考答案:
1.考虑得相当细致的shell脚本
#!/bin/bash

read -p "Please enter your name:" -t 10 name
if [ $? -ne 0 ]
then
	echo -e "n!!!!!!Enter is timeout!!!!!!"
	exit 1
fi

touch temp result
cat /dev/null > result	#存放最后的结果,格式为:$name is $number
cat /dev/null > temp	#存放临时的结果,每行内容均为:$number

while true
do
	#if [ $(grep ^$name result | wc -l) -ge 1 ]	#这里的grep判断有误,比如:输入了haha之后就无法输入用户名h
	if [ $(grep ^b$nameb result | wc -l) -ge 1 ]	#添加b锚定单词
	then
		echo "The name already exists."
	fi
	if [ "$name" == "exit" ]
	then
		rm temp -f
		echo "******************************"
		echo "The result of the top three:"
		sort -k3rn result | head -3		# sort的各种选项需要好好学习
		echo "******************************"
		exit 1
	fi
	if [ -z $name ]		# 这个判断流程的选择可以好好思考思考!
		then
		echo "Your name is null."
		read -p "Please enter your name:"
	fi
	number=$(($RANDOM%99+1))	#需要注意空格的使用
	if [ $(grep "^$number$" temp | wc -l) -eq 0 ] && [ $(grep ^$name result|wc -l) -eq 0 ];then
		echo "$name is $number" >> result
		echo "$name is $number"
		echo $number >> temp
		if [ $(cat temp|wc -l) -ge 99 ];then	#考虑的真是够细致的!
			echo -e "The number out of range.n exit!!!"
			rm temp -f
			echo "******************************"
			echo "The result of the top three:"
			sort -k3rn result|head -3
			echo "******************************"
			exit 1
		fi
	fi
	echo "Enter 'exit' end the process!"
	read -p "Please enter your name:" -t 10 name
	if [ $? -ne 0 ]
	then
		echo -e "n!!!!!!Enter is timeout!!!!!!!"
		echo "******************************"
		echo "The result of the top three:"
		sort -k3rn result|head -3
		echo "******************************"
		exit 1
	fi
	sleep 0.1
done
2.比较简单的Python脚本,有很多问题没有考虑
#!/usr/bin/env python
#coding=utf-8
import random
running = True
while running:
	name = raw_input('name:')
	if not name:
		break
	print name
	a = range(1,99)
	slice = random.sample(a, 1)  #Python的random.sample()从指定序列中随机获取指定长度{第二个参数}的片段
	for i in slice:		#这里没有进行重复与否的判断
		num = str(i)
		print num
	f = open('/tmp/user', 'a')
	f.write(name + ":::" + num + "n")
	f.close
3.比较简单的Python脚本(只管录入不管别的)
#!/usr/bin/env python
#coding=utf-8
import random
import ConfigParser

scores = {}

def saveScore():
	config = ConfigParser.RawConfigParser()
	#config.read('score.cfg')
	config.add_section('score')
	for k, v in scores.items():
		config.set('score', k, v)	#使用set设置k,v值
	with open('score.cfg', 'wb') as configfile:
		config.write(configfile)
	config = None

username = raw_input('请输入姓名:')
while username:
	if username and not scores.has_key(username):
		score = random.randint(1, 99)
		scores[username] = score
		print('名字:%s, 得分:%s' % (username, score))
		saveScore()
	else:
		print('请输入正确的名字, 或者名字已经存在 n')
	username = raw_input('请输入姓名:')
4.有保存功能的Python脚本
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import random, pickle, os, sys

def load():
	f = open('list.txt', 'r')
	global list
	list = pickle.load(f)
	return list
	f.close()
def save():
	f = open('list.txt', 'w')
	pickle.dump(list, f)
	f.close()
def leave(x):
	print ""
	print "%sThe TOP Three is:" % x
	print 'ID   NAME'
	print '-----------------------'
	for i in list2[-4:-1]:	#取列表中最后的3个元素{前面使用了sort函数对列表进行了排序}
		print '%s   %s'%(i, list1[i])
	print '-----------------------'

if not os.path.exists('list.txt'):
	f = open('list.txt', 'w')
	aa = {'id':'name'}
	pickle.dump(aa, f)
	f.close()
try:
	while True:
		digint = random.randrange(01, 100)
		list1 = load()
		list2 = list1.keys()
		list2.sort()
		inpu = raw_input("Please input you English name:").strip()
		if (list2.index(list2[-1]) == 100) or (inpu == 'exit'):
			leave("Now come to the end, ")
			sys.exit()
		if len(inpu) == 0:
			print "don't empty, please input again"
			continue
		list1 = load()
		if inpu in list1.values():
			print "system have it's name, please change"
			continue
		else:
			while digint in list1:
				digint = random.randrange(01, 100)
				continue
			else:
				list1[digint] = inpu
				print "%s's id is %s"%(inpu, digint)
				save()
except KeyboardInterrupt:
	list1 = load()
	list2 = list1.keys()
	list2.sort()
	leave("")
5.虽然简单但功能挺全的shell脚本
#!/bin/bash

[ ! -f file ] && touch file
while true;
do
	read -p '输入:' you
	if [ "$you" == 'exit' ];then
		break
	fi
	if [ -n "$you" ] && ! egrep "^$you.*" file;then
		while true;
		do
			rannum=$(expr $RANDOM % 99 + 1)
			if ! egrep "$you number is $rannum" file ;then
				echo "$you number is $rannum" | tee -a file
				break
			fi
		done
	fi
done
6.功能非常全的shell脚本
#!/bin/bash

#整个流程就是:
#判断输入内容,分为:Null|quit|sort|clear|参与者名字
#当输入正常时,再判断文件大小是否为0,若为0则直接输入;否则根据已有内容判断用户名是否已存在
echo "   ##################################################################"
echo "   #  Interesting companies shell practical programming problem	#"
echo "   ##################################################################"
echo "   #   You Can Use :  'quit' to exit shell scripts				#"
echo "   ##################################################################"
echo "   #   'sort' to sort the order in result file					#"
echo "   ##################################################################"
txt=temp.txt
touch "$txt"
while(true);do
read -p "   #Please input your name : " name
if [ "$name" == "" ];then
	echo "   #WARNING: Username should not be empty! "
elif [ "$name" == "quit" ];then
	exit 0
elif [ "$name" == "sort" ];then
	cat temp.txt | sort -n	#这个貌似没有起到排序的作用?
elif [ "$name" == "cl" ] || [ "$name" == "clear" ] ;then
	clear
else
	if [ -s "$txt" ];then	#文件大小非0时为真
		a=`grep -w "$name" "$txt" | wc -l`
		if [ "$a" -gt 0 ];then	#当已存在时,则会给出提示-显示已有内容并退出当前循环
			echo "   #WARNING: name as $name is existing"
			echo -n "   ";grep -w "$name" "$txt"
			continue
		else
			declare -i num=$RANDOM%99+1		#-i选项会把"num"当作整数看待
			b=`grep -w "$num" "$txt" |wc -l`
			if [ "$b" -gt 0 ];then
				continue
			else
				echo -e "$numt$name">>$txt	#存入文件的格式
				echo -n "   ";grep -w "$name" "$txt"
			fi
		fi
	else	#当文件大小为0时,表示是第1次进行,直接写入结果即可
		declare -i num=$RANDOM%99+1
		echo -e "$numt$name" >>$txt
		echo -n "   ";grep -w "$name" "$txt"
	fi
fi
done

 

参考链接:

http://oldboy.blog.51cto.com/2561410/1308647

, ,

《“抓阄的游戏脚本”》 有 1 条评论

  1. 一个逗比写的各种逗比脚本~
    https://github.com/ToyoDAdoubi/doubi
    `
    ssr.sh 脚本说明: ShadowsocksR 一键安装/管理脚本,支持单端口/多端口切换和管理
    ssrmu.sh 脚本说明: ShadowsocksR 一键安装/管理脚本,支持流量控制
    ssr_check.sh 脚本说明: ShadowsocksR 批量快速验证账号可用性
    ssrstatus.sh 脚本说明: ShadowsocksR 账号在线监控网站
    aria2.sh 脚本说明: Aria2 一键安装脚本
    `

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注