'上传项目'

parent df28f77a
/Lottery/.vs
/Lottery/Lottery/bin
/Lottery/Lottery/obj
\ No newline at end of file

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.29215.179
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lottery", "Lottery\Lottery.csproj", "{041D16E0-7C67-40F3-95BD-D6D92399E58B}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{041D16E0-7C67-40F3-95BD-D6D92399E58B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{041D16E0-7C67-40F3-95BD-D6D92399E58B}.Debug|Any CPU.Build.0 = Debug|Any CPU
{041D16E0-7C67-40F3-95BD-D6D92399E58B}.Release|Any CPU.ActiveCfg = Release|Any CPU
{041D16E0-7C67-40F3-95BD-D6D92399E58B}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {E148B5A2-4007-4A3E-A3AB-A1506DCB5959}
EndGlobalSection
EndGlobal
{
// Use IntelliSense to find out which attributes exist for C# debugging
// Use hover for the description of the existing attributes
// For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md
"version": "0.2.0",
"configurations": [
{
"name": ".NET Core Launch (console)",
"type": "coreclr",
"request": "launch",
"preLaunchTask": "build",
// If you have changed target frameworks, make sure to update the program path.
"program": "${workspaceFolder}/bin/Debug/netcoreapp2.1/Lottery.dll",
"args": [],
"console":"externalTerminal",
"cwd": "${workspaceFolder}",
// For more information about the 'console' field, see https://aka.ms/VSCode-CS-LaunchJson-Console
"stopAtEntry": false
},
{
"name": ".NET Core Attach",
"type": "coreclr",
"request": "attach",
"processId": "${command:pickProcess}"
}
]
}
\ No newline at end of file
{
"version": "2.0.0",
"tasks": [
{
"label": "build",
"command": "dotnet",
"type": "process",
"args": [
"build",
"${workspaceFolder}/Lottery.csproj",
"/property:GenerateFullPaths=true",
"/consoleloggerparameters:NoSummary"
],
"problemMatcher": "$msCompile"
},
{
"label": "publish",
"command": "dotnet",
"type": "process",
"args": [
"publish",
"${workspaceFolder}/Lottery.csproj",
"/property:GenerateFullPaths=true",
"/consoleloggerparameters:NoSummary"
],
"problemMatcher": "$msCompile"
},
{
"label": "watch",
"command": "dotnet",
"type": "process",
"args": [
"watch",
"run",
"${workspaceFolder}/Lottery.csproj",
"/property:GenerateFullPaths=true",
"/consoleloggerparameters:NoSummary"
],
"problemMatcher": "$msCompile"
}
]
}
\ No newline at end of file
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lottery
{
/// <summary>
/// 表示奖项信息
/// </summary>
class Lottery
{
public int Level { get; private set; }
public string Name { get; private set; }
public string Prize { get; private set; }
public int Count { get; private set; }
public static IReadOnlyList<Lottery> GetLotteries()
{
string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "l.txt");
return File.Exists(filePath) ? File.ReadLines(filePath).Where(p => !string.IsNullOrEmpty(p)).Select(p =>
{
var items = p.Split(';');
return new Lottery { Level = int.Parse(items[0]), Name = items[1], Prize = items[2], Count = int.Parse(items[3]) };
}).ToList() : new List<Lottery>()
{
new Lottery{ Count = 1, Level = 1, Name = "一等奖", Prize = "键盘" },
new Lottery{ Count = 3, Level = 2, Name = "二等奖" , Prize = "按摩仪"},
new Lottery{ Count = 8, Level = 3, Name = "三等奖" , Prize = "坚果礼盒"},
new Lottery{ Count = 55, Level = 4, Name = "阳光普照奖", Prize = "身体乳、大宝SOD密、旅行套装、靠枕、鼠标垫" },
new Lottery{ Count = 100, Level = 5, Name = "未中奖" },
};
}
}
}
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.1</TargetFramework>
<AllowUnsafeBlocks>false</AllowUnsafeBlocks>
</PropertyGroup>
<ItemGroup>
<None Remove="p.csv" />
</ItemGroup>
<ItemGroup>
<Content Include="p.csv">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>
</Project>
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace Lottery
{
static class LotteryResult
{
/// <summary>
/// 保存结果
/// </summary>
/// <param name="persons">抽奖人员</param>
/// <param name="lotteries">奖项信息</param>
public static void SaveResult(IReadOnlyList<Person> persons, IReadOnlyList<Lottery> lotteries)
{
Console.Clear();
Console.WriteLine("抽奖结果" + Environment.NewLine);
string saveFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Result.txt");
if (File.Exists(saveFile))
{
File.Delete(saveFile);
}
var stream = new FileStream(saveFile, FileMode.Create);
for (int i = 0; i < lotteries.Count; i++)
{
Console.ForegroundColor = ConsoleColor.Yellow;
var lottery = $"{lotteries[i].Name}{lotteries[i].Prize}";
Console.WriteLine(lottery);
var text = Encoding.UTF8.GetBytes(lottery + Environment.NewLine);
stream.Write(text, 0, text.Length);
Console.ForegroundColor = ConsoleColor.White;
persons.OrderByDescending(p => p.NewGrade)
.Skip(Enumerable.Range(0, i).Sum(p => lotteries[p].Count))
.Take(lotteries[i].Count)
.ToList()
.ForEach(p =>
{
var content = p.Name + "\t";
Console.Write(content);
text = Encoding.UTF8.GetBytes(content);
stream.Write(text, 0, text.Length);
});
Console.WriteLine(Environment.NewLine);
text = Encoding.UTF8.GetBytes(Environment.NewLine);
stream.Write(text, 0, text.Length);
}
stream.Flush();
stream.Dispose();
Console.WriteLine("抽奖结果已保存在程序运行目录下的Result.txt文件");
}
}
}
using System;
using System.Collections.Generic;
using System.Net.NetworkInformation;
using System.Text;
namespace Lottery
{
static class NetConnect
{
public static bool CheckNetConnect()
{
try
{
Ping ping = new Ping();
PingReply reply = ping.Send("www.baidu.com");
ping.Dispose();
return reply.Status == IPStatus.Success;
}
catch (Exception)
{
}
return false;
}
}
}
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lottery
{
/// <summary>
/// 表示参与抽奖的人物信息
/// </summary>
class Person
{
public string Name { get; private set; }
public int BaseGrade { get; private set; }
private int newGrade = 0;
public int NewGrade
{
get => newGrade;
set
{
OldGrade = newGrade;
newGrade = value;
}
}
public int OldGrade { get; private set; } = 0;
/// <summary>
/// 从文件读取人物信息
/// </summary>
/// <returns></returns>
public static IReadOnlyList<Person> GetPersons()
{
string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "p.csv");
return File.Exists(filePath) ? File.ReadLines(filePath)
.Where(p => !string.IsNullOrEmpty(p)).
Select(p => new Person
{
BaseGrade = int.Parse(p.Split(new []{','})[1]),
Name = p.Split(new []{','})[0]
}).ToList()
: new List<Person>(0);
}
public static int GetRandomBaseGrade(int baseGrade)
{
var r = new Random(379);
var bs = new[] {3, 7, 9};
if (baseGrade % 3 == 0)
{
return baseGrade * bs[r.Next(0,2)];
}
if (baseGrade % 7 == 0)
{
return baseGrade * bs[r.Next(0,2)];
}
if (baseGrade % 9 == 0)
{
return baseGrade * bs[r.Next(0,2)];
}
return baseGrade;
}
}
}
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Lottery
{
class Program
{
static void Main(string[] args)
{
Screen.Init();
if (!NetConnect.CheckNetConnect())
{
Console.WriteLine(Environment.NewLine + "请检查网络连接");
Console.ReadLine();
return;
}
//最终参与抽奖的人数可能变动,采用读文件方式动态获取
IReadOnlyList<Person> persons = Person.GetPersons().ToList();
IReadOnlyList<Lottery> lotteries = Lottery.GetLotteries();
if (persons.Count == 0)
{
Console.WriteLine(Environment.NewLine + "未找到抽奖人员,请在程序生成目录下编写p.txt文件,每个人名占一行");
Console.ReadLine();
return;
}
Console.Clear();
Screen.ShowTitle("1024抽奖程序");
Console.WriteLine(Environment.NewLine + "程序将进行3轮计算,为每个人随机发金币,最终按照所得的金币数由多到少排序,以此分别决定所得的奖项大小,按回车开始运行");
Console.ReadLine();
for (int i = 1; i <= 3; i++)
{
Console.Clear();
Screen.ShowTitle("1024抽奖程序");
Console.WriteLine("...正在计算...");
//开始计分,该循环表示计分规则
//获取从www.random.org生成的真随机数
IReadOnlyList<int> randoms = RandomOrg.GetRandomsAsync(persons.Count).Result;
for (int j = 0; j < persons.Count; j++)
{
//计分方式1:根据返回的随机数加金币
//计分方式2:看命
//计分方式3:随即加上一个人的金币,看能否逆袭
//其他方式:可在下方对NewGrade属性进行操作
persons[j].NewGrade += (randoms[j] +
(Math.Abs(persons[j].GetHashCode() << 1) % persons.Count) +
persons[randoms[j] - 1].OldGrade);
if (i == 3 && persons[j].BaseGrade > 0)
{
persons[j].NewGrade += Person.GetRandomBaseGrade(persons[j].BaseGrade);
}
}
//计分结束,以下为保存及更新显示
Console.Clear();
Screen.ShowTitle("第" + i.ToString() + "轮");
Screen.ShowGradeList(persons, lotteries.Where(p => p.Level <= 3).Sum(p => p.Count));
Screen.Show(i, persons, lotteries);
Console.WriteLine(Environment.NewLine + "按回车继续...");
Console.ReadLine();
}
LotteryResult.SaveResult(persons, lotteries);
Console.ReadLine();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Reflection;
using System.Reflection.Emit;
using System.Text;
using System.Threading.Tasks;
namespace Lottery
{
/// <summary>
/// 表示真随机数
/// </summary>
static class RandomOrg
{
/// <summary>
/// 获取从www.random.org根据大气噪声生成的真随机数列表
/// </summary>
/// <param name="length">需要获取的随机数个数</param>
/// <returns>length长度的随机数集合</returns>
public static async Task<IReadOnlyList<int>> GetRandomsAsync(int length)
{
try
{
using (HttpClient httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.TryAddWithoutValidation("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3936.0 Safari/537.36 Edg/79.0.301.2");
var resp = await httpClient.GetAsync($"https://www.random.org/integers/?num={length}&min=1&max={length}&col=1&base=10&format=plain&rnd=new");
if (resp.IsSuccessStatusCode)
{
string content = await resp.Content.ReadAsStringAsync();
return content.Split('\n').Where(p => !string.IsNullOrEmpty(p)).Select(p => int.Parse(p)).ToList();
}
}
}
catch (Exception)
{
}
var r = new Random(length);
return Enumerable.Range(0, length).Select(p => r.Next(1, length + 1)).ToList();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace Lottery
{
static class Screen
{
static List<Person> old = new List<Person>();
public static void ShowTitle(string title)
{
Console.ForegroundColor = ConsoleColor.Cyan;
Enumerable.Range(0, Console.LargestWindowWidth - 3).ToList().ForEach(p => Console.Write("$"));
Console.SetCursorPosition(Console.LargestWindowWidth / 2, 1);
title.ToList().ForEach(p => Console.Write(p));
Console.SetCursorPosition(0, 2);
Enumerable.Range(0, Console.LargestWindowWidth - 3).ToList().ForEach(p => Console.Write("$"));
}
public static void Show(int i, IReadOnlyList<Person> persons, IReadOnlyList<Lottery> lotteries)
{
var temp = persons.OrderByDescending(p => p.NewGrade).ToList();
if (i == 1)
{
old.AddRange(temp);
}
else if (i > 1)
{
Console.WriteLine();
var n = temp.Take(lotteries.Where(p => p.Level <= 3).Sum(p => p.Count)).Max(p => old.LastIndexOf(p));
Console.WriteLine($"逆袭大神:{old[n].Name}");
n = old.Take(lotteries.Where(p => p.Level <= 3).Sum(p => p.Count))
.Max(p => temp.LastIndexOf(p));
Console.WriteLine();
Console.WriteLine($"翻车小弟:{persons[n].Name}");
old.Clear();
old.AddRange(temp);
}
}
public static void ShowGradeList(IReadOnlyList<Person> person, int highlight)
{
var people = person.OrderByDescending(p => p.NewGrade).ToList();
int width = ((Console.LargestWindowWidth - 6) / 3 - 6) / 3;
Console.ForegroundColor = ConsoleColor.Yellow;
var titles = new List<string> { "排名", "人名", "金币" };
for (int i = 0; i < titles.Count; i++)
{
Console.SetCursorPosition(i * width, 5);
Console.Write(titles[i]);
}
var list1 = people.Take(people.Count / 3).ToList();
int index = 1;
for (int i = 0; i < list1.Count; i++)
{
Console.ForegroundColor = index <= highlight ? ConsoleColor.Yellow : ConsoleColor.White;
Console.SetCursorPosition(0, i + 6);
Console.Write($"{index++}");
Console.SetCursorPosition(width, i + 6);
Console.Write($"{list1[i].Name}");
Console.SetCursorPosition(width * 2, i + 6);
Console.Write($"{list1[i].NewGrade}");
}
Console.ForegroundColor = ConsoleColor.Yellow;
for (int i = 1; i <= titles.Count; i++)
{
Console.SetCursorPosition((i - 1) * width + width * 4 - 4, 5);
Console.Write(titles[i - 1]);
}
var list2 = people.Skip(people.Count / 3).Take(people.Count / 3).ToList();
for (int i = 0; i < list2.Count; i++)
{
Console.ForegroundColor = index <= highlight ? ConsoleColor.Yellow : ConsoleColor.White;
Console.SetCursorPosition(0 + width * 4 - 4, i + 6);
Console.Write($"{index++}");
Console.SetCursorPosition(width + width * 4 - 4, i + 6);
Console.Write($"{list2[i].Name}");
Console.SetCursorPosition(width * 2 + width * 4 - 4, i + 6);
Console.Write($"{list2[i].NewGrade}");
}
Console.ForegroundColor = ConsoleColor.Yellow;
for (int i = 1; i <= titles.Count; i++)
{
Console.SetCursorPosition((i - 1) * width + width * 8 - 4, 5);
Console.Write(titles[i - 1]);
}
var list3 = people.Skip(people.Count / 3).Skip(people.Count / 3).ToList();
for (int i = 0; i < list3.Count; i++)
{
Console.ForegroundColor = index <= highlight ? ConsoleColor.Yellow : ConsoleColor.White;
Console.SetCursorPosition(0 + width * 8 - 4, i + 6);
Console.Write($"{index++}");
Console.SetCursorPosition(width + width * 8 - 4, i + 6);
Console.Write($"{list3[i].Name}");
Console.SetCursorPosition(width * 2 + width * 8 - 4, i + 6);
Console.Write($"{list3[i].NewGrade}");
}
}
[DllImport("User32.dll", EntryPoint = "FindWindow")]
private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll", EntryPoint = "FindWindowEx")]
private static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);
[DllImport("User32.dll", EntryPoint = "SendMessage")]
private static extern int SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, string lParam);
[DllImport("User32.dll", EntryPoint = "ShowWindow")]
private static extern bool ShowWindow(IntPtr hWnd, int type);
public static void Init()
{
Console.Title = "1024抽奖程序";
IntPtr ParenthWnd = new IntPtr(0);
IntPtr et = new IntPtr(0);
ParenthWnd = FindWindow(null, "1024抽奖程序");
//最大化
ShowWindow(ParenthWnd, 3);
Console.SetWindowSize(Console.LargestWindowWidth, Console.LargestWindowHeight);
Console.BufferWidth = Console.LargestWindowWidth;
Console.BufferHeight = Console.LargestWindowHeight * 2;
Console.WindowLeft = Console.WindowTop = 0;
Enumerable.Range(0, Console.LargestWindowWidth).ToList().ForEach(p => Enumerable.Range(0, Console.LargestWindowHeight).ToList().ForEach(d => Console.Write("")));
}
}
}
马凤银,0
胡国材,0
韦锦超,0
曾沂轮,0
罗学周,0
刘培,0
张启明,0
吴思铭,0
陈辉,0
毛福寿,0
杨璐,0
梁晓彤,0
刘恽伟,0
黄瑞卿,0
唐建勇,0
梁振雄,0
石卉,0
汪杰,0
刘建平,0
田杰,0
何军,0
李佳,0
张玉婷,0
廖天兰,0
黄宝红,0
詹文容,0
欧阳城枫,0
赵文雅,0
谭慧珍,0
卢泽晓,0
叶进国,0
曾少鹏,0
马娜,0
周海鹏,0
唐柳,0
邓伟驰,0
单永华,0
韩越越,0
高燕,0
李婉儿,0
陈珠河,0
张睿,0
余子明,0
邱美欣,0
蔡卫国,0
林健忠,0
刘玲,0
黄慧敏,0
罗颖骄,0
李文文,0
谢旭,0
梁锦银,0
林志诚,0
林子胜,0
苏堉,0
梁明俊,0
莫振浩,0
杨文伟,0
廖家宝,0
赖颂菊,0
于小岚,0
程春景,0
吕时有,0
张可欣,0
吴素洁,0
胡浩琴,0
靳梦杨,0
徐敬钊,0
曾德城,0
严韵诗,0
蔡增威,0
侯祥意,0
韦哲,0
高波,0
刘国民,0
李静,0
杨东宏,0
叶宜博,0
黄文婷,0
覃琳,0
林军,0
黄程程,0
赵运雄,0
周俊晖,0
林丽梅,0
毛燮敏,0
陈晓玲,0
叶子钠,0
李元昭,0
徐林燕,0
\ No newline at end of file
# 1024抽奖程序
该程序使用了www.random.org提供的随机数API,它提供了真正的随机数序列,它通过大气噪音这种大自然的随机现象来产生随机数
# 调试运行
## 使用Visual Studio
下载安装Visual Studio后打开项目文件Lottery.sln即可F5调试运行,若无法加载项目,则项目右键安装缺少的.NET Core依赖
## 使用VS Code或其他文本编辑器
以VS Code为例,该编辑器打开项目文件夹后(*.cs文件所在的文件夹),会自动安装C#的语法提示及调试器等插件,随后:
1. 下载并安装[.NET Core SDK](https://dotnet.microsoft.com/download)
2. 修改代码后,可以在VS Code中按F5运行或打开CMD或PowerShell定位到*.cs文件所在的文件夹,输入dotnet run即可运行
# 修改
计分规则位于Program.cs文件中并已注释可修改的部分,其他*.cs文件均为更新屏幕显示、Model、帮助类等
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment