Skip to content

Commit

Permalink
Refactor and some improvements (#131)
Browse files Browse the repository at this point in the history
* Refactor + some improvements

* translation refactor

* extension

* ext

* namespace

* minor fixes

* comparasion change
  • Loading branch information
Lunat1q authored and undorev committed Sep 2, 2018
1 parent 5421e95 commit 67828bd
Show file tree
Hide file tree
Showing 35 changed files with 986 additions and 617 deletions.
18 changes: 18 additions & 0 deletions UFBLauncher/App.config
@@ -0,0 +1,18 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="UFBLauncher.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
</sectionGroup>
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
<userSettings>
<UFBLauncher.Properties.Settings>
<setting name="UFBName" serializeAs="String">
<value />
</setting>
</UFBLauncher.Properties.Settings>
</userSettings>
</configuration>
49 changes: 49 additions & 0 deletions UFBLauncher/Program.cs
@@ -0,0 +1,49 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Mime;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace UFBLauncher
{
class Program
{
private const string ExeExt = ".exe";
private const string DefaultName = "UltimateFishBot.exe";

static void Main(string[] args)
{
var lastName = Properties.Settings.Default.UFBName;

if (!RunBotSecretly(lastName)) RunBotSecretly(DefaultName);
}

[DllImport("user32.dll")]
static extern int SetWindowText(IntPtr hWnd, string text);

static bool RunBotSecretly(string name)
{
var currentPath = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), name);
var ufbExeFile = new FileInfo(currentPath);
if (ufbExeFile.Exists)
{
var newName = StringUtils.RandomString(12) + ExeExt;
var newPath = Path.Combine(Path.GetDirectoryName(currentPath), newName);
ufbExeFile.MoveTo(newPath);
Properties.Settings.Default.UFBName = newName;
Properties.Settings.Default.Save();
var p = Process.Start(ufbExeFile.FullName);
Thread.Sleep(1500);
SetWindowText(p.MainWindowHandle, newName);
return true;
}
return false;
}
}
}
36 changes: 36 additions & 0 deletions UFBLauncher/Properties/AssemblyInfo.cs
@@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("UFBLauncher")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("UFBLauncher")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("6529fb5b-d58f-4e12-aa91-5c694e44b142")]

// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
38 changes: 38 additions & 0 deletions UFBLauncher/Properties/Settings.Designer.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 9 additions & 0 deletions UFBLauncher/Properties/Settings.settings
@@ -0,0 +1,9 @@
<?xml version='1.0' encoding='utf-8'?>
<SettingsFile xmlns="http://schemas.microsoft.com/VisualStudio/2004/01/settings" CurrentProfile="(Default)" GeneratedClassNamespace="UFBLauncher.Properties" GeneratedClassName="Settings">
<Profiles />
<Settings>
<Setting Name="UFBName" Type="System.String" Scope="User">
<Value Profile="(Default)" />
</Setting>
</Settings>
</SettingsFile>
18 changes: 18 additions & 0 deletions UFBLauncher/StringUtils.cs
@@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace UFBLauncher
{
internal class StringUtils
{
private static readonly Random Random = new Random();
public static string RandomString(int length, string chars = "abcdefghijklmnopqrstuvwxyz0123456789")
{
return new string(Enumerable.Repeat(chars, length)
.Select(s => s[Random.Next(s.Length)]).ToArray());
}
}
}
68 changes: 68 additions & 0 deletions UFBLauncher/UFBLauncher.csproj
@@ -0,0 +1,68 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{6529FB5B-D58F-4E12-AA91-5C694E44B142}</ProjectGuid>
<OutputType>Exe</OutputType>
<RootNamespace>UFBLauncher</RootNamespace>
<AssemblyName>UFBLauncher</AssemblyName>
<TargetFrameworkVersion>v4.6.1</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Properties\Settings.Designer.cs">
<AutoGen>True</AutoGen>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
<DependentUpon>Settings.settings</DependentUpon>
</Compile>
<Compile Include="StringUtils.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
<None Include="Properties\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<LastGenOutput>Settings.Designer.cs</LastGenOutput>
</None>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\UltimateFishBot\UltimateFishBot.csproj">
<Project>{e4705d9f-56cd-48cb-863b-4363d03c8424}</Project>
<Name>UltimateFishBot</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>
12 changes: 11 additions & 1 deletion UltimateFishBot.sln
@@ -1,7 +1,7 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.27428.2015
VisualStudioVersion = 15.0.27130.2027
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UltimateFishBot", "UltimateFishBot\UltimateFishBot.csproj", "{E4705D9F-56CD-48CB-863B-4363D03C8424}"
EndProject
Expand All @@ -10,6 +10,8 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".nuget", ".nuget", "{FEE29B
.nuget\NuGet.Config = .nuget\NuGet.Config
EndProjectSection
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UFBLauncher", "UFBLauncher\UFBLauncher.csproj", "{6529FB5B-D58F-4E12-AA91-5C694E44B142}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand All @@ -27,6 +29,14 @@ Global
{E4705D9F-56CD-48CB-863B-4363D03C8424}.Release|Any CPU.Build.0 = Release|Any CPU
{E4705D9F-56CD-48CB-863B-4363D03C8424}.Release|x64.ActiveCfg = Release|x64
{E4705D9F-56CD-48CB-863B-4363D03C8424}.Release|x64.Build.0 = Release|x64
{6529FB5B-D58F-4E12-AA91-5C694E44B142}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{6529FB5B-D58F-4E12-AA91-5C694E44B142}.Debug|Any CPU.Build.0 = Debug|Any CPU
{6529FB5B-D58F-4E12-AA91-5C694E44B142}.Debug|x64.ActiveCfg = Debug|Any CPU
{6529FB5B-D58F-4E12-AA91-5C694E44B142}.Debug|x64.Build.0 = Debug|Any CPU
{6529FB5B-D58F-4E12-AA91-5C694E44B142}.Release|Any CPU.ActiveCfg = Release|Any CPU
{6529FB5B-D58F-4E12-AA91-5C694E44B142}.Release|Any CPU.Build.0 = Release|Any CPU
{6529FB5B-D58F-4E12-AA91-5C694E44B142}.Release|x64.ActiveCfg = Release|Any CPU
{6529FB5B-D58F-4E12-AA91-5C694E44B142}.Release|x64.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down
49 changes: 21 additions & 28 deletions UltimateFishBot/Classes/BodyParts/Ears.cs
@@ -1,46 +1,42 @@
using CoreAudioApi;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using UltimateFishBot.Collections;

namespace UltimateFishBot.Classes.BodyParts
namespace UltimateFishBot.BodyParts
{
class Ears
internal class Ears
{
private MMDevice SndDevice;
private Queue<int> m_volumeQueue;
private int tickrate = 50; //ms pause between sound checks
private MMDevice _sndDevice;
private readonly LimitedCollection<int> _volumeQueue;
private int _tickrate = 50; //ms pause between sound checks

private const int MAX_VOLUME_QUEUE_LENGTH = 5;
private const int MaxVolumeQueueLength = 5;

public Ears()
{
m_volumeQueue = new Queue<int>();
m_volumeQueue.Enqueue(0);
_volumeQueue = new LimitedCollection<int>(MaxVolumeQueueLength) {0};
}

public async Task<bool> Listen(int millisecondsToListen, CancellationToken cancellationToken)
{
Stopwatch stopwatch = new Stopwatch();
var stopwatch = new Stopwatch();
stopwatch.Start();
MMDeviceEnumerator SndDevEnum = new MMDeviceEnumerator();
if (Properties.Settings.Default.AudioDevice != "") {
SndDevice = SndDevEnum.GetDevice(Properties.Settings.Default.AudioDevice);
} else {
SndDevice = SndDevEnum.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia);
}
var sndDevEnum = new MMDeviceEnumerator();
_sndDevice = Properties.Settings.Default.AudioDevice != ""
? sndDevEnum.GetDevice(Properties.Settings.Default.AudioDevice)
: sndDevEnum.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia);
Func<bool> heardFish;
if (Properties.Settings.Default.AverageSound)
heardFish = ListenTimerTickAvg;
else
heardFish = ListenTimerTick;

while (stopwatch.ElapsedMilliseconds <= millisecondsToListen) {
await Task.Delay(tickrate, cancellationToken);
await Task.Delay(_tickrate, cancellationToken);
if (heardFish()) {
return true;
}
Expand All @@ -50,7 +46,7 @@ public async Task<bool> Listen(int millisecondsToListen, CancellationToken cance

private bool ListenTimerTick() {
// Get the current level
int currentVolumnLevel = (int)(SndDevice.AudioMeterInformation.MasterPeakValue * 100);
var currentVolumnLevel = (int)(_sndDevice.AudioMeterInformation.MasterPeakValue * 100);

if (currentVolumnLevel >= Properties.Settings.Default.SplashLimit)
return true;
Expand All @@ -61,28 +57,25 @@ public async Task<bool> Listen(int millisecondsToListen, CancellationToken cance
private bool ListenTimerTickAvg()
{
// Get the current level
int currentVolumnLevel = (int)(SndDevice.AudioMeterInformation.MasterPeakValue * 100);
int avgVol = GetAverageVolume();
bool hear = false;
var currentVolumnLevel = (int)(_sndDevice.AudioMeterInformation.MasterPeakValue * 100);
var avgVol = GetAverageVolume();
var hear = false;

// Determine if the current level is high enough to be a fish
if (currentVolumnLevel - avgVol >= Properties.Settings.Default.SplashLimit) {
Serilog.Log.Information("Hear: {av},{cvl},{queue}", avgVol, currentVolumnLevel, m_volumeQueue);
Serilog.Log.Information("Hear: {av},{cvl},{queue}", avgVol, currentVolumnLevel, _volumeQueue);
hear = true;
}

m_volumeQueue.Enqueue(currentVolumnLevel);
// Keep a running queue of the last X sounds as a reference point
if (m_volumeQueue.Count >= MAX_VOLUME_QUEUE_LENGTH) {
m_volumeQueue.Dequeue();
}
_volumeQueue.Add(currentVolumnLevel);
return hear;

}

private int GetAverageVolume()
{
return (int)m_volumeQueue.Average();
return (int)_volumeQueue.Average();
}
}
}

0 comments on commit 67828bd

Please sign in to comment.