学生随机点名程序


代码托管地址(svn-checkout):

http://student-call.googlecode.com/svn/trunk/

作者水平有限,欢迎高手们指点迷津。


功能描述:

1.导入班级名单(excel)

2.随机生成两个学生(当前的和下一个的)

3.对当前的学生进行星级评价

4.评价过的学生加入右侧的历史记录栏

5.保存历史记录到本地


编程语言:C#



主要算法也就是随机算法:

1.先随机产生两个人

2.从两个人中选择一个被点到次数较少的一个(增加一定公平性)


最终界面效果图:




代码清单:



模型类:

学生

using System;

namespace stdCall.Models
{
    /// 
    /// 学生模型类:姓名,学号,被点名次数
    /// 
    class Student
    {
        private String name;
        private String number;
        private int unluckyCallNum;
       /* private String message;*/

        public int UnluckyCallNum
        {
            get { return unluckyCallNum; }
            set { unluckyCallNum = value; }
        }
     
        public Student(String number, String name)
        {
            this.name = name;
            this.number = number;
        }

        public Student(String number, String name ,int unluckyCallNum)
        {
            this.name = name;
            this.number = number;
            this.unluckyCallNum = unluckyCallNum;
        }

        public String Number
        {
            get { return number; }
            set { number = value; }
        }

        public String Name
        {
            get { return name; }
            set { name = value; }
        }

        public String getMessage()
        {
            return (number + "," + name);
        }

 
    }
}

点名模型

using System;

namespace stdCall.Models
{
    /// 
    /// 点名模型类:id,学生号,星级,课程号
    /// 
    class UnluckyCall
    {
        private String id;
        private String studentid;
        private int star;
        private int courseID;

        public UnluckyCall()
        {
            id = "";
            studentid = "";
            star = 0;
            courseID = 0;
        }

        public UnluckyCall(String id, String studentid, int star, int courseNum)
        {
            this.id = id;
            this.studentid = studentid;
            this.star = star;
            this.courseID = courseNum;
        }

        public UnluckyCall( String studentid, int star, int courseNum)
        {
            this.studentid = studentid;
            this.star = star;
            this.courseID = courseNum;
        }

        internal String Studentid
        {
            get { return studentid; }
            set { studentid = value; }
        }

        public int Star
        {
            get { return star; }
            set { star = value; }
        }

        public int CourseID
        {
            get { return courseID; }
            set { courseID = value; }
        }

        public String Id
        {
            get { return id; }
            set { id = value; }
        }

        /// 
        /// 获得模型类的信息
        /// 
        /// 
        public String getMessage()
        {
            return ("id:" + id + ",studentid:" + studentid + ",star:" + star.ToString() + ",courseID:" + courseID.ToString() + "");
        }
    }
}


模型管理类:

学生管理

using stdCall.MyUtils;
using System;
using System.Collections;

namespace stdCall.Models
{
    /// 
    /// 学生管理类,学生表为静态Hash表
    /// 
    class StudentsManager
    {
        private static Hashtable students = new Hashtable();

        public static Hashtable Students
        {
            get { return StudentsManager.students; }
            set { StudentsManager.students = value; }
        }

        /// 
        /// 根据学号获取学生
        /// 
        /// 
        /// 
        public Student getStudentByNum(String studentNum)
        {
         //   Student student=null;

            return (Student)students[studentNum];
        }

        /// 
        /// 获取所有学生,返回排序后的ArrayList
        /// 
        /// 
        public ArrayList getAllStudents()
        {
            ArrayList stds = new ArrayList();
            foreach (DictionaryEntry de in students)
            {
                stds.Add((Student)(de.Value));
            }
            stds.Sort(new StudentCompare());
            return stds;
        }

        /// 
        /// 添加一个学生
        /// 
        /// 
        /// 
        public void addStudent(String studentNum , String name)
        {
            students.Add(studentNum, new Student(studentNum, name));
        }

        /// 
        /// 添加一个学生
        /// 
        /// 
        /// 
        /// 被点名次数
        public void addStudent(String studentNum, String name,int unluckyNum)
        {
            students.Add(studentNum, new Student(studentNum, name, unluckyNum));
        }
      
// 
//         public Student getAPoorStdFairly()
//         {
//             Student student = null;
// 
//             return student;
//         }


//         public bool loadStudents()
//         {
//             bool flag = false;
//             return flag;
//         }

    }
}


点名模型管理

using System;
using System.Collections;

namespace stdCall.Models
{
    /// 
    /// 点名模型管理器,点名表unluckyCalls为静态
    /// 
    class UnluckyCallsManager
    {
        private static Hashtable unluckyCalls = new Hashtable();
        private static int callid = 0;

        public static Hashtable UnluckyCalls
        {
            get { return UnluckyCallsManager.unluckyCalls; }
            set { UnluckyCallsManager.unluckyCalls = value; }
        }

        /// 
        /// 根据学生号获取点名次数
        /// 
        /// 
        /// 点名次数
        public int getCallNumByStdNum(String studentnum){
            int num = 0;
            foreach (DictionaryEntry de in unluckyCalls)
            {
                UnluckyCall uc = (UnluckyCall)de.Value;
                if (uc.Studentid.Equals(studentnum))
                {
                    num++;
                }
            }
            return num;
        }

        /************************************************************************/
        /* bug                                                                     */
        /************************************************************************/
        public ArrayList getCallsByStdNum(String studentnum){
            ArrayList unluckycalls = new ArrayList();
            foreach (DictionaryEntry de in unluckyCalls)
            {
                UnluckyCall uc = (UnluckyCall)de.Value;
                if (uc.Studentid.Equals(studentnum))
                {
                    unluckycalls.Add(uc);
                }
            }
            return unluckycalls;
        }

        /// 
        /// 根据课程号获取点名的学生列表
        /// 
        /// 
        /// 学生列表
        public ArrayList getPoolStdsByCourseID(int courseid)
        {
            ArrayList students = new ArrayList();
            foreach (DictionaryEntry de in unluckyCalls)
            {
                UnluckyCall uc = (UnluckyCall)de.Value;
                if (uc.CourseID==courseid)
                {
                    students.Add(new StudentsManager().getStudentByNum(uc.Studentid));
                }
            }
            return students;
        }

        /************************************************************************/
        /* BUG                                                                     */
        /************************************************************************/
        /// 
        /// BUG,未实现
        /// 
        /// 
        /// 
        /// 
        public int getStarBySNumCID(String studentnum,int courseid)
        {
            String id = getCallID();
            return ((UnluckyCall)unluckyCalls[id]).Star;
        }

        /// 
        /// 添加一个点名
        /// 
        /// 
        /// 
        /// 
        public void addUnluckyCall(String studentNum ,int star, int courseID)
        {
            String id = getCallID();
            unluckyCalls.Add(id, new UnluckyCall(id, studentNum, star, courseID));
        }
// 
//         public bool loadUnluckyCalls()
//         {
//             bool flag = false;
//             return flag;
//         }

        /// 
        /// 获取点名ID
        /// 
        /// 
        public String getCallID()
        {
            callid++;
            return callid.ToString();
        }


      
    }
}


读取excel的类(可重用)

using System;
using System.Collections.Generic;
using Excel = Microsoft.Office.Interop.Excel;

namespace stdCall.MyExcel
{
    /// 
    /// Excel读取类
    /// 
    class ExcelHelper
    {
        private Excel._Application excelApp;
        private string fileName = string.Empty;
        private Excel.WorkbookClass wbclass;
        public ExcelHelper(string _filename)
        {
            excelApp = new Excel.Application();
            object objOpt = System.Reflection.Missing.Value;
            wbclass = (Excel.WorkbookClass)excelApp.Workbooks.Open(_filename, objOpt, false, objOpt, objOpt, objOpt, true, objOpt, objOpt, true, objOpt, objOpt, objOpt, objOpt, objOpt);
        }
        /// 
        /// 所有sheet的名称列表
        /// 
        /// 
        public List GetSheetNames()
        {
            List list = new List();
            Excel.Sheets sheets = wbclass.Worksheets;
            string sheetNams = string.Empty;
            foreach (Excel.Worksheet sheet in sheets)
            {
                list.Add(sheet.Name);
            }
            return list;
        }
        /// 
        /// 获取sheet表
        /// 
        /// 
        /// 
        public Excel.Worksheet GetWorksheetByName(string name)
        {
            Excel.Worksheet sheet = null;
            Excel.Sheets sheets = wbclass.Worksheets;
            foreach (Excel.Worksheet s in sheets)
            {
                if (s.Name == name)
                {
                    sheet = s;
                    break;
                }
            }
            return sheet;
        }
        /// 
        /// 获取sheetName的所有内容
        /// 
        /// sheet名称
        /// 
        public Array GetContent(string sheetName)
        {
            Excel.Worksheet sheet = GetWorksheetByName(sheetName);
            //获取A1 到AM24范围的单元格
            Excel.Range rang = sheet.get_Range("A1", "B200");
            //读一个单元格内容
            //sheet.get_Range("A1", Type.Missing);
            //不为空的区域,列,行数目
            //   int l = sheet.UsedRange.Columns.Count;
            // int w = sheet.UsedRange.Rows.Count;
            //  object[,] dell = sheet.UsedRange.get_Value(Missing.Value) as object[,];
            System.Array values = (Array)rang.Cells.Value2;
            // double d=(double)values.GetValue(1,1);
            return values;
        }

        /// 
        /// 关闭文件
        /// 
        public void Close()
        {
            excelApp.Quit();
            excelApp = null;
        }

    }
}

读取excel并导入文本文件的类

using stdCall.File;
using stdCall.MyExcel;
using stdCall.Resource;
using stdCall;
using System;
using System.Windows.Forms;

namespace stdCall.MyExcel
{
    /// 
    /// 提供导入excel模块的服务
    /// 
    class ExcelService
    {
        ExcelHelper excelHelper ;
        /// 
        /// 倒入excel主函数
        /// 
        /// 
        public bool loadExcel(){
            bool flag = false;
            try
            {
                OpenFileDialog ofd = new OpenFileDialog();                //new一个方法
                ofd.Filter = "excel文件(*.xls)|*.xls|所有文件(*.*)|*.*";
                //  ofd.InitialDirectory = Environment.GetFolderPath_r(Environment.SpecialFolder.MyDocuments); //定义打开的默认文件夹位置
                ofd.ShowDialog();
                if (ofd.FileName == null || ofd.FileName == "") return false;
                excelHelper = new ExcelHelper(ofd.FileName);
                FileHelper fileHelper = new FileHelper();
                fileHelper.openWriteFile(ResourseLoader.FileSTDSPath, false);
                Array stds = excelHelper.GetContent("Sheet1");
                excelHelper.Close();
                int y = 1;
                do
                {
                    String stdnum = (stds.GetValue(y, 1)).ToString();
                    fileHelper.writeSingleData(stdnum);
                    String stdname = stds.GetValue(y, 2).ToString().Trim();
                    fileHelper.writeSingleData(stdname);
                    y++;
                } while (stds.GetValue(y, 1) != null);
                fileHelper.closeFile();
                flag = true;
            }
            catch (System.Exception ex)
            {
                flag = false;
            }
            return flag;
        }
    }
}



读写文件类(可重用)

using System;
using System.IO;
using System.Windows.Forms;

namespace stdCall.File
{
    /// 
    /// 文本文件读写类,File为静态类
    /// 
    class FileHelper
    {
        private static StreamReader readFile;
        private static StreamWriter writeFile;

        public static StreamReader ReadFile
        {
            get { return FileHelper.readFile; }
            set { FileHelper.readFile = value; }
        }

        public static StreamWriter WriteFile
        {
            get { return FileHelper.writeFile; }
            set { FileHelper.writeFile = value; }
        }

        /// 
        /// 打开读文件,未确认是否关闭
        /// 
        /// 
        /// 
        public  bool openReadFile(String filepath)
        {
            bool flag = false;
            try
            {
                readFile = new StreamReader(filepath);
                flag = true;
            }
            catch (System.Exception ex)
            {
                Console.Write(ex.Message);
            }
            return flag;
        }

        /// 
        /// 打开写文件,未确认是否关闭,默认添加内容到尾部
        /// 
        /// 
        /// 
        public bool openWriteFile(String filepath)
        {
            bool flag = false;
            try
            {
                writeFile = new StreamWriter(filepath,true);
                flag = true;
            }
            catch (System.Exception ex)
            {
                Console.Write(ex.Message);
            }
            return flag;
        }

        /// 
        /// 打开写文件,可选择是否覆盖
        /// 
        /// 
        /// false为覆盖
        /// 
        public bool openWriteFile(String filepath,bool apendFlag)
        {
            bool flag = false;
            try
            {
                writeFile = new StreamWriter(filepath, apendFlag);
                flag = true;
            }
            catch (System.Exception ex)
            {
                Console.Write(ex.Message);
            }
            return flag;
        }

        /// 
        /// 确认是否关闭,并关闭文件
        /// 
        /// 
        public  bool closeFile()
        {
            bool flag = false;
            try
            {
                if (readFile != null)
                {
                    readFile.Close();
                }
                if (writeFile != null)
                {
                    writeFile.Close();
                }
                flag = true;
            }
            catch (System.Exception ex)
            {
                Console.Write(ex.Message);
                flag = false;
            }
            return flag;
        }

        /// 
        /// 读取一行数据
        /// 
        /// 
        public  String readSingleData()
        {
            String data = null;
            try
            {
                if (!ReadFile.EndOfStream)
                {
                    data=readFile.ReadLine().Trim();
                }
            }
            catch (System.Exception ex)
            {
                Console.Write(ex.Message);
            }
            return data;
        }

        /// 
        /// 写入一行数据
        /// 
        /// 
        /// 
        public  bool writeSingleData(String data)
        {
            bool flag = false;
            try
            {
                writeFile.WriteLine(data);
                flag = true;
            }
            catch (System.Exception ex)
            {
                Console.Write("writeSingleData:" + ex.Message);
                ThreadExceptionDialog warnDialog = new ThreadExceptionDialog(ex);
                warnDialog.ShowDialog();
                flag = false;
            }
            return flag;
        }
    }
}


读取文件并转换为模型的类

using stdCall.File;
using stdCall.Models;
using stdCall;
using System;
using System.Windows.Forms;

namespace stdCall.Resource
{
    /// 
    /// 资源加载类,包含名单和点名的文本文件路径(静态)
    /// 
    class ResourseLoader
    {
        private StudentsManager studentManager = new StudentsManager();
        private UnluckyCallsManager unluckyCallsManager = new UnluckyCallsManager();
        private static  String fileSTDSPath = @".\students.txt";
        private static String fileCourseIDPath = @".\course.txt";
   /*     public static Hashtable static_controls = new Hashtable();*/


        public static String FileCourseIDPath
        {
            get { return ResourseLoader.fileCourseIDPath; }
            set { ResourseLoader.fileCourseIDPath = value; }
        }

        public static String FileSTDSPath
        {
            get { return ResourseLoader.fileSTDSPath; }
        }

        private static  String fileUCSPath = @".\unluckycalls.txt";

        public static String FileUCSPath
        {
            get { return ResourseLoader.fileUCSPath; }
        } 

        private FileHelper fileHelper = new FileHelper();
        public static int CourseID = 0;


        /// 
        /// 加载所有系统资源(学生列表,点名历史,课程ID)
        /// 
        public void loadSystemResourse()
        {
            loadUnluckyCalls();
            loadStudents();
        }

        /// 
        /// 加载学生表
        /// 
        public void loadStudents()
        {
            fileHelper.openReadFile(fileSTDSPath);
            while (!FileHelper.ReadFile.EndOfStream)
            {
                String stdNum = fileHelper.readSingleData();
                String stdName = fileHelper.readSingleData();
                new StudentsManager().addStudent(stdNum,stdName,new UnluckyCallsManager().getCallNumByStdNum(stdNum));
            }
            fileHelper.closeFile();
        }

        /// 
        /// 加载点名历史表
        /// 
        public void loadUnluckyCalls()
        {
            fileHelper.openReadFile(fileUCSPath);
            while (!FileHelper.ReadFile.EndOfStream)
            {
                String stdNum = fileHelper.readSingleData();
                String star = fileHelper.readSingleData();
                String courseID = fileHelper.readSingleData();

                new UnluckyCallsManager().addUnluckyCall(stdNum, int.Parse(star), int.Parse(courseID));
            }
            fileHelper.closeFile();
        }

        /// 
        /// 加载课程ID,未实现
        /// 
        public void loadCourseID()
        {
          /*  CourseID = 2;*/
            fileHelper.openReadFile(fileCourseIDPath);
            CourseID = int.Parse(fileHelper.readSingleData().Trim())+1;
            fileHelper.closeFile();
        }


        /// 
        /// 设置此堂课程编号
        /// 
        /// 
        public void setCourseID(int courseid)
        {
            CourseID = courseid;
            FileHelper fh = new FileHelper();
            fh.closeFile();
            fh.openWriteFile(ResourseLoader.FileCourseIDPath,false);
            try
            {
                fh.writeSingleData(courseid.ToString());
            }
            catch (System.Exception ex)
            {
                ThreadExceptionDialog warnDialog = new ThreadExceptionDialog(ex);
                warnDialog.ShowDialog();
            }
            fh.closeFile();
        }


    }
}


随机算法模块:

服务类

using stdCall.MyAnimate;
using stdCall.Models;
using stdCall;

namespace stdCall.MyRandom
{
    /// 
    /// 提供核心随机服务
    /// 
    class RandomService
    {
        public static Student currentStudent;
        public static Student nextStudent;
        private StudentsManager studentManager = new StudentsManager();

        /// 
        /// 点击random按钮触发,随机主函数,包括动画
        /// 先做当前学生Label的动画(做 AnimateService.animateNum次:获取随机学生,进行动画)
        /// 再做下一个学生Label的动画(做 AnimateService.animateNum次:Service.getAnimateService().animateNextResulted())
        /// 
        public void startRandom(){
            AnimateService animateService = new AnimateService();
            Student std = null;
            int num = AnimateService.animateNum;
            System.Collections.ArrayList stds = studentManager.getAllStudents();
            for (int i = 0; i < num; i++)
            {
                std = Caculator.getAPoorStdNum(stds);
                animateService.animateCurrentStd(std, i);
            }
            RandomService.currentStudent = std;
            RandomService.nextStudent=animateService.animateNextAndReturnStd();
        }
    }
}

具体算法实现类

using stdCall.Models;
using System;
using System.Collections;

namespace stdCall.MyRandom
{
    /// 
    /// 核心算法类
    /// 
    class Caculator
    {
        public static int RandomStdNum = 2;

        /// 
        /// 按算法获取一个可怜的学生
        /// 
        /// 包含点名次数的学生列表
        /// 学生
        public static Student getAPoorStdNum(ArrayList calllist)
        {
            int index= decideFinally(calllist, randomFirstly(calllist.Count));
            Student std=(Student)calllist[index];
            new StudentsManager().getStudentByNum(std.Number).UnluckyCallNum++;
            return std;
        }

        /// 
        /// 初始随机产生RandomStdNum个学生索引
        /// 
        /// 随机数范围
        /// RandomStdNum个学生索引数组
        public static int[] randomFirstly(int range)
        {
            int[] s=new int[RandomStdNum];
            for (int i = 0; i < RandomStdNum; i++)
            {
                s[i] = -1;
            }
                s = getRandomNum(RandomStdNum, 0, range);
            return s;
        }

        /// 
        /// 按公平算法决定最终的倒霉鬼索引
        /// 
        /// 包含点名次数的学生列表
        /// 初始随机产生的学生索引数组
        /// 最终倒霉鬼索引
        public static int decideFinally(ArrayList calllist,int []students)
        {
            int luckiestStudent = 0;
            int fairness = 1000;
            for (int i = 0; i < RandomStdNum; i++)
            {
                ArrayList ca = new ArrayList();
                foreach (Student std in calllist)
                {
                    ca.Add(new Student(std.Number,std.Name,std.UnluckyCallNum));
                }
                int index = students[i];
                ((Student)(ca[index])).UnluckyCallNum++;
                if (computeUnlucky(ca) < fairness)
                {
                    luckiestStudent = students[i];
                    fairness = computeUnlucky(ca);
                }
            }
            return luckiestStudent;
        }

        /// 
        /// 计算公平值,各个学生倒霉值的平方的和
        /// 
        /// 包含点名次数的学生列表
        /// 公平值
        public static int computeUnlucky(ArrayList calllist)
        {
            int result = 0;
            foreach(Student std in calllist){
                result += std.UnluckyCallNum * std.UnluckyCallNum;
            }
            return result;
        }

        /// 
        /// 随机产生num个数
        /// 
        /// 
        /// 范围最小值(包含)
        /// 范围最大值(不包含)
        /// 
        private static int[] getRandomNum(int num, int minValue, int maxValue)
        {
            Random ra = new Random(unchecked((int)DateTime.Now.Ticks));
            int[] arrNum = new int[num];
            int tmp = 0;
            for (int i = 0; i <= num - 1; i++)
            {
                tmp = ra.Next(minValue, maxValue); //随机取数
                arrNum[i] = getNum(arrNum, tmp, minValue, maxValue, ra); //取出值赋到数组中
            }
            return arrNum;
        }

        /// 
        /// 递归,确保随机不重复
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        private static int getNum(int[] arrNum, int tmp, int minValue, int maxValue, Random ra)
        {
            int n = 0;
            while (n <= arrNum.Length - 1)
            {
                if (arrNum[n] == tmp) //利用循环判断是否有重复
                {
                    tmp = ra.Next(minValue, maxValue); //重新随机获取。
                    getNum(arrNum, tmp, minValue, maxValue, ra);//递归:如果取出来的数字和已取得的数字有重复就重新随机获取。
                }
                n++;
            }
            return tmp;
        }
    }
}


评价模块:

评价服务

using stdCall.MyRandom;
using stdCall.Resource;
using stdCall.TotalService;
using stdCall;
using System.Windows.Forms;
using stdCall.MyUtils;

namespace stdCall.MyEvaluation
{
    /// 
    /// 继承ResourceGet,提供评价模块的服务
    /// 
    class EvaluateService:ResourceGet
    {
        Evaluation evaluation = new Evaluation();

        /// 
        /// 评价主函数
        /// 点击星星触发
        /// 因为逻辑和第一次不同,判断是否已做了第一次随机,没有不继续
        /// 添加当前学生到历史记录
        /// 改变RandomService.currentStudent=RandomService.nextStudent;
        /// 延迟,让星星保留一段时间
        /// 
        /// 点击的星星
        public void evaluateCurrentStd(object sender){
            if (RandomService.nextStudent == null || RandomService.currentStudent == null)
            {
                return;
            }
            Panel panel_history = (Panel)resources["panel_history"];
            evaluation.markStarAndAddHisLabel((PictureBox)sender, RandomService.currentStudent, panel_history.Controls);
            Utils.Delay(500);
            FormMain.clearStars();
            Service.getAnimateService().animateCurrentStd(RandomService.nextStudent, 1);
            RandomService.currentStudent = RandomService.nextStudent;
            RandomService.nextStudent=Service.getAnimateService().animateNextAndReturnStd();
            //Utils.Delay(100);
        }
    }
}

评价具体实现的类

using stdCall.History;
using stdCall.Models;
using stdCall.Resource;
using System;
using System.Collections;
using System.Windows.Forms;

namespace stdCall.MyEvaluation
{
    /// 
    /// 评价类
    /// 
    class Evaluation
    {

        public static ArrayList picStars;
        public static int historyPosx = 0;
        public static int historyPosy = 0;
        public static Label latestHistoryLabel = new Label();
        private static bool firstFlag = true;

        private const int blankInside = 5;
        private const int blankOutside = 10;
        private const int picStarHeight = 20;
        /// 
        /// 待优化,评分,并生成星级图片到历史记录栏,直接添加至外部容器,并返回一个包含学生姓名的历史记录Label,在外部添加
        /// 
        /// 星级评价(0-5)
        /// 
        /// 容器类
        /// 包含学生姓名的历史记录Label
        public void markStarAndAddHisLabel(PictureBox picstar, Student currentStd,Control.ControlCollection collection)
        {
            
            if (currentStd == null) return ;
            int stars = 0;
            foreach (PictureBox pb in picStars)
            {
                if (pb != picstar)
                {
                    pb.Load("star_yellow.png");
                    stars++;
                }
                else
                {
                    pb.Load("star_yellow.png");
                    stars++;
                    break;
                }
            }

            new StudentsManager().getStudentByNum(currentStd.Number).UnluckyCallNum++;
            new CurrentHistory().addUnluckyCall(currentStd.Number,stars,ResourseLoader.CourseID);
            if (firstFlag)
            {
                latestHistoryLabel = generateHistoryLabelStars(collection, currentStd.Name, stars, historyPosx, historyPosy);
                firstFlag = false;
            }
            else
            {
                latestHistoryLabel = generateHistoryLabelStars(collection, currentStd.Name, stars, latestHistoryLabel);
            }
            collection.Add(latestHistoryLabel);
        }


        private Label generateHistoryLabelStars(Control.ControlCollection collection, String text, int stars, Label label)
        {
      
            generateHistoryStar(collection, stars, label.Location.X, label.Location.Y + label.Size.Height * 2 + picStarHeight + blankInside*2 + blankOutside);
            return generateLabel(text, label.Location.X, label.Location.Y + label.Size.Height + blankOutside + picStarHeight+blankInside);
        }

        /// 
        /// 生成一个历史记录Label
        /// 
        /// Label内容
        /// Label位置x
        /// Label位置y
        /// 
        public Label generateHistoryLabel(String text, int posx, int posy)
        {
            historyPosy += 45;
            return generateLabel(text,posx,posy);
        }

        /// 
        /// 生成星级图片到历史记录栏,直接添加至外部容器,并返回一个包含学生姓名的历史记录Label,在外部添加
        /// 
        /// 外部容器
        /// 
        /// 星级(0-5)
        /// 
        /// 
        /// 
        public Label generateHistoryLabelStars(Control.ControlCollection collection,String text, int stars,int posx, int posy)
        {
           /* historyPosy += 65;*/
            Label lable=generateLabel(text, posx, posy);
            generateHistoryStar(collection, stars,posx, posy +lable.Size.Height+blankInside);
            return lable;
        }

        /// 
        /// 生成并返回一个Label
        /// 
        /// 
        /// 
        /// 
        /// 
        private Label generateLabel(String text, int posx, int posy)
        {
            Label mylabel = new Label();
            mylabel.AutoSize = true;
            mylabel.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            mylabel.Font = new System.Drawing.Font("Buxton Sketch", 21.75F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            mylabel.Location = new System.Drawing.Point(posx, posy);
            mylabel.Size = new System.Drawing.Size(164, 38);
            mylabel.TabIndex = 1;
            mylabel.Text = text;
            return mylabel;
        }

        /// 
        /// 根据评分生成历史记录栏的星级,直接添加至外部容器
        /// 
        /// 外部容器
        /// 
        /// 
        /// 
        public void generateHistoryStar(Control.ControlCollection collection,int stars,int posx,int posy){
            int starPosX = posx;
            int starPosY = posy;
            for (int i = 0; i < stars; i++)
            {

                System.Windows.Forms.PictureBox pictureBox_star;
                pictureBox_star = new System.Windows.Forms.PictureBox();
                pictureBox_star.Location = new System.Drawing.Point(starPosX, starPosY);
                pictureBox_star.Name = "pictureBox_stars";
                pictureBox_star.Size = new System.Drawing.Size(picStarHeight, picStarHeight);
                pictureBox_star.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
                pictureBox_star.TabIndex = 3;
                pictureBox_star.TabStop = false;
               /* pictureBox_star.Click += new System.EventHandler(this.pictureBox_stars_Click);*/
                pictureBox_star.Load("star_yellow.png");
                collection.Add(pictureBox_star);
               // picStars.Add(pictureBox_star);
                starPosX += 25;
            }
        }
    }
}


历史记录模块:

历史记录服务类

using stdCall;

namespace stdCall.History
{
    /// 
    /// 提供保存当前历史的服务
    /// 
    class HistoryService
    {
        CurrentHistory currentHistory = new CurrentHistory();
        /// 
        /// 保存当前历史主函数
        /// 
        /// 
        public bool saveCurrentHistory()
        {
            bool flag = false;
            try
            {
                currentHistory.save();
                flag = true;
            }
            catch (System.Exception ex)
            {
                flag = false;
            }
            return flag;
        }
    }
}

历史记录模型类

using stdCall.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace stdCall.History
{
    class unluckSavingCall:UnluckyCall
    {
        private bool saveflag = false;

        public unluckSavingCall(string studentid, int star, int courseNum)
        {
            // TODO: Complete member initialization
            this.Studentid = studentid;
            this.Star = star;
            this.CourseID = courseNum;
        }

        /// 
        /// 防止重复保存
        /// 
        public bool Saveflag
        {
            get { return saveflag; }
            set { saveflag = value; }
        }
    }
}

历史记录具体实现类

using stdCall.File;
using stdCall.Models;
using stdCall.Resource;
using System;
using System.Collections;
using System.Windows.Forms;

namespace stdCall.History
{
    /// 
    /// 历史记录类
    /// 
    class CurrentHistory
    {
        public static ArrayList unluckSavingCalls = new ArrayList();

        /// 
        /// 保存历史记录到ResouseLoader.FileUCSPath
        /// 
        /// 
        public bool save(){
            new FileHelper().closeFile();
            new FileHelper().openWriteFile(ResourseLoader.FileUCSPath);
            bool flag = true;
            foreach (unluckSavingCall uc in unluckSavingCalls)
            {
                if (!uc.Saveflag)
                {
                    try
                    {
                        new FileHelper().writeSingleData(uc.Studentid);
                        new FileHelper().writeSingleData(uc.Star.ToString());
                        new FileHelper().writeSingleData(uc.CourseID.ToString());
                        uc.Saveflag = true;
                    }
                    catch (System.Exception ex)
                    {
                        flag = false;
                        ThreadExceptionDialog warnDialog = new ThreadExceptionDialog(ex);
                        warnDialog.ShowDialog();
                        uc.Saveflag = false;
                    }
                }
            }
            new FileHelper().closeFile();
            return flag;
        }

        /// 
        /// 添加一个点名
        /// 
        /// 
        /// 
        /// 
        public void addUnluckyCall(String studentid, int star, int courseNum)
        {
            unluckSavingCalls.Add(new unluckSavingCall(studentid, star, courseNum));
        }

        public void getHistoryCalls()
        {

        }
        /// 
        /// 删除历史记录,未实现
        /// 
        /// 
        public void delCallByStdNum(int studentnum)
        {

        }

        

    }
}


所有服务获取类

using stdCall.MyAnimate;
using stdCall.MyEvaluation;
using stdCall.MyExcel;
using stdCall.MyRandom;
namespace stdCall.TotalService
{
    /// 
    /// 总服务类,即各模块服务获取类
    /// 
    class Service
    {

        public static stdCall.Resource.ResourseServer getResouseService()
        {
            return new stdCall.Resource.ResourseServer();
        }

        public static RandomService getRandomService()
        {
            return new RandomService();
        }

        public static EvaluateService getEvaluateService()
        {
            return new EvaluateService();
        }


        public static ExcelService getExcelService()
        {
            return new ExcelService();
        }

        public static AnimateService getAnimateService()
        {
            return new AnimateService();
        }

        public static stdCall.History.HistoryService getHistoryService()
        {
            return new stdCall.History.HistoryService();
        }

    }
}


界面类实现

using stdCall;
using stdCall.MyEvaluation;
using stdCall.Models;
using stdCall.TotalService;
using System;
using System.Collections;
using System.Windows.Forms;

namespace stdCall
{
    /// 
    /// 主页面
    /// 
    public partial class FormMain : Form
    {
        ArrayList historyStds = new ArrayList();
        static ArrayList picStars = new ArrayList();
        StudentsManager studentManager = new StudentsManager();
        UnluckyCallsManager unluckyCallsManager = new UnluckyCallsManager();
        /// 
        /// 
        /// 
        public FormMain()
        {
            FormMain.CheckForIllegalCrossThreadCalls = false;
            InitializeComponent();
            sendControlsToModles();
            Service.getResouseService().loadSystemResourse();
            new CourseDialog().ShowDialog();
            generateStars();
            Evaluation.picStars = picStars;
        }

        /// 
        /// 让需要空间的模块获取控件
        /// 
        private void sendControlsToModles()
        {
            Service.getAnimateService().addResource("label_currentStd", this.label_currentStd);
            Service.getAnimateService().addResource("label_hideCurrentStd", this.label_hideCurrentStd);
            Service.getAnimateService().addResource("label_nextStd", this.label_nextStd);
            Service.getAnimateService().addResource("label_hideNextStd", this.label_hideNextStd);
            Service.getAnimateService().addResource("panel_current", this.panel_current);
            Service.getAnimateService().addResource("panel_nextstd", this.panel_nextstd);
            Service.getEvaluateService().addResource("panel_history", this.panel_history);
        }

        /// 
        /// 生成星级(黑),并加入容器
        /// 
        private void generateStars()
        {
            int starSize = 52;
            int starPosX = this.label_currentStd.Width / 2 - starSize;
            int starPosY = 0;

            for (int i = 0; i < 5; i++)
            {

                System.Windows.Forms.PictureBox pictureBox_star;
                pictureBox_star = new System.Windows.Forms.PictureBox();
                pictureBox_star.Cursor = System.Windows.Forms.Cursors.Hand;
                pictureBox_star.Location = new System.Drawing.Point(starPosX, starPosY);
                pictureBox_star.Name = "pictureBox_stars";
                pictureBox_star.Size = new System.Drawing.Size(starSize, starSize);
                pictureBox_star.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
                pictureBox_star.TabIndex = 3;
                pictureBox_star.TabStop = false;
                pictureBox_star.Click += new System.EventHandler(this.pictureBox_stars_Click);
                pictureBox_star.Load("star_black.png");
                this.panel_star.Controls.Add(pictureBox_star);
                picStars.Add(pictureBox_star);
                starPosX += starSize+8;
            }
        }

        
        /// 
        /// 星级初始化并随机产生倒霉鬼
        /// 
        /// 
        /// 
        private void button_random_Click(object sender, EventArgs e)
        {
            clearStars();
            Service.getRandomService().startRandom();
        }
    
        /// 
        /// 星星变黑,初始化
        /// 
        public static void  clearStars()
        {
            foreach (PictureBox pb in picStars)
            {
                pb.Load("star_black.png");
            }
        }


        /// 
        /// 星级的评价,点击可评价,不可修改
        /// 
        /// 点击的图片
        /// 
        private void pictureBox_stars_Click(object sender, EventArgs e)
        {
            Service.getEvaluateService().evaluateCurrentStd(sender);
           // clearStars();
        }

        /// 
        /// 保存当前历史记录
        /// 
        /// 
        /// 
        private void button_save_Click(object sender, EventArgs e)
        {
            stdCall.View.DialogReply reply = new stdCall.View.DialogReply();
            if (Service.getHistoryService().saveCurrentHistory())
            {
                reply.setReply("当前历史保存成功!");
                reply.ShowDialog();
            }
            else
            {
                reply.setReply("当前历史保存失败,请检查!");
                reply.ShowDialog();
            }
        }

        /// 
        /// 点击加载excel(班级名单)
        /// 
        /// 
        /// 
        private void button_loadExcel_Click(object sender, EventArgs e)
        {
            stdCall.View.DialogReply reply = new stdCall.View.DialogReply();
            if (Service.getExcelService().loadExcel())
            {
                reply.setReply("班级名单导入成功!");
                reply.ShowDialog();
                //reply.Dispose();
            }
            else
            {
                reply.setReply("班级名单导入失败,请检查!");
                reply.ShowDialog();
            }
        }

 
   

    }
}

课程ID询问对话框

using stdCall;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using stdCall.TotalService;
using stdCall.Resource;

namespace stdCall
{
    /// 
    /// 课程设置对话框
    /// 
    public partial class CourseDialog : Form
    {
        /// 
        /// 
        /// 
        public CourseDialog()
        {
            InitializeComponent();
            ResourseLoader rl=new ResourseLoader();
            rl.loadCourseID();
            textBox_courseID.Text = ResourseLoader.CourseID.ToString();
        }

        private void button_ok_Click(object sender, EventArgs e)
        {
            try
            {
            	int courseid = int.Parse(textBox_courseID.Text);
                new ResourseLoader().setCourseID(int.Parse(textBox_courseID.Text));
                this.Dispose();
            }
            catch (System.Exception ex)
            {
                ThreadExceptionDialog td = new ThreadExceptionDialog(ex);
                td.ShowDialog();
            }
        }

       
    }
}

操作回复对话框

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace stdCall.View
{
    /// 
    /// 操作回复对话框
    /// 
    public partial class DialogReply : Form
    {
        public DialogReply()
        {
            InitializeComponent();
        }
        public void setReply(String text){
            this.label_reply.Text = text;
        }

        private void button_ok_Click(object sender, EventArgs e)
        {
            this.Dispose();
        }
    }
}


实用类(目前只有延迟函数)

using System;
using System.Windows.Forms;

namespace stdCall.MyUtils
{
    /// 
    /// 实用类
    /// 
    class Utils
    {
        /// 
        /// 延迟函数,毫秒级
        /// 
        /// 延迟时间,毫秒级
        /// 
        public static bool Delay(int delayTime)
        {
            DateTime now = DateTime.Now;
            int s;
            do
            {
                TimeSpan spand = DateTime.Now - now;
                s = spand.Milliseconds;
                Application.DoEvents();
            }
            while (s < delayTime);
            return true;
        }
    }
}


学生排序类

using stdCall.Models;
namespace stdCall.MyUtils
{
    /// 
    /// 学生ArrayList的排序规则:学号升序
    /// 
    class StudentCompare : System.Collections.IComparer
    {
        public int Compare(object x, object y)
        {
            return int.Parse(((Student)x).Number) - int.Parse(((Student)y).Number);
        }
    }
  
}







你可能感兴趣的:(学生随机点名程序)