text
stringlengths
13
6.01M
using DataStructure.Interfaces; using System; using System.Collections.Generic; using System.Text; namespace DataStructure.Abstractions { public abstract class BaseModel : IBaseModel<string>, IAuditInfo { public string Id { get; set; } public DateTime CreatedAt { get; set; } public DateTime? ModifiedAt { get; set; } public DateTime? DeletedAt { get; set; } } }
using System; using NUnit.Framework; using SFA.DAS.ProviderCommitments.Web.Mappers.Apprentice; using SFA.DAS.ProviderCommitments.Web.Models.Apprentice; using System.Threading.Tasks; using AutoFixture; using Moq; using SFA.DAS.ProviderCommitments.Interfaces; using SFA.DAS.ProviderCommitments.Web.Services.Cache; namespace SFA.DAS.ProviderCommitments.Web.UnitTests.Mappers.Apprentice { [TestFixture] public class EndDateRequestMapperTests { private EndDateRequestMapperFixture _fixture; [SetUp] public void SetUp() { _fixture = new EndDateRequestMapperFixture(); } [Test] public async Task ThenApprenticeshipHashedIdIsMapped() { var result = await _fixture.Act(); Assert.AreEqual(_fixture.ViewModel.ApprenticeshipHashedId, result.ApprenticeshipHashedId); } [Test] public async Task ThenProviderIdIsMapped() { var result = await _fixture.Act(); Assert.AreEqual(_fixture.ViewModel.ProviderId, result.ProviderId); } [Test] public async Task ThenStartDateIsPersistedToCache() { await _fixture.Act(); _fixture.VerifyStartDatePersisted(); } } public class EndDateRequestMapperFixture { private readonly Fixture _fixture; private readonly EndDateRequestMapper _sut; private readonly Mock<ICacheStorageService> _cacheStorage; private readonly ChangeEmployerCacheItem _cacheItem; public StartDateViewModel ViewModel { get; } public EndDateRequestMapperFixture() { _fixture = new Fixture(); ViewModel = new StartDateViewModel { ApprenticeshipHashedId = "DFE546SD", ProviderId = 2350, StartMonth = 6, StartYear = 2020, }; _cacheItem = _fixture.Create<ChangeEmployerCacheItem>(); _cacheStorage = new Mock<ICacheStorageService>(); _cacheStorage.Setup(x => x.RetrieveFromCache<ChangeEmployerCacheItem>(It.Is<Guid>(key => key == ViewModel.CacheKey))) .ReturnsAsync(_cacheItem); _sut = new EndDateRequestMapper(_cacheStorage.Object); } public Task<EndDateRequest> Act() => _sut.Map(ViewModel); public void VerifyStartDatePersisted() { _cacheStorage.Verify(x => x.SaveToCache(It.Is<Guid>(key => key == _cacheItem.Key), It.Is<ChangeEmployerCacheItem>(cache => cache.StartDate == ViewModel.StartDate.MonthYear), It.IsAny<int>())); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace saintify.Business { /// <summary> /// This class is designed to define an artist /// </summary> public class Artist { #region private attributes private int id = -1; private String pictureName = "";//artist's picture's file name (see application ressources.resx) private String name = "";//artist's name private String bio = ""; private List<Song> listOfSongs = null;//list of the artist's songs private int songsTotalDuration = -1;//total duration of the list of songs private int shortestSongDuration = -1; private int longestSongDuration = -1; private int averageSongDuration = -1; private int medianSongDuration = -1; #endregion private attributes #region constructors /// <summary> /// This constructor initializes a new instance of the artist class. /// </summary> /// <param name="id">The artist's id</param> /// <param name="pictureName">The artist's picture (see application ressources.resx</param> /// <param name="name">The artist's name</param> /// <param name="bio">The artist's biography</param> /// <param name="listOfSongs">The list of artist's songs</param> public Artist (int id, String pictureName, String name, String bio, List<Song> listOfSongs) { this.id = id; this.pictureName = pictureName; this.name = name; this.bio = bio; AddSong(listOfSongs); } #endregion constructors #region public methods #region getters and setters /// <summary> /// This getter delivers the value of the private attribute "id" /// </summary> /// <returns>The artist's id</returns> public int Id() { return this.id; } /// <summary> /// This getter delivers the value of the private attribut "title" /// </summary> /// <returns>The artist's picture's file name (see application ressources.resx)</returns> public String PictureName() { return this.pictureName; } /// <summary> /// This getter delivers the value of the private attribute "name" /// </summary> /// <returns>The artist's name</returns> public String Name() { return this.name; } /// <summary> /// This getter delivers the value of the private attribute "bio" /// </summary> /// <returns></returns> public String Bio() { return this.bio; } /// <summary> /// This getter delivers the list of Songs /// </summary> /// <returns>All songs performed by the artists</returns> public List<Song> ListOfSongs() { return this.listOfSongs; } /// <summary> /// This method allows to add a song /// </summary> /// <param name="songToAdd">an object song to add to the list of existing song</param> public void AddSong (Song songToAdd) { if (this.listOfSongs == null) { this.listOfSongs = new List<Song>(); } if (songToAdd != null) { if (SongNotNull(songToAdd)) { this.listOfSongs.Add(songToAdd); updateSongsStatistics(this.listOfSongs); } } } /// <summary> /// This method allows to add a song /// </summary> /// <param name="songToAdd">The song to be added</param> public void AddSong(List<Song> listOfSongsToAdd) { if (listOfSongsToAdd != null) { foreach (Song song in listOfSongsToAdd) { this.AddSong(song); } } } /// <summary> /// This getter delivers the value of the private attribut /// songsTotalDuration /// </summary> public int SongsTotalDuration() { return this.songsTotalDuration; } /// <summary> /// This getter delivers the value of the private attribut /// longestSongDuration /// </summary> public int LongestSongDuration() { return this.longestSongDuration; } /// <summary> /// This getter delivers the value of the private attribut /// shortestSongDuration /// </summary> public int ShortestSongDuration() { return this.shortestSongDuration; } /// <summary> /// This getter delivers the value of the private attribut /// averageSongDuration /// </summary> public int AverageSongDuration() { return this.averageSongDuration; } /// <summary> /// This getter delivers the value of the private attribut /// averageSongDuration /// </summary> public int MedianSonggDuration() { return this.medianSongDuration; } #endregion getters and setters #endregion public methods #region private /// <summary> /// This method prevents duplicate (when adding a song for the second time) /// </summary> /// <param name="songToCheck">The song to be added</param> /// <returns></returns> private bool SongExists(Song songToCheck) { bool exists = false; foreach (Song song in this.listOfSongs) { if (song.Title() == songToCheck.Title() && song.Duration() == songToCheck.Duration()) { exists = true; } } return exists; } /// <summary> /// This method prevents adding "null" song /// </summary> /// <param name="songToCheck">The song to be added</param> /// <returns></returns> private bool SongNotNull(Song songToCheck) { bool songNotEmpty = false; if (songToCheck != null) { songNotEmpty = true; } return songNotEmpty; } private void updateSongsStatistics(List<Song> listOfSongs) { UpdateSongsTotalDuration(listOfSongs); UpdateShortestSongDuration(listOfSongs); UpdateLongestSongDuration(listOfSongs); UpdateAverageSongDuration(listOfSongs); UpdateMedianSongDuration(listOfSongs); } /// <summary> /// This method update the private attribut "songsTotalDuration" /// </summary> /// <param name="listOfSongs">List of Song just updated</param> private void UpdateSongsTotalDuration(List<Song> listOfSongs) { int temp = 0; foreach (Song song in listOfSongs) { temp += song.Duration(); } this.songsTotalDuration = temp; } /// <summary> /// This method update the private attribut "shortestSongDuration" /// </summary> /// <param name="listOfSongs">List of Song just updated</param> private void UpdateShortestSongDuration(List<Song> listOfSongs) { int temp = 0; foreach (Song song in listOfSongs) { int currentSongDuration = song.Duration(); if (temp == 0 || currentSongDuration < temp) { temp = song.Duration(); } } this.shortestSongDuration = temp; } /// <summary> /// This method update the private attribut "longestSongDuration" /// </summary> /// <param name="listOfSongs">List of Song just updated</param> private void UpdateLongestSongDuration(List<Song> listOfSongs) { int temp = 0; foreach (Song song in listOfSongs) { int currentSongDuration = song.Duration(); if (temp == 0 || currentSongDuration > temp) { temp = song.Duration(); } } this.longestSongDuration = temp; } /// <summary> /// This method update the private attribut "averageSongs" /// Be carreful, this method need a object Artist with updpated attribut SongsDuration /// </summary> /// <param name="listOfSongs">List of Song just updated</param> private void UpdateAverageSongDuration(List<Song> listOfSongs) { int temp = 0; if (this.listOfSongs != null) { if (this.listOfSongs.Count != 0) { temp = this.songsTotalDuration / this.listOfSongs.Count(); } } this.averageSongDuration = temp; } /// <summary> /// This method update the private attribut "averageSongs" /// Be carreful, this method need a object Artist with updpated attribut SongsDuration /// </summary> /// <param name="listOfSongs">List of Song just updated</param> private void UpdateMedianSongDuration(List<Song> listOfSongs) { //first we sort the song by duration List<Song> listOfSongsOrdered = listOfSongs.OrderBy(song => song.Duration()).ToList(); //we find the position of the song in the list int medianSongPosition = listOfSongsOrdered.Count / 2; //we get the duration of this the media song int temp = listOfSongsOrdered[medianSongPosition].Duration(); this.medianSongDuration = temp; } #endregion private } }
using damdrempe_zadaca_1.Modeli; using damdrempe_zadaca_1.Podaci.Modeli; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace damdrempe_zadaca_1 { class GeneratorEntiteta { public static List<Ulica> StvoriKorisnike(List<Ulica> ulice) { int korisnikID = 1; foreach (Ulica ulica in ulice) { int brojMalih = (int)Math.Round(ulica.UdioMalih / 100.00 * ulica.BrojMjesta, MidpointRounding.AwayFromZero); int brojSrednjih = (int)Math.Round(ulica.UdioSrednjih / 100.00 * ulica.BrojMjesta, MidpointRounding.AwayFromZero); int brojVelikih = (int)Math.Round(ulica.UdioVelikih / 100.00 * ulica.BrojMjesta, MidpointRounding.AwayFromZero); for (int i = 0; i < brojMalih; i++) { Korisnik korisnik = new Korisnik { ID = korisnikID, Kategorija = Kategorija.Mali, }; ulica.KorisniciMali.Add(korisnik); korisnikID++; } for (int i = 0; i < brojSrednjih; i++) { Korisnik korisnik = new Korisnik { ID = korisnikID, Kategorija = Kategorija.Srednji, }; ulica.KorisniciSrednji.Add(korisnik); korisnikID++; } for (int i = 0; i < brojVelikih; i++) { Korisnik korisnik = new Korisnik { ID = korisnikID, Kategorija = Kategorija.Veliki, }; ulica.KorisniciVeliki.Add(korisnik); korisnikID++; } } return ulice; } public static List<Spremnik> StvoriSpremnike(List<Ulica> ulice, List<Spremnik> spremniciVrste) { int spremnikID = 1; int brojacKorisnici; List<Spremnik> spremnici = new List<Spremnik>(); foreach (Ulica ulica in ulice) { foreach (Spremnik spremnikVrsta in spremniciVrste) { brojacKorisnici = 0; while (brojacKorisnici < ulica.KorisniciMali.Count) { if (spremnikVrsta.BrojnostMali == 0) break; Spremnik spremnik = new Spremnik(); spremnik = new Spremnik(); spremnik.ID = spremnikID; spremnik.Naziv = spremnikVrsta.Naziv; int brojacKorisnikaGrupe = 1; while (brojacKorisnikaGrupe <= spremnikVrsta.BrojnostMali && brojacKorisnici < ulica.KorisniciMali.Count) { Korisnik korisnik = ulica.KorisniciMali[brojacKorisnici]; spremnik.Korisnici.Add(korisnik.ID); brojacKorisnikaGrupe++; brojacKorisnici++; } spremnici.Add(spremnik); } brojacKorisnici = 0; while (brojacKorisnici < ulica.KorisniciSrednji.Count) { if (spremnikVrsta.BrojnostSrednji == 0) break; Spremnik spremnik = new Spremnik(); spremnik = new Spremnik(); spremnik.ID = spremnikID; spremnik.Naziv = spremnikVrsta.Naziv; int brojacKorisnikaGrupe = 1; while (brojacKorisnikaGrupe <= spremnikVrsta.BrojnostSrednji && brojacKorisnici < ulica.KorisniciSrednji.Count) { Korisnik korisnik = ulica.KorisniciSrednji[brojacKorisnici]; spremnik.Korisnici.Add(korisnik.ID); brojacKorisnikaGrupe++; brojacKorisnici++; } spremnici.Add(spremnik); } brojacKorisnici = 0; while (brojacKorisnici < ulica.KorisniciVeliki.Count) { if (spremnikVrsta.BrojnostVeliki == 0) break; Spremnik spremnik = new Spremnik(); spremnik = new Spremnik(); spremnik.ID = spremnikID; spremnik.Naziv = spremnikVrsta.Naziv; int brojacKorisnikaGrupe = 1; while (brojacKorisnikaGrupe <= spremnikVrsta.BrojnostVeliki && brojacKorisnici < ulica.KorisniciVeliki.Count) { Korisnik korisnik = ulica.KorisniciVeliki[brojacKorisnici]; spremnik.Korisnici.Add(korisnik.ID); brojacKorisnikaGrupe++; brojacKorisnici++; } spremnici.Add(spremnik); } } } return spremnici; } } }
using UnityEngine; using UnityEngine.SceneManagement; public class EndingScreen : MonoBehaviour { public void Restart() { SceneManager.LoadScene("Level"); } public void ReturnToMainMenu() { SceneManager.LoadScene("MainMenu"); } }
using UnityEngine; using System.Collections; /* * * All new, an attempt to increase performance of the game once loaded * * */ public class LoadAllResources : MonoBehaviour { // Use this for initialization void Start () { Resources.LoadAll ("/resources"); } }
 namespace DFC.ServiceTaxonomy.GraphSync.GraphSyncers.Interfaces.Contexts { public interface IDescribeRelationshipsItemSyncContext : IItemSyncContext, IDescribeRelationshipsContext { //todo: sort once we swap to c#9 //new IEnumerable<IDescribeRelationshipsContext> ChildContexts { get; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Exercicio25 { class MenorDeCadaColuna { static void Main(string[] args) { { Console.Write("Quantas linhas tem a matriz? "); int N = Convert.ToInt16(Console.ReadLine()); Console.Write("Quantas colunas tem a matriz? "); int M = Convert.ToInt16(Console.ReadLine()); int[,] A = new int[N + 1, M]; for (int I = 0; I <= N - 1; I++) for (int J = 0; J <= M - 1; J++) { Console.Write("A[{0},{1}]=", I, J); A[I, J] = Convert.ToInt16(Console.ReadLine()); } int Linmin; for (int J = 0; J <= M - 1; J++) { Linmin = 0; for (int I = 1; I <= N - 1; I++) if (A[I, J] < A[Linmin, J]) Linmin = I; A[N, J] = A[Linmin, J]; } for (int I = 0; I <= N - 1; I++) { for (int J = 0; J <= M - 1; J++) Console.Write("{0, 6}", A[I, J]); Console.WriteLine(); } for (int J = 0; J <= M - 1; J++) Console.Write("{0, 6}", "-"); Console.WriteLine(); for (int J = 0; J <= M - 1; J++) Console.Write("{0, 6}", A[N, J]); Console.WriteLine(); } } } }
using MonoDevelop.Components.Chart; using System; namespace MonoDevelop.NUnit { internal class TestRunAxis : IntegerAxis { public UnitTestResult[] CurrentResults; public TestRunAxis(bool showLabel) : base(showLabel) { } public override string GetValueLabel(double value) { string result; if (this.CurrentResults == null) { result = ""; } else { int val = (int)value; if (val >= this.CurrentResults.Length) { result = ""; } else { UnitTestResult res = this.CurrentResults[this.CurrentResults.Length - val - 1]; string arg_74_0 = "{0}/{1}"; System.DateTime testDate = res.TestDate; object arg_74_1 = testDate.Day; testDate = res.TestDate; result = string.Format(arg_74_0, arg_74_1, testDate.Month); } } return result; } } }
using Anywhere2Go.AccountingLogic; using Anywhere2Go.DataAccess; using Anywhere2Go.DataAccess.AccountEntity; using Anywhere2Go.DataAccess.Object; using Claimdi.Account.Filters; using Claimdi.Account.Helper; using Claimdi.Account.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Security; namespace Claimdi.Account.Controllers { public class HomeController : Controller { public ActionResult Login() { return View(); } public ActionResult Error(string err = "") { if (err == "UnauthorizedTask") ViewBag.Message = Constant.ErrorMessage.ExistingData; else if (err == "Unauthorized") ViewBag.Message = Constant.ErrorMessage.Unauthorized; else if (err == "noApproveImgTask") ViewBag.Message = Constant.ErrorMessage.noApproveImageTask; else ViewBag.Message = "Error occurred, Please contact administrator."; ViewBag.typeError = err; return View(); } [AuthorizeUser(AccessLevel = "Edit", PageAction = "Home")] public ActionResult NoPermission() { ViewBag.Message = "Your Account No Permission This Task."; return View(); } [HttpPost] public ActionResult Login(LoginModel model) { if (ModelState.IsValid) { AccountProfileLogic acc = new AccountProfileLogic(); var obj = acc.getAccountProfileByUsernamePassword(model.Username, model.Password); if (obj != null) { AccountingAuthentication authen = new AccountingAuthentication() { acc_id = obj.acc_id.ToString(), first_name = obj.first_name, gender = obj.gender, last_name = obj.last_name, username = obj.username, dev_id = obj.dev_id, Role = obj.Role, picture = obj.picture, RolePermissions = (ICollection<eRolePermission>)obj.Role.RolePermissions }; ClaimdiSessionFacade.ClaimdiSession = authen; return RedirectToAction("TaskList", "Task"); } ViewBag.Message = "invalid login, Please try again ."; } return View(model); } public ActionResult Logout() { ClaimdiSessionFacade.Clear(); return RedirectToAction("Login", "Home"); } } }
using System.Collections.Generic; using RunPath.Models; namespace RunPathTests { public class PhotoTestData { private readonly List<Photo> _photos; private readonly int _photoCount; public PhotoTestData() { _photos = new List<Photo> { new Photo { AlbumId = 1, Id = 1, Title = "accusamus beatae ad facilis cum similique qui sunt", Url = "https://via.placeholder.com/600/92c952", ThumbnailUrl = "https://via.placeholder.com/150/92c952" }, new Photo() { AlbumId = 1, Id = 2, Title = "reprehenderit est deserunt velit ipsam", Url = "https://via.placeholder.com/600/771796", ThumbnailUrl = "https://via.placeholder.com/150/771796" }, new Photo() { AlbumId = 2, Id = 3, Title = "officia porro iure quia iusto qui ipsa ut modi", Url = "https://via.placeholder.com/600/24f355", ThumbnailUrl = "https://via.placeholder.com/150/24f355" }, new Photo() { AlbumId = 2, Id = 4, Title = "culpa odio esse rerum omnis laboriosam voluptate repudiandae", Url = "https://via.placeholder.com/600/d32776", ThumbnailUrl = "https://via.placeholder.com/150/d32776" }, new Photo() { AlbumId = 3, Id = 5, Title = "natus nisi omnis corporis facere molestiae rerum in", Url = "https://via.placeholder.com/600/f66b97", ThumbnailUrl = "https://via.placeholder.com/150/f66b97" } }; _photoCount = _photos.Count; } public List<Photo> GetPhotos() => _photos; public int GetPhotoCount() => _photoCount; } }
using System.Threading.Tasks; using SFA.DAS.CommitmentsV2.Shared.Interfaces; using SFA.DAS.ProviderCommitments.Web.Authentication; using SFA.DAS.ProviderCommitments.Infrastructure.OuterApi.Requests; namespace SFA.DAS.ProviderCommitments.Web.Mappers { public class AttachApimUserInfoToSaveRequests<TFrom, TTo> : IMapper<TFrom, TTo> where TFrom : class where TTo : class { private readonly IMapper<TFrom, TTo> _innerMapper; private readonly IAuthenticationService _authenticationService; public AttachApimUserInfoToSaveRequests(IMapper<TFrom, TTo> innerMapper, IAuthenticationService authenticationService) { _innerMapper = innerMapper; _authenticationService = authenticationService; } public async Task<TTo> Map(TFrom source) { var to = await _innerMapper.Map(source); if (to is ApimSaveDataRequest saveDataRequest) { saveDataRequest.UserInfo = GetUserInfo(); } return to; } protected ApimUserInfo GetUserInfo() { if (_authenticationService.IsUserAuthenticated()) { return new ApimUserInfo { UserId = _authenticationService.UserId, UserDisplayName = _authenticationService.UserName, UserEmail = _authenticationService.UserEmail }; } return null; } } }
using AppStore.Application.Services.Exceptions; using System; using System.Collections.Generic; using System.Net; namespace AppStore.API.Helpers { public static class ExceptionConversor { public static HttpStatusCode ToHttpStatusCode(this Exception exception) { Dictionary<Type, HttpStatusCode> dict = GetExceptionDictionary(); if (dict.ContainsKey(exception.GetType())) { return dict[exception.GetType()]; } return dict[typeof(Exception)]; } private static Dictionary<Type, HttpStatusCode> GetExceptionDictionary() { Dictionary<Type, HttpStatusCode> dict = new Dictionary<Type, HttpStatusCode>(); dict[typeof(ResourceNotFoundException)] = HttpStatusCode.NotFound; dict[typeof(InvalidOperationException)] = (HttpStatusCode)422; //Unprocessable Entity dict[typeof(ArgumentException)] = HttpStatusCode.BadRequest; dict[typeof(Exception)] = HttpStatusCode.InternalServerError; return dict; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Threading; namespace Bit8Piano { public interface IEventObserver { void HandleEvent(object sender, EventArgs e); } partial class View : Form { private string[] KeysControlingPiano = new string[] { "a", "s", "d", "f", "g", "h", "j", "k", "w", "e", "r", "y", "u" }; private IBeatModel beatModel; private IBeatController beatController; void minimizeButton_Click(object sender, EventArgs e) { this.WindowState = FormWindowState.Minimized; } void button0_Click(object sender, EventArgs e) { Application.Exit(); } private void button_Up(object sender, MouseEventArgs e) { beatController.Stop(); } private void button_Click(object sender, EventArgs e) { //DisablePianoKeys(); foreach (var pianoKeyButton in this.pianoKeysButtons) { if (Object.ReferenceEquals(sender, pianoKeyButton)) { Button f = (Button)pianoKeyButton; beatController.PerformActionWithStrategy(f.TabIndex); } } } private delegate void EnablePianoKeysDelegate(); private void EnablePianoKeys() { if (this.InvokeRequired) { this.BeginInvoke(new EnablePianoKeysDelegate(EnablePianoKeys), new object[] { }); return; } pianoKeysButtons.ForEach(key => { key.Enabled = true; key.BackColor = System.Drawing.Color.White; }); } public void DisablePianoKeys() { pianoKeysButtons.ForEach(key => key.Enabled = false); } private KeyboardButton UsedKeysActivationStrategy(int customIndex) { KeyboardButton buttonActivatedByKey; switch (customIndex) { case 0: buttonActivatedByKey = this.button1; break; case 1: buttonActivatedByKey = this.button2; break; case 2: buttonActivatedByKey = this.button3; break; case 3: buttonActivatedByKey = this.button4; break; case 4: buttonActivatedByKey = this.button5; break; case 5: buttonActivatedByKey = this.button6; break; case 6: buttonActivatedByKey = this.button7; break; case 7: buttonActivatedByKey = this.button8; break; case 8: buttonActivatedByKey = this.button9; break; case 9: buttonActivatedByKey = this.button10; break; case 10: buttonActivatedByKey = this.button11; break; case 11: buttonActivatedByKey = this.button12; break; case 12: buttonActivatedByKey = this.button13; break; default: throw new NotSupportedException("Theres no button assigned for this key"); } return buttonActivatedByKey; } void View_KeyDown(object sender, KeyEventArgs e) { //if (this.keyDownOnce == true) //{ //should call c++ function for getting physical keyboard layout, in order to keep it working at any possible keyboard if (KeysControlingPiano.Contains(e.KeyCode.ToString().ToLower())) { var customIndex = Array.IndexOf(KeysControlingPiano, e.KeyCode.ToString().ToLower()); var actualButtonForKey = UsedKeysActivationStrategy(customIndex); actualButtonForKey.PerformKeyDown(); } //this.keyDownOnce = false; //} } void View_KeyUp(object sender, KeyEventArgs e) { //this.keyDownOnce = true; if (KeysControlingPiano.Contains(e.KeyCode.ToString().ToLower())) { var customIndex = Array.IndexOf(KeysControlingPiano, e.KeyCode.ToString().ToLower()); var actualButtonForKey = UsedKeysActivationStrategy(customIndex); actualButtonForKey.PerformKeyUp(); } } public View(IBeatController beatController, IBeatModel beatModel) { this.beatController = beatController; this.beatModel = beatModel; InitializeComponent(); } } }
using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using System.Linq; using Discord.Commands; using Discord.WebSocket; namespace FifthBot.Resources.Preconditions { public class RequireDMAttribute : PreconditionAttribute { public override Task<PreconditionResult> CheckPermissionsAsync(ICommandContext context, CommandInfo command, IServiceProvider services) { if (context.Channel.GetType() == typeof(SocketDMChannel)) { return Task.FromResult(PreconditionResult.FromSuccess()); } return Task.FromResult(PreconditionResult.FromError("You cannot run this command in this channel, sowwy!")); } } }
using Datos; using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Negocio { public class ServicioPorRuta { public int idRutaAerea { get; set; } public int idTipoServicio { get; set; } public DataTable obtenerTodosPorIdRuta(int id) { string[] parametros = {"@id"}; DatosSistema datos = new DatosSistema(); return datos.getDatosTabla("[INFONIONIOS].[spObtenerServiciosPorRutaPorIdRuta]", parametros, id); } public List<ServicioPorRuta> obtenerListaPorIdRuta(int id) { List<ServicioPorRuta> servicios = new List<ServicioPorRuta>(); DataTable dt = this.obtenerTodosPorIdRuta(id); foreach (DataRow row in dt.Rows) { ServicioPorRuta s = new ServicioPorRuta(); s.idRutaAerea = id; s.idTipoServicio = Int32.Parse(row["TIPO_SERVICIO_ID"].ToString()); servicios.Add(s); } return servicios; } internal void elimiarPorIdRuta(int id) { string[] parametros = { "@id" }; DatosSistema datos = new DatosSistema(); datos.Ejecutar("[INFONIONIOS].[spEliminarServiciosPorIdRuta]", parametros, id); } internal void insertarServicios(List<TipoServicio> servicios, int id) { foreach (TipoServicio ts in servicios) { this.insertarServicioPorRuta(ts.idTipoServicio, id); } } private void insertarServicioPorRuta(int idServicio, int idRuta) { string[] parametros = { "@idServicio","@idRuta" }; DatosSistema datos = new DatosSistema(); datos.Ejecutar("[INFONIONIOS].[spInsertarServicioPorRuta]", parametros, idServicio,idRuta); } } }
using Microsoft.Owin; using Owin; [assembly: OwinStartupAttribute(typeof(SEELahore2k18.Startup))] namespace SEELahore2k18 { using System.ComponentModel; public partial class Startup { public void Configuration(IAppBuilder app) { ConfigureAuth(app); } } }
using System; using UnityAtoms.MonoHooks; namespace UnityAtoms.MonoHooks { /// <summary> /// Event Reference of type `CollisionGameObjectPair`. Inherits from `AtomEventReference&lt;CollisionGameObjectPair, CollisionGameObjectVariable, CollisionGameObjectPairEvent, CollisionGameObjectVariableInstancer, CollisionGameObjectPairEventInstancer&gt;`. /// </summary> [Serializable] public sealed class CollisionGameObjectPairEventReference : AtomEventReference< CollisionGameObjectPair, CollisionGameObjectVariable, CollisionGameObjectPairEvent, CollisionGameObjectVariableInstancer, CollisionGameObjectPairEventInstancer>, IGetEvent { } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CommandPreprocessor { public class CommandPreprocessor { #region Properties private static readonly log4net.ILog logger = LogManager.LogManager.GetLogger(); private WorkingPlane workingPlane; private UnitsPosition currentPosition; private UnitsPosition referencePosition; // Origen de la pieza a fresar #endregion #region Constructor private static CommandPreprocessor instance; protected CommandPreprocessor() { this.workingPlane = WorkingPlane.XY; this.currentPosition = new UnitsPosition(0, 0, 0); this.referencePosition = new UnitsPosition(0, 0, 0); } public static CommandPreprocessor GetInstance() { if (instance == null) { instance = new CommandPreprocessor(); } return instance; } #endregion #region Getters & Setters public WorkingPlane WorkingPlane { get { return this.workingPlane; } set { this.workingPlane = value; } } public UnitsPosition CurrentPosition { get { return this.currentPosition; } set { this.currentPosition = value; } } public UnitsPosition ReferencePosition { get { return this.referencePosition; } set { this.referencePosition = value; } } #endregion #region Private Methods private double GetValueParameter(char parameterName, string command) { foreach(string parameter in command.ToUpper().Split(' ')) { if (parameter[0] == parameterName) { return double.Parse(parameter.Substring(1)); } } return 0; } private bool HasValueParameter(char parameterName, string command) { return command.ToUpper().IndexOf(parameterName) != -1; } private UnitsPosition GetFinalPosition(string command) { UnitsPosition result = new UnitsPosition(); if (Configuration.absoluteProgamming) { result.X = HasValueParameter('X', command) ? GetValueParameter('X', command) + this.ReferencePosition.X : CurrentPosition.X; result.Y = HasValueParameter('Y', command) ? GetValueParameter('Y', command) + this.ReferencePosition.Y : CurrentPosition.Y; result.Z = HasValueParameter('Z', command) ? this.ReferencePosition.Z - GetValueParameter('Z', command) : CurrentPosition.Z; } else { // Translate to relative programming mode result.X = HasValueParameter('X', command) ? GetValueParameter('X', command) + this.CurrentPosition.X : CurrentPosition.X; result.Y = HasValueParameter('Y', command) ? GetValueParameter('Y', command) + this.CurrentPosition.Y : CurrentPosition.Y; result.Z = HasValueParameter('Z', command) ? this.CurrentPosition.Z - GetValueParameter('Z', command) : CurrentPosition.Z; } logger.Info("voy a ir al Z " + result.Z); if (result.Z < 0) throw new Exception("Movimiento Inválido. (Eje Z sobrepasa límite superior)"); // If the values are in inches, convert to millimeters if (!Configuration.millimetersProgramming) { result.X *= 25.4; result.Y *= 25.4; result.Z *= 25.4; } return result; } private UnitsPosition GetFromRadius(double r, string command) { double midX, midY, midZ, cat1x, cat1y, cat1z, cat1, cat2x, cat2y, cat2z, cat2; logger.Info("Get from radius"); UnitsPosition final = GetFinalPosition(command); UnitsPosition centerPosition = new UnitsPosition(); // componentes de Punto Medio de segmento que une Punto Inicial con Punto Final midZ = (final.Z + CurrentPosition.Z) / 2; midY = (final.Y + CurrentPosition.Y) / 2; midX = (final.X + CurrentPosition.X) / 2; // componentes de Longitud desde Punto Inicial a Punto Medio de segmento cat1x = midX - CurrentPosition.X; cat1y = midY - CurrentPosition.Y; cat1z = midZ - CurrentPosition.Z; switch (this.WorkingPlane) { case WorkingPlane.XY: cat1 = Math.Sqrt(cat1x * cat1x + cat1y * cat1y); if (cat1 > Math.Abs(r)) { logger.Error("Imposible realizar arco: " + command + ". (Distancia media entre punto inicial y final es mayor al radio)"); throw new Exception("Imposible realizar arco: " + command + ". (Distancia media entre punto inicial y final es mayor al radio)"); } cat2 = Math.Sqrt(r * r - cat1 * cat1); cat2x = cat1y * cat2 / cat1; cat2y = -cat1x * cat2 / cat1; if (r > 0) { centerPosition.X = midX + cat2x; centerPosition.Y = midY + cat2y; } else { centerPosition.X = midX - cat2x; centerPosition.Y = midY - cat2y; } centerPosition.Z = midZ; break; case WorkingPlane.XZ: cat1 = Math.Sqrt(cat1x * cat1x + cat1z * cat1z); if (cat1 > Math.Abs(r)) { logger.Error("Imposible realizar arco: " + command + ". (Distancia media entre punto inicial y final es mayor al radio)"); throw new Exception("Imposible realizar arco: " + command + ". (Distancia media entre punto inicial y final es mayor al radio)"); } cat2 = Math.Sqrt(r * r - cat1 * cat1); cat2x = cat1z * cat2 / cat1; cat2z = -cat1x * cat2 / cat1; if (r > 0) { centerPosition.X = midX + cat2x; centerPosition.Z = midZ + cat2z; } else { centerPosition.X = midX - cat2x; centerPosition.Z = midZ - cat2z; } centerPosition.Y = midY; break; case WorkingPlane.YZ: cat1 = Math.Sqrt(cat1y * cat1y + cat1z * cat1z); if (cat1 > Math.Abs(r)) { logger.Error("Imposible realizar arco: " + command + ". (Distancia media entre punto inicial y final es mayor al radio)"); throw new Exception("Imposible realizar arco: " + command + ". (Distancia media entre punto inicial y final es mayor al radio)"); } cat2 = Math.Sqrt(r * r - cat1 * cat1); cat2y = cat1z * cat2 / cat1; cat2z = -cat1y * cat2 / cat1; if (r > 0) { centerPosition.Y = midY + cat2y; centerPosition.Z = midZ + cat2z; } else { centerPosition.Y = midY - cat2y; centerPosition.Z = midZ - cat2z; } centerPosition.X = midX; break; } return centerPosition; } private UnitsPosition GetCenterPosition(string command) { UnitsPosition result = new UnitsPosition(); if (HasValueParameter('R', command)) { double r = GetValueParameter('R', command); result = GetFromRadius(r, command); } else { // The center point is relative to the start position... Translate to absolute programming mode result.X = GetValueParameter('I', command) + this.CurrentPosition.X; result.Y = GetValueParameter('J', command) + this.CurrentPosition.Y; result.Z = GetValueParameter('K', command) + this.CurrentPosition.Z; } return result; } private List<UnitsPosition> ProcessCurvePlaneXY(string code) { List<UnitsPosition> result = new List<UnitsPosition>(); double feedRate = HasValueParameter('F', code) ? GetValueParameter('F', code) : Configuration.defaultFeedrate; // Ver qué valor va cuando no hay valor - CONFIGURACION? - UnitsPosition startPosition = this.CurrentPosition; logger.Info("procesando curva XY"); UnitsPosition finalPosition = this.GetFinalPosition(code); UnitsPosition centerPosition = this.GetCenterPosition(code); int gCode = Convert.ToInt32(GetValueParameter('G', code)); bool clockwise = gCode == 2 ? true : false; double aX, aY, bX, bY, angleA, angleB, angle, radius, length; int steps; aX = currentPosition.X - centerPosition.X; aY = currentPosition.Y - centerPosition.Y; bX = finalPosition.X - centerPosition.X; bY = finalPosition.Y - centerPosition.Y; angleA = clockwise ? Math.Atan2(bY, bX) : Math.Atan2(aY, aX); angleB = clockwise ? Math.Atan2(aY, aX) : Math.Atan2(bY, bX); if (angleB <= angleA) angleB += 2 * Math.PI; angle = angleB - angleA; radius = Math.Sqrt(aX * aX + aY * aY); length = radius * angle; steps = (int)(length / Configuration.millimetersCurveSection); steps = steps == 0 ? 1 : steps; for (int s = 1; s <= steps; s++) { UnitsPosition sectionPosition = new UnitsPosition(); int step = clockwise ? steps - s : s; sectionPosition.X = centerPosition.X + radius * Math.Cos(angleA + angle * ((float)step / steps)); sectionPosition.Y = centerPosition.Y + radius * Math.Sin(angleA + angle * ((float)step / steps)); sectionPosition.Z = (finalPosition.Z - startPosition.Z) * ((float)s / steps) + this.ReferencePosition.Z; if ((sectionPosition.X < 0) || (sectionPosition.Y < 0) || (sectionPosition.Z < 0)) { logger.Error("Underflow procesando: " + code + "."); throw new Exception("Underflow procesando: " + code + ". (PuntoDestino: X" + sectionPosition.X + " Y" + sectionPosition.Y + " Z" + sectionPosition.Z); } // Traducir la curva (G02 / G03) como varias rectas (G01) result.Add(sectionPosition); } return result; } private List<UnitsPosition> ProcessCurvePlaneXZ(string code) { List<UnitsPosition> result = new List<UnitsPosition>(); double feedRate = HasValueParameter('F', code) ? GetValueParameter('F', code) : Configuration.defaultFeedrate; // Ver qué valor va cuando no hay valor - CONFIGURACION? - UnitsPosition startPosition = this.CurrentPosition; UnitsPosition finalPosition = this.GetFinalPosition(code); UnitsPosition centerPosition = this.GetCenterPosition(code); int gCode = Convert.ToInt32(GetValueParameter('G', code)); bool clockwise = gCode == 2 ? true : false; double aX, aZ, bX, bZ, angleA, angleB, angle, radius, length; int steps; aX = currentPosition.X - centerPosition.X; aZ = currentPosition.Z - centerPosition.Z; bX = finalPosition.X - centerPosition.X; bZ = finalPosition.Z - centerPosition.Z; angleA = clockwise ? Math.Atan2(bZ, bX) : Math.Atan2(aZ, aX); angleB = clockwise ? Math.Atan2(aZ, aX) : Math.Atan2(bZ, bX); if (angleB <= angleA) angleB += 2 * Math.PI; angle = angleB - angleA; radius = Math.Sqrt(aX * aX + aZ * aZ); length = radius * angle; steps = (int)(length / Configuration.millimetersCurveSection); for (int s = 1; s <= steps; s++) { UnitsPosition sectionPosition = new UnitsPosition(); int step = clockwise ? steps - s : s; sectionPosition.X = centerPosition.X + radius * Math.Cos(angleA + angle * ((float)step / steps)); sectionPosition.Y = (finalPosition.Y - startPosition.Y) * ((float)s / steps); sectionPosition.Z = centerPosition.Z + radius * Math.Sin(angleA + angle * ((float)step / steps)); if ((sectionPosition.X < 0) || (sectionPosition.Y < 0) || (sectionPosition.Z < 0)) { logger.Error("Underflow procesando: " + code + "."); throw new Exception("Underflow procesando: " + code + "."); } result.Add(sectionPosition); } return result; } private List<UnitsPosition> ProcessCurvePlaneYZ(string code) { List<UnitsPosition> result = new List<UnitsPosition>(); double feedRate = HasValueParameter('F', code) ? GetValueParameter('F', code) : Configuration.defaultFeedrate; // Ver qué valor va cuando no hay valor - CONFIGURACION? - UnitsPosition startPosition = this.CurrentPosition; UnitsPosition finalPosition = this.GetFinalPosition(code); UnitsPosition centerPosition = this.GetCenterPosition(code); int gCode = Convert.ToInt32(GetValueParameter('G', code)); bool clockwise = gCode == 2 ? true : false; double aY, aZ, bY, bZ, angleA, angleB, angle, radius, length; int steps; aY = currentPosition.Y - centerPosition.Y; aZ = currentPosition.Z - centerPosition.Z; bY = finalPosition.Y - centerPosition.Y; bZ = finalPosition.Z - centerPosition.Z; angleA = clockwise ? Math.Atan2(bZ, bY) : Math.Atan2(aZ, aY); angleB = clockwise ? Math.Atan2(aZ, aY) : Math.Atan2(bZ, bY); if (angleB <= angleA) angleB += 2 * Math.PI; angle = angleB - angleA; radius = Math.Sqrt(aY * aY + aZ * aZ); length = radius * angle; steps = (int)(length / Configuration.millimetersCurveSection); for (int s = 1; s <= steps; s++) { UnitsPosition sectionPosition = new UnitsPosition(); int step = clockwise ? steps - s : s; sectionPosition.X = (finalPosition.X - startPosition.X) * ((float)s / steps); sectionPosition.Y = centerPosition.Y + radius * Math.Cos(angleA + angle * ((float)step / steps)); sectionPosition.Z = centerPosition.Z + radius * Math.Sin(angleA + angle * ((float)step / steps)); if ((sectionPosition.X < 0) || (sectionPosition.Y < 0) || (sectionPosition.Z < 0)) { logger.Error("Underflow procesando: " + code + "."); throw new Exception("Underflow procesando: " + code + "."); } result.Add(sectionPosition); } return result; } private List<UnitsPosition> ProcessCurveCommand(string code) { switch (this.WorkingPlane) { case WorkingPlane.XY: return this.ProcessCurvePlaneXY(code); case WorkingPlane.XZ: return this.ProcessCurvePlaneXZ(code); case WorkingPlane.YZ: return this.ProcessCurvePlaneYZ(code); } // no deberia llegar nunca aca return new List<UnitsPosition>(); } #endregion #region Public Methods private List<string> ProcessCommand(string command) { int code; List<string> result = new List<string>(); double feedRate = HasValueParameter('F', command) ? GetValueParameter('F', command) : Configuration.defaultFeedrate; // Ver qué valor va cuando no hay valor - CONFIGURACION? - if (HasValueParameter('G', command)) { code = Convert.ToInt32(GetValueParameter('G', command)); string finalLine; switch (code) { case 0: case 1: UnitsPosition line = this.GetFinalPosition(command); finalLine = line.ToStepsPosition(CurrentPosition, feedRate, code == 0).ToString(-1); logger.Debug("Resultado Linea: " + finalLine); result.Add(finalLine); CurrentPosition = line; break; case 2: case 3: List<UnitsPosition> curveLines = this.ProcessCurveCommand(command); foreach (UnitsPosition curveLine in curveLines) { finalLine = curveLine.ToStepsPosition(CurrentPosition, feedRate).ToString(-1); logger.Debug("Resultado Sección de Curva: " + finalLine); result.Add(finalLine); CurrentPosition = curveLine; } break; case 4: result.Add(command); break; case 17: this.WorkingPlane = WorkingPlane.XY; break; case 18: this.WorkingPlane = WorkingPlane.XZ; break; case 19: this.WorkingPlane = WorkingPlane.YZ; break; case 20: Configuration.millimetersProgramming = false; break; case 21: Configuration.millimetersProgramming = true; break; case 90: Configuration.absoluteProgamming = true; break; case 91: Configuration.absoluteProgamming = false; break; default: logger.Error("Comando no soportado: " + command + "."); throw new Exception("Comando no soportado: " + command + "."); } } else if (HasValueParameter('M', command)) { code = Convert.ToInt32(GetValueParameter('M', command)); switch(code) { case 0: case 2: case 3: case 4: case 5: result.Add(command); break; default: logger.Error("Comando no soportado: " + command + "."); throw new Exception("Comando no soportado: " + command + "."); } } return result; } public List<string> ProcessProgram(List<string> program) { List<string> result = new List<string>(); try { logger.Info("Iniciando Preprocesamiento de programa. Parametros:" + Environment.NewLine + "Programación Absoluta: " + Configuration.absoluteProgamming + Environment.NewLine + "Programación en Milímetros: " + Configuration.millimetersProgramming + Environment.NewLine + "Milímetros de Sección Curva: " + Configuration.millimetersCurveSection + Environment.NewLine + "Milímetros por Minuto (default): " + Configuration.defaultFeedrate); this.CurrentPosition = this.ReferencePosition; // Process every command in the program foreach (string cmd in program) { logger.Info("Procesando comando: " + cmd); if (!string.IsNullOrEmpty(cmd)) { result.AddRange(this.ProcessCommand(cmd)); logger.Info("actualizando currentPosition"); this.CurrentPosition = this.GetFinalPosition(cmd); } } return result; } catch (Exception) { throw; } } #endregion } }
using System.Data.Common; using System.Threading; using System.Threading.Tasks; using Marten.Linq; using Npgsql; namespace Marten.Services.BatchQuerying { public class CountHandler : IDataReaderHandler<long> { private readonly TaskCompletionSource<long> _source = new TaskCompletionSource<long>(); public void Configure(NpgsqlCommand command, DocumentQuery query) { query.ConfigureForCount(command); } public Task<long> ReturnValue => _source.Task; public async Task Handle(DbDataReader reader, CancellationToken token) { await reader.ReadAsync(token).ConfigureAwait(false); _source.SetResult(reader.GetInt64(0)); } } }
namespace Sentry.Tests.Internals; [UsesVerify] public class CollectionExtensionsTests { [Fact] public Task GetOrCreate_invalid_type() { var dictionary = new ConcurrentDictionary<string, object> {["key"] = 1}; return Throws(() => dictionary.GetOrCreate<Value>("key")) .IgnoreStackTrace(); } private class Value { } }
using A4CoreBlog.Data.Models; using A4CoreBlog.Data.Services.Contracts; using A4CoreBlog.Data.UnitOfWork; using AutoMapper; using AutoMapper.QueryableExtensions; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using A4CoreBlog.Data.ViewModels; namespace A4CoreBlog.Data.Services.Implementations { public class CommentService : ICommentService { private readonly IBlogSystemData _data; public CommentService(IBlogSystemData data) { _data = data; } public async Task<int> Add<T>(T model) { var comment = Mapper.Map<Comment>(model); _data.Comments.Add(comment); await _data.SaveChangesAsync(); return comment.Id; } public async Task<int> AddBlogComment<T>(T model, int blogId) { var commentId = await Add(model); var dbBlogComment = new BlogComment { BlogId = blogId, CommentId = commentId }; _data.BlogComments.Add(dbBlogComment); _data.SaveChanges(); return dbBlogComment.Id; } public async Task<int> AddBlogComment(PostACommentViewModel model) { var user = _data.Users.All().FirstOrDefault(u => u.UserName == model.AuthorName); if (user != null) { model.AuthorId = user.Id; return await AddBlogComment(model, model.ForId); } return 0; } public async Task<int> AddPostComment<T>(T model, int postId) { var commentId = await Add(model); var dbPostComment = new PostComment { PostId = postId, CommentId = commentId }; _data.PostComments.Add(dbPostComment); await _data.SaveChangesAsync(); return dbPostComment.Id; } public async Task<int> AddPostComment(PostACommentViewModel model) { var user = _data.Users.All().FirstOrDefault(u => u.UserName == model.AuthorName); if (user != null) { model.AuthorId = user.Id; return await AddPostComment(model, model.ForId); } return 0; } public async Task<bool> Delete(int id) { try { var bComment = _data.BlogComments.All().FirstOrDefault(bc => bc.CommentId == id); if (bComment != null) { _data.BlogComments.Delete(bComment.Id); } var pComment = _data.PostComments.All().FirstOrDefault(pc => pc.CommentId == id); if (pComment != null) { _data.PostComments.Delete(pComment.Id); } _data.Comments.Delete(id); await _data.SaveChangesAsync(); return true; } catch (Exception ex) { return false; } } public async Task<IQueryable<T>> GetAll<T>() { return _data.Comments.All().ProjectTo<T>(); } public async Task<IQueryable<T>> GetAllForBlog<T>(int blogId) { var result = _data.BlogComments.All() .Where(bc => bc.BlogId == blogId) .ProjectTo<T>(); return result; } public async Task<IQueryable<T>> GetAllForPost<T>(int postId) { var result = _data.PostComments.All() .Where(pc => pc.PostId == postId) .ProjectTo<T>(); return result; } } }
/************************************************************************************* Extended WPF Toolkit Copyright (C) 2007-2013 Xceed Software Inc. This program is provided to you under the terms of the Microsoft Public License (Ms-PL) as published at http://wpftoolkit.codeplex.com/license For more features, controls, and fast professional support, pick up the Plus Edition at http://xceed.com/wpf_toolkit Stay informed: follow @datagrid on Twitter or Like http://facebook.com/datagrids ***********************************************************************************/ using System.Windows; using System.Windows.Markup; [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )] [assembly: XmlnsPrefix( "http://schemas.xceed.com/wpf/xaml/avalondock", "xcad" )] [assembly: XmlnsDefinition( "http://schemas.xceed.com/wpf/xaml/avalondock", "Xceed.Wpf.AvalonDock" )] [assembly: XmlnsDefinition( "http://schemas.xceed.com/wpf/xaml/avalondock", "Xceed.Wpf.AvalonDock.Controls" )] [assembly: XmlnsDefinition( "http://schemas.xceed.com/wpf/xaml/avalondock", "Xceed.Wpf.AvalonDock.Converters" )] [assembly: XmlnsDefinition( "http://schemas.xceed.com/wpf/xaml/avalondock", "Xceed.Wpf.AvalonDock.Layout" )] [assembly: XmlnsDefinition( "http://schemas.xceed.com/wpf/xaml/avalondock", "Xceed.Wpf.AvalonDock.Themes" )]
// Bar POS, class BillHeader // Versiones: // V0.01 14-May-2018 Moisés: Basic skeleton // V0.02 15-May-2018 Moisés: CompanyData spreed into name,addres // V0.03 18-May-2018 Moisés: Method ToString using System; namespace BarPOS { public struct Company { public string Name; public string Address; } public class BillHeader { public Company CompanyData { get; set; } public int Table { get; set; } public int Number { get; set; } public DateTime Date { get; set; } public User Employee { get; set; } public BillHeader(int number, User employee, int table) { CompanyData = new Company { Name = "Moisex S.L", Address = "C/ Lillo Juan, 128" }; Table = table; Employee = employee; Number = number; Date = DateTime.Now; } public override string ToString() { return Table + "·" + Number + "·" + Date + "=" + Employee.ToString(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Ezconet.GerenciamentoProjetos.Infra.Data.Repositories { public sealed class UsuarioRepository : Domain.Contracts.Repositories.IUsuarioRepository { private readonly Contexts.GerenciamentoProjetosDbContext _context; public UsuarioRepository( Contexts.GerenciamentoProjetosDbContext context) { _context = context; } public Domain.Entities.UsuarioEntity GetByCodigo(int codigo) { //using (var contexto = new Contexts.GerenciamentoProjetosDbContext()) //{ // contexto.SaveChanges(); // return contexto.UsuarioEntities // .SingleOrDefault(x => x.Codigo == codigo); //} return _context.UsuarioEntities .SingleOrDefault(x => x.Codigo == codigo); } } }
using Contracts; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AnalysisEngine.Analyzers { public class MsBuildAnalyzer : AnalyzerBase, IAnalyzer { public MsBuildAnalyzer() { Name = "MsBuild"; Threats = new List<Threat>(){ //new Threat{FilePath = @"C:\Windows\Microsoft.Net\Framework\v2.0.50727\MSBuild.exe", Name=Name,Type=VulnerabilityType.MSBuild_v2_0_50727 } , //new Threat{FilePath = @"C:\Windows\Microsoft.Net\Framework\v3.5\MSBuild.exe", Name=Name,Type=VulnerabilityType.MSBuild_v3_5 } , //new Threat{FilePath = @"C:\Windows\Microsoft.Net\Framework\v4.0.30319\MSBuild.exe", Name=Name,Type=VulnerabilityType.MSBuild_v4_0_30319 } , //new Threat{FilePath = @"C:\Windows\Microsoft.Net\Framework64\v2.0.50727\MSBuild.exe",Name=Name,Type=VulnerabilityType.MSBuild_x64_v2_0_50727 } , //new Threat{FilePath = @"C:\Windows\Microsoft.Net\Framework64\v3.5\MSBuild.exe", Name=Name,Type=VulnerabilityType.MSBuild_x64_v3_5 } , new Threat{FilePath = @"C:\Windows\Microsoft.Net\Framework64\v4.0.30319\MSBuild.exe", Name=Name,Type=VulnerabilityType.MSBuild_x64_v4_0_30319 } , }; } } }
 namespace _1.TaskSchool { using System; using System.Linq; public class CustomSchoolExeption : Exception { readonly string message; //constructors public CustomSchoolExeption() { } public CustomSchoolExeption(string errorMessage) { this.message = errorMessage; } } }
using System.Collections.Generic; using FsCheck; //using FsCheck.Xunit; using NUnit.Framework; using Task3; using Task3.Testing; using Xunit; namespace FS3.Testing { public class Tests { //[Fact] //public void MoveProperty() //{ // var property = Prop.ForAll(MovesArbitrary.Move(), // move => // { // var message = // "[[\"x\", 2, \"y\", 2, \"v\", \"x\"], [\"x\", 1, \"y\", 0, \"v\", \"o\"], [\"x\", 0, \"y\", 0, \"v\", \"x\"], [\"x\", 1, \"y\", 1, \"v\", \"o\"], [\"x\", 2, \"y\", 0, \"v\", \"x\"]]"; // var dictionaryFromMsg = MessageDecoder.ParseMoves(message); // var newMessage = MessageEncoder.UpdateMessage(message, move); // var dictionaryFromNewMessage = MessageDecoder.ParseMoves(newMessage); // /* dictionaryFromMsg.Add(dictionaryFromMsg.Count.ToString(), new Dictionary<string, string>() // { // {"v", "o"}, // {"x", move.Item1.ToString()}, // {"y", move.Item2.ToString()} // }); // Assert.Equal(dictionaryFromMsg, dictionaryFromNewMessage);*/ // }); // property.QuickCheckThrowOnFailure(); //} } }
// ScreenShaker2D: shakes a 2D camera to a specified magnitude, for a specified duration // Usage: // ScreenShaker2D shaker = new ScreenShaker2D(my2DCamera, duration:0.2f, magnitude:4); // shaker.Shake(); using Godot; using System; public class ScreenShaker2D { private Camera2D _camera; private Random _rand = new Random(); private Vector2 _initialOffset; // private float _duration; // private int _magnitude; public ScreenShaker2D(Camera2D camera)//, float duration = 0.18f, int magnitude = 3) { _camera = camera; // _duration = duration; // _magnitude = magnitude; _initialOffset = _camera.Offset; } // Call this externally to cause the shake effect public async void Shake(float duration, int magnitude) { // Upon a new shake, start time at 0 float time = 0; // Until time elapsed passes the specified duration of the shake while (time < duration) { // Increment _time but not beyond max duration time += _camera.GetProcessDeltaTime(); time = Math.Min(time, duration); // Every frame set the offset to a random x and y value within the specified magnitude // So with a larger magnitude the offset will be greater and the screen will appear to shake more Vector2 offset = new Vector2(); offset.x = (float) _rand.Next(-magnitude, magnitude + 1); offset.y = (float) _rand.Next(-magnitude, magnitude + 1); _camera.Offset = _initialOffset + offset; // Must be called otherwise the screen will freeze throughout the loop await _camera.ToSignal(_camera.GetTree(), "idle_frame"); } // After the shake set time back to 0 so we can shake all over again when needed _camera.Offset = _initialOffset; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _4.DancingBits { class CheckForDancers { static void Main() { int k = int.Parse(Console.ReadLine()); int n = int.Parse(Console.ReadLine()); uint num; uint counter1 = 0; uint counter0 = 0; int counterFinal = 0; uint bit = 0; for (int count = 0; count < n; count++) { num = uint.Parse(Console.ReadLine()); bit = 0; int bitPosition = 0; uint bitStart = 0; for (int counterBit = 0; counterBit < 32; counterBit++) { bitStart = GetBitInPosition(counterBit, num); if (bitStart == 1) { bitPosition = counterBit; break; } } for (int counter = bitPosition; counter < 32; counter++) { bit = GetBitInPosition(counter, num); if (bit == 1) { counter1++; if (counter0 == k) { counterFinal++; } counter0 = 0; } else { counter0++; if (counter1 == k) { counterFinal++; } counter1 = 0; } } } if (bit == 1) { if (counter1 == k) { counterFinal++; } } else { if (counter0 == k) { counterFinal++; } } Console.WriteLine(counterFinal); } private static uint GetBitInPosition(int bitPosition, uint number) { uint bit = 0; uint mask = 2147483648; mask = mask >> bitPosition; uint nAndMask = number & mask; if (nAndMask == mask) { return 1; } else { return 0; } } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace Omega.Lib.APNG.Chunks { public abstract class APngChunk { public ChunkType ChunkType { get; private set; } public abstract MemoryStream Data { get; } protected APngChunk(ChunkType type) { ChunkType = type; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class RoomStarter : MonoBehaviour { public ClosedEnemyDoors ced; private void OnTriggerExit2D(Collider2D other) { ced.ActivateRoom(other); } }
using Xamarin.Forms; using System; namespace ProctorCreekGreenwayApp { public partial class App : Application { public static RestService DBManager {get; private set;} static PCGLocalDatabase database; public App() { InitializeComponent(); // Initialize database manager DBManager = new RestService(); MainPage = new MainPage(); } public static PCGLocalDatabase Database { get { if (database == null) { // Database not instantiated yet database = new PCGLocalDatabase(DependencyService.Get<IDBFileHelper>().GetLocalFilePath("PCGAppSQLite.db3")); } return database; } } protected override void OnStart() { // Handle when your app starts } protected override void OnSleep() { // Handle when your app sleeps } protected override void OnResume() { // Handle when your app resumes } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class GameController : MonoBehaviour { public static GameController Instance; public GameObject player; public GameObject prefabsParent; //public int NUMBER_OF_OBSTACLES; //public int NUMBER_OF_BROKEN_PARTS; //public float distanceFromTopEdge; //public float distanceFromBottomEdge; //public float distanceFromRightEdge; //public float distanceFromLeftEdge; //public GameObject borderTop; //public GameObject borderBottom; //public GameObject borderRight; //public GameObject borderLeft; public bool gameOver = false; //private float topObjectsLimit; //private float bottomObjectsLimit; //private float rightObjectsLimit; //private float leftObjectsLimit; void Awake() { if (Instance == null) { Instance = this; } else if (Instance != this) { Destroy(gameObject); } //this.topObjectsLimit = this.borderTop.transform.position.y - this.distanceFromTopEdge; //this.bottomObjectsLimit = this.borderBottom.transform.position.y + this.distanceFromBottomEdge; //this.rightObjectsLimit = this.borderRight.transform.position.x - this.distanceFromRightEdge; //this.leftObjectsLimit = this.borderLeft.transform.position.x + this.distanceFromLeftEdge; } void Start() { //this.PutRandomResourcesOnScreen("Obstacle", NUMBER_OF_OBSTACLES); //this.PutRandomResourcesOnScreen("BrokenShipPart", NUMBER_OF_BROKEN_PARTS); } void Update() { // 0 - Reset scene cheat if (Input.GetKeyDown(KeyCode.Alpha0) || Input.GetKeyDown(KeyCode.Keypad0)) { Debug.Log("Player: " + player); Debug.Log("Reloading scene with 0"); SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex); } } //private void PutRandomResourcesOnScreen(string resourceName, int nInstances) //{ // for (int i = 0; i < nInstances; i++) // { // GameObject objResource = Instantiate(Resources.Load(resourceName)) as GameObject; // float xPos = Random.Range(this.leftObjectsLimit, this.rightObjectsLimit); // float yPos = Random.Range(this.bottomObjectsLimit, this.topObjectsLimit); // // TODO: different sizes for the objects // objResource.transform.position = new Vector3(xPos, yPos, 0); // objResource.transform.parent = prefabsParent.transform; // float randAngle = Random.Range(0, 200f); // objResource.transform.eulerAngles = new Vector3(0, 0, randAngle); // } //} }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection; using System.Linq.Expressions; using System.Collections; namespace CRL { #region 比较时间格式 /// <summary> /// 比较时间格式 /// </summary> public enum DatePart { /// <summary> /// 年 /// </summary> yy, /// <summary> /// 季度 /// </summary> qq, /// <summary> /// 月 /// </summary> mm, /// <summary> /// 年中的日 /// </summary> dy, /// <summary> /// 日 /// </summary> dd, /// <summary> /// 周 /// </summary> ww, /// <summary> /// 星期 /// </summary> dw, /// <summary> /// 小时 /// </summary> hh, /// <summary> /// 分 /// </summary> mi, /// <summary> /// 秒 /// </summary> ss, /// <summary> /// 毫秒 /// </summary> ms, /// <summary> /// 微妙 /// </summary> mcs, /// <summary> /// 纳秒 /// </summary> ns } #endregion /// <summary> /// 查询扩展方法,请引用CRL命名空间 /// </summary> public static partial class ExtensionMethod { #region 手动更改值,以代替ParameCollection /// <summary> /// 用==表示值被更改 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="obj"></param> /// <param name="expression"></param> public static void Change<T>(this T obj, Expression<Func<T, bool>> expression) where T : CRL.IModel, new() { BinaryExpression be = ((BinaryExpression)expression.Body); MemberExpression mExp = (MemberExpression)be.Left; string name = mExp.Member.Name; var right = be.Right; object value; if (right is ConstantExpression) { ConstantExpression cExp = (ConstantExpression)right; value = cExp.Value; } else { value = Expression.Lambda(right).Compile().DynamicInvoke(); } obj.SetChanges(name,value); } /// <summary> /// 表示值被更改 /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="TKey"></typeparam> /// <param name="obj"></param> /// <param name="expression"></param> public static void Change<T, TKey>(this T obj, Expression<Func<T, TKey>> expression) where T : CRL.IModel, new() { MemberExpression mExp = (MemberExpression)expression.Body; string name = mExp.Member.Name; var field = TypeCache.GetProperties(typeof(T), true)[name]; object value = field.GetValue(obj); obj.SetChanges(name, value); } /// <summary> /// 传参表示值被更改 /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="TKey"></typeparam> /// <param name="obj"></param> /// <param name="expression"></param> /// <param name="value"></param> public static void Change<T, TKey>(this T obj, Expression<Func<T, TKey>> expression,TKey value) where T : CRL.IModel, new() { MemberExpression mExp = (MemberExpression)expression.Body; string name = mExp.Member.Name; obj.SetChanges(name, value); } #endregion ///// <summary> ///// lamada传入方法,传入要查询的字段 ///// 示例:b.SelectField(b.Id, b.Name) ///// </summary> ///// <param name="s"></param> ///// <param name="args"></param> ///// <returns></returns> //public static bool SelectField(this IModel s, params object[] args) //{ // return true; //} /// <summary> /// Like("%key%") /// </summary> /// <param name="s"></param> /// <param name="likeString"></param> /// <returns></returns> public static bool Like(this string s,string likeString) { if (string.IsNullOrEmpty(likeString)) throw new Exception("参数值不能为空:likeString"); return s.IndexOf(likeString) > -1; } /// <summary> /// NotLike("%key%") /// </summary> /// <param name="s"></param> /// <param name="likeString"></param> /// <returns></returns> public static bool NotLike(this string s, string likeString) { if (string.IsNullOrEmpty(likeString)) throw new Exception("参数值不能为空:likeString"); return s.IndexOf(likeString) == -1; } /// <summary> /// 字符串 in /// </summary> /// <param name="s"></param> /// <param name="inString"></param> /// <returns></returns> public static bool In(this string s, params string[] inString) { return true; } /// <summary> /// 字符串 NotIn("'1312','123123'") /// </summary> /// <param name="s"></param> /// <param name="inString"></param> /// <returns></returns> public static bool NotIn(this string s, params string[] inString) { return true; } /// <summary> /// 数字 In(12312,12312) /// </summary> /// <param name="s"></param> /// <param name="values"></param> /// <returns></returns> public static bool In(this int s, params int[] values) { if (values==null) throw new Exception("参数值不能为空:inString"); return true; } /// <summary> /// Enum in /// </summary> /// <param name="s"></param> /// <param name="values"></param> /// <returns></returns> public static bool In(this Enum s, params Enum[] values) { if (values == null) throw new Exception("参数值不能为空:inEnum"); return true; } /// <summary> /// 数字 NotIn(1231,1231) /// </summary> /// <param name="s"></param> /// <param name="values"></param> /// <returns></returns> public static bool NotIn(this int s, params int[] values) { if (values == null) throw new Exception("参数值不能为空:inString"); return true; } /// <summary> /// 枚举转换为INT /// </summary> /// <param name="e"></param> /// <returns></returns> public static int ToInt(this Enum e) { return Convert.ToInt32(e); } /// <summary> /// DateTime Between /// </summary> /// <param name="time"></param> /// <param name="begin"></param> /// <param name="end"></param> /// <returns></returns> public static bool Between(this DateTime time, DateTime begin, DateTime end) { return true; } /// <summary> /// DateDiff /// </summary> /// <param name="time"></param> /// <param name="format">DatePart</param> /// <param name="compareTime">比较的时间</param> /// <returns></returns> public static int DateDiff(this DateTime time, DatePart format, DateTime compareTime) { return 1; } #region group用 /// <summary> /// 表示Sum此字段 /// </summary> /// <param name="origin"></param> /// <returns></returns> public static int SUM(this object origin) { return 0; } /// <summary> /// 表示Count此字段 /// </summary> /// <param name="origin"></param> /// <returns></returns> public static int COUNT(this object origin) { return 0; } #endregion /// <summary> /// 转换共同属性的对象 /// </summary> /// <typeparam name="TDest"></typeparam> /// <param name="source"></param> /// <returns></returns> public static TDest ToType<TDest>(this object source) where TDest : class,new() { var simpleTypes = typeof(TDest).GetProperties(); List<PropertyInfo> complexTypes = source.GetType().GetProperties().ToList(); complexTypes.RemoveAll(b => b.Name == "Item"); TDest obj = new TDest(); foreach (var info in simpleTypes) { var complexInfo = complexTypes.Find(b => b.Name == info.Name); if (complexInfo != null) { object value = complexInfo.GetValue(source, null); info.SetValue(obj, value, null); } } return obj; } /// <summary> /// 转换为共同属性的集合 /// </summary> /// <typeparam name="TDest"></typeparam> /// <param name="source"></param> /// <returns></returns> public static List<TDest> ToType<TDest>(this IEnumerable source) where TDest : class,new() { var simpleTypes = typeof(TDest).GetProperties(); List<PropertyInfo> complexTypes = null; List<TDest> list = new List<TDest>(); foreach (var item in source) { TDest obj = new TDest(); if (complexTypes == null) { complexTypes = item.GetType().GetProperties().ToList(); complexTypes.RemoveAll(b => b.Name == "Item"); } foreach (var info in simpleTypes) { var complexInfo = complexTypes.Find(b => b.Name == info.Name); if (complexInfo != null) { object value = complexInfo.GetValue(item,null); value = ObjectConvert.ConvertObject(info.PropertyType, value); info.SetValue(obj, value, null); } } list.Add(obj); } return list; } public static T Find<T>(this IEnumerable<T> source,Func<T, bool> predicate) { return source.Where(predicate).FirstOrDefault(); } public static List<T> FindAll<T>(this IEnumerable<T> source, Func<T, bool> predicate) { return source.Where(predicate).ToList(); } } }
using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Security.Cryptography.X509Certificates; using System.Web; using ModelLibrary; namespace HotelRestAPI.DBUtil { public interface IManageHotel { IEnumerable<Hotel> Get(); Hotel Get(int id); bool Post(Hotel hotel); bool Put(int id, Hotel hotel); bool Delete(int id); } public class ManageHotel : IManageHotel { //Local private const string connectionString = @"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=HotelDbtest2;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"; //Azure //private const string connectionString = "Data Source=nicolaiserver.database.windows.net;Initial Catalog=NicolaiDataBase;User ID=NicolaiAdmin;Password=********;Connect Timeout=30;Encrypt=True;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"; private const string GET_ALL = "Select * from hotel"; private const string GET_ONE = "Select * from hotel Where Hotel_No = @Id"; private const string INSERT = "Insert into hotel values(@Id, @Name, @Address)"; private const string UPDATE = "Update hotel set Hotel_No = @Hotelid, Name = @Name, Address = @Address where Hotel_No = @Id"; private const string DELETE = "Delete from hotel where Hotel_No =@Id"; public IEnumerable<Hotel> Get() { List<Hotel> liste = new List<Hotel>(); SqlConnection conn = new SqlConnection(connectionString); conn.Open(); SqlCommand cmd = new SqlCommand(GET_ALL, conn); SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { Hotel hotel = readHotel(reader); liste.Add(hotel); } conn.Close(); return liste; } private Hotel readHotel(SqlDataReader reader) { Hotel hotel = new Hotel(); hotel.Id = reader.GetInt32(0); hotel.Name = reader.GetString(1); hotel.Address = reader.GetString(2); return hotel; } public Hotel Get(int id) { Hotel hotel = null; SqlConnection conn = new SqlConnection(connectionString); conn.Open(); SqlCommand cmd = new SqlCommand(GET_ONE, conn); cmd.Parameters.AddWithValue("@Id", id); SqlDataReader reader = cmd.ExecuteReader(); if (reader.Read()) { hotel = readHotel(reader); } conn.Close(); return hotel; } public bool Post(Hotel hotel) { bool ok = false; SqlConnection conn = new SqlConnection(connectionString); conn.Open(); SqlCommand cmd = new SqlCommand(INSERT, conn); cmd.Parameters.AddWithValue("@Id", hotel.Id); cmd.Parameters.AddWithValue("@Name", hotel.Name); cmd.Parameters.AddWithValue("@Address", hotel.Address); int noOfRowsAffected = cmd.ExecuteNonQuery(); ok = noOfRowsAffected == 1 ? true :false; conn.Close(); return ok; } public bool Put(int id, Hotel hotel) { bool ok = false; SqlConnection conn = new SqlConnection(connectionString); conn.Open(); SqlCommand cmd = new SqlCommand(UPDATE, conn); cmd.Parameters.AddWithValue("@HotelId", hotel.Id); cmd.Parameters.AddWithValue("@Name", hotel.Name); cmd.Parameters.AddWithValue("@Address", hotel.Address); cmd.Parameters.AddWithValue("@Id", id); int noOfRowsAffected = cmd.ExecuteNonQuery(); ok = noOfRowsAffected == 1 ? true : false; conn.Close(); return ok; } public bool Delete(int id) { bool ok = false; SqlConnection conn = new SqlConnection(connectionString); conn.Open(); SqlCommand cmd = new SqlCommand(DELETE, conn); cmd.Parameters.AddWithValue("@Id", id); int noOfRowsAffected = cmd.ExecuteNonQuery(); ok = noOfRowsAffected == 1 ? true : false; conn.Close(); return ok; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace LodowkaSerwice.Models { public class Komentarz { public int Id { get; set; } public int UzytkownikID { get; set; } public int PrzepisID { get; set; } public string Koment { get; set; } } }
namespace SimpleMVC.App.Views.Users { using System.Text; using MVC.Interfaces; public class Register : IRenderable { public string Render() { StringBuilder sb = new StringBuilder(); sb.AppendLine("<a href =\"/home/index\">&lt;Home</a>"); sb.AppendLine("<main>"); sb.AppendLine("<h2>Register new user</h2>"); sb.AppendLine("<form action=\"\" method=\"post\">"); sb.AppendLine("<label for=\"username\">Username: </label>"); sb.AppendLine("<input type=\"text\" name=\"Username\" id=\"username\">"); sb.AppendLine("<br>"); sb.AppendLine("<label for=\"pass\">Password: </label>"); sb.AppendLine("<input type=\"password\" name=\"Password\" id=\"pass\">"); sb.AppendLine("<br>"); sb.AppendLine("<input type=\"submit\" value=\"Register\">"); sb.AppendLine("</form>"); sb.AppendLine("</main>"); return sb.ToString(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using OpenQA.Selenium; namespace WebAutomationFramework.Pages { class CheckoutPage { private IWebDriver Driver { get; set; } public CheckoutPage(IWebDriver driver) { Driver = driver; } public void TravelReasonBusiness() { Wait.WaitForElement(Driver, By.CssSelector("input[id*=reason-1]")); Console.WriteLine("On Checkout Page"); var travelReasonBusiness = Driver.FindElement(By.CssSelector("input[id*=reason-1]")); travelReasonBusiness.Click(); } public void TitleField() { Wait.WaitForElement(Driver, By.Id("title-dropdown-adult-1")); var titleField = Driver.FindElement(By.Id("title-dropdown-adult-1")); titleField.Click(); titleField.SendKeys("Mr"); } public void FirstNameField() { Wait.WaitForElement(Driver, By.Id("firstname-textbox-adult-1")); var firstName = Driver.FindElement(By.Id("firstname-textbox-adult-1")); firstName.Click(); firstName.SendKeys("Bruce"); } public void LastNameField() { Wait.WaitForElement(Driver, By.Id("lastname-textbox-adult-1")); var lastNameFieldClick = Driver.FindElement(By.Id("lastname-textbox-adult-1")); lastNameFieldClick.Click(); lastNameFieldClick.SendKeys("Wayne"); } public void AgeField() { Wait.WaitForElement(Driver, By.Id("age-dropdown-adult-1")); var ageField = Driver.FindElement(By.Id("age-dropdown-adult-1")); ageField.Click(); ageField.SendKeys("18+"+Keys.Tab); } public void ContinueButtonClick() { Wait.WaitForElement(Driver, By.CssSelector("button[ng-click*=Continue]")); var continueButtonClick = Driver.FindElement(By.CssSelector("button[ng-click*=Continue]")); continueButtonClick.Click(); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace IotHubSync.Logic { using Microsoft.Azure.Devices; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Newtonsoft.Json; public class DeviceSynchronizer { private readonly ILogger _logger; private readonly bool _isValidConnectionStrings; private readonly string _connectionStringMaster, _connectionStringSlave; public DeviceSynchronizer(ConnectionStrings connectionStrings, ILogger logger) { _connectionStringMaster = connectionStrings.ConnectionStringMaster; _connectionStringSlave = connectionStrings.ConnectionStringSlave; _logger = logger; // Validate Connection Strings _isValidConnectionStrings = ValidateConnectionString(_connectionStringMaster, IotHubType.Master) && ValidateConnectionString(_connectionStringSlave, IotHubType.Slave); } public async Task<bool> CreateDevice(string eventGridData) { bool isSuccess = true; // Only run if connection strings are valid if (!_isValidConnectionStrings) { throw new InvalidOperationException("Can not run with invalid connection strings."); } string deviceIdMaster; try { var jobjectTwinMaster = JObject.Parse(eventGridData); deviceIdMaster = (string)jobjectTwinMaster["twin"]["deviceId"]; } catch (JsonReaderException ex) { _logger.LogError(ex, $"Invalid information received from Event Grid."); return false; } if (!ConnectRegistryManager(out RegistryManager registryManagerMaster, IotHubType.Master) || !ConnectRegistryManager(out RegistryManager registryManagerSlave, IotHubType.Slave)) { return false; } // Get Device from Master IoT Hub var deviceListMaster = await GetDeviceListFromIotHub(registryManagerMaster, deviceIdMaster, IotHubType.Master); if (deviceListMaster.Count == 0) { _logger.LogError($"{deviceIdMaster}: Can not find device in Master IoT Hub."); isSuccess = false; } // Add device to Slave IoT Hub if (isSuccess) { isSuccess = await AddDeviceToIotHub(true, registryManagerSlave, deviceListMaster[0], IotHubType.Slave); } await registryManagerMaster.CloseAsync(); await registryManagerSlave.CloseAsync(); return isSuccess; } public async Task<bool> DeleteDevice(string eventGridData) { bool isSuccess = true; // Only run if connection strings are valid if (!_isValidConnectionStrings) { throw new InvalidOperationException("Can not run with invalid connection strings."); } string deviceIdMaster; try { var jobjectTwinMaster = JObject.Parse(eventGridData); deviceIdMaster = (string)jobjectTwinMaster["twin"]["deviceId"]; } catch (JsonReaderException ex) { _logger.LogError(ex, $"Invalid information received from Event Grid."); return false; } if (!ConnectRegistryManager(out RegistryManager registryManagerSlave, IotHubType.Slave)) { return false; } // Remove device from Slave IoT Hub try { await registryManagerSlave.RemoveDeviceAsync(deviceIdMaster); } catch (Exception ex) { _logger.LogError(ex, $"{deviceIdMaster}: Can not remove device from Slave IoT Hub."); isSuccess = false; } finally { await registryManagerSlave.CloseAsync(); } return isSuccess; } public async Task<bool> SyncIotHubsAsync() { bool isSuccess = true; // Only run if connection strings are valid if (!_isValidConnectionStrings) { _logger.LogError($"Can not run with invalid connection strings."); return false; } if (!ConnectRegistryManager(out RegistryManager registryManagerMaster, IotHubType.Master) || !ConnectRegistryManager(out RegistryManager registryManagerSlave, IotHubType.Slave)) { return false; } _logger.LogInformation($"IoT Hub synchronization started."); // Get Master device list var deviceListMaster = await GetDeviceListFromIotHub(registryManagerMaster, null, IotHubType.Master); _logger.LogInformation($"Found {deviceListMaster.Count} devices in Master IoT Hub."); // Get Slave device list var deviceListSlave = await GetDeviceListFromIotHub(registryManagerSlave, null, IotHubType.Slave); _logger.LogInformation($"Found {deviceListSlave.Count} devices in Slave IoT Hub."); foreach (var deviceInfoMaster in deviceListMaster) { var deviceInfoSlave = deviceListSlave.Find(r => r.Device.Id == deviceInfoMaster.Device.Id); // Device does not exist in Slave: Add if (deviceInfoSlave == null) { isSuccess = await AddDeviceToIotHub(isSuccess, registryManagerSlave, deviceInfoMaster, IotHubType.Slave); } // Device exists in Slave: Verify and Update else { isSuccess = await VerifyAndUpdateDeviceInIotHub(isSuccess, deviceListSlave, deviceInfoMaster, deviceInfoSlave, registryManagerSlave); isSuccess = await CompareTwinDesiredPropertiesInIotHub(isSuccess, deviceInfoMaster, deviceInfoSlave, registryManagerSlave); } } // Delete the devices that no longer exist in Master isSuccess = await DeleteObsoleteDevicesFromIotHub(isSuccess, deviceListSlave, registryManagerSlave); if (isSuccess) { _logger.LogDebug($"Master/Slave IoT Hub synchronization completed with no errors."); } else { _logger.LogError($"Master/Slave IoT Hub synchronization completed with errors."); } await registryManagerMaster.CloseAsync(); await registryManagerSlave.CloseAsync(); return isSuccess; } private bool ValidateConnectionString(string connectionString, IotHubType type) { // Validate Master connection string if (string.IsNullOrEmpty(connectionString)) { _logger.LogError($"{type} IoT Hub connection string not found in configuration."); return false; } else { // Just show Master IoT Hub Hostname if (TryGetHostFromConnectionString(connectionString, out string hostName)) { _logger.LogDebug($"Using {type} IoT Hub: {hostName}"); } else { _logger.LogError($"Invalid {type} IoT Hub connection string in configuration. Can not find \"HostName=\"."); return false; } } return true; } private bool ConnectRegistryManager(out RegistryManager registryManager, IotHubType type) { string connectionString; if (type == IotHubType.Master) { connectionString = _connectionStringMaster; } else { connectionString = _connectionStringSlave; } try { registryManager = RegistryManager.CreateFromConnectionString(connectionString); _logger.LogDebug($"Connected to {type} IoT Hub."); } catch (Exception ex) { _logger.LogError(ex, $"Can not connect to {type} IoT Hub."); registryManager = null; return false; } return true; } private async Task<List<DeviceInfo>> GetDeviceListFromIotHub(RegistryManager registryManager, string deviceId, IotHubType type) { var deviceInfoList = new List<DeviceInfo>(); var queryString = "SELECT * FROM devices"; if (!string.IsNullOrEmpty(deviceId)) { queryString += $" WHERE deviceId = '{deviceId}'"; } try { var query = registryManager.CreateQuery(queryString); while (query.HasMoreResults) { var twinList = await query.GetNextAsTwinAsync(); foreach (var twin in twinList) { var device = await registryManager.GetDeviceAsync(twin.DeviceId); device.ETag = null; deviceInfoList.Add(new DeviceInfo(device, twin, false)); await PreventIotHubThrottling(); } } } catch (Exception ex) { _logger.LogError(ex, $"Failed loading devices from {type} IoT Hub."); deviceInfoList = new List<DeviceInfo>(); if (ExceptionHandler.IsFatal(ex)) { throw; } } return deviceInfoList; } private async Task<bool> AddDeviceToIotHub(bool isSuccess, RegistryManager registryManager, DeviceInfo deviceInfo, IotHubType type) { var deviceInfoSlave = new DeviceInfo(); // Prepare Scope if (!string.IsNullOrEmpty(deviceInfo.Device.Scope)) { string edgeDeviceIdSlave = GetDeviceIdFromScope(deviceInfo.Device.Scope); if (string.IsNullOrEmpty(edgeDeviceIdSlave)) { _logger.LogError($"{deviceInfo.Device.Id} has invalid Edge device scope: {deviceInfo.Device.Scope}."); } else if (deviceInfo.Device.Id != edgeDeviceIdSlave) { Device edgeDeviceInfoSlave = null; try { edgeDeviceInfoSlave = await registryManager.GetDeviceAsync(edgeDeviceIdSlave); await PreventIotHubThrottling(); } catch (Exception ex) { _logger.LogError(ex, $"{edgeDeviceIdSlave}: Failed loading device from {type} IoT Hub."); } if (edgeDeviceInfoSlave != null) { deviceInfo.Device.Scope = edgeDeviceInfoSlave.Scope; } else { _logger.LogWarning($"{deviceInfo.Device.Id}: Device has Edge device parent of {edgeDeviceIdSlave} but that device has not been created in Slave IoT Hub yet. It will be added at next run."); } } } // Add device to IoT Hub try { deviceInfoSlave.Device = await registryManager.AddDeviceAsync(deviceInfo.Device); await PreventIotHubThrottling(); } catch (Exception ex) { _logger.LogError(ex, $"{deviceInfo.Device.Id}: Can not add device to {type} IoT hub."); isSuccess = false; } // Get Device Twin from IoT Hub try { deviceInfoSlave.Twin = await registryManager.GetTwinAsync(deviceInfo.Device.Id); await PreventIotHubThrottling(); } catch (Exception ex) { _logger.LogError(ex, $"{deviceInfo.Device.Id}: Can not read device Twin from {type} IoT Hub."); isSuccess = false; } // Update Device Twin in IoT Hub try { deviceInfoSlave.Twin = await registryManager.UpdateTwinAsync(deviceInfo.Device.Id, deviceInfo.Twin, deviceInfoSlave.Twin.ETag); await PreventIotHubThrottling(); } catch (Exception ex) { _logger.LogError(ex, $"{deviceInfo.Device.Id}: Can not update device Twin in {type} IoT Hub."); isSuccess = false; } return isSuccess; } private async Task<bool> VerifyAndUpdateDeviceInIotHub(bool isSuccess, List<DeviceInfo> deviceListSlave, DeviceInfo deviceInfoMaster, DeviceInfo deviceInfoSlave, RegistryManager registryManagerSlave) { var isStale = false; // Mark as existing in Master deviceInfoSlave.ExistsInMaster = true; // Update Authentication Symmetric Keys if not matching if (deviceInfoMaster.Device.Authentication.SymmetricKey.PrimaryKey != deviceInfoSlave.Device.Authentication.SymmetricKey.PrimaryKey || deviceInfoMaster.Device.Authentication.SymmetricKey.SecondaryKey != deviceInfoSlave.Device.Authentication.SymmetricKey.SecondaryKey) { deviceInfoSlave.Device.Authentication.SymmetricKey = deviceInfoMaster.Device.Authentication.SymmetricKey; isStale = true; } // Update Device Status Info if not matching if (deviceInfoMaster.Device.Status != deviceInfoSlave.Device.Status) { deviceInfoSlave.Device.Status = deviceInfoMaster.Device.Status; isStale = true; } // Compare Device Scope isStale = CompareDeviceScopeInIotHub(deviceListSlave, deviceInfoMaster, deviceInfoSlave, isStale); // Do we need to write the Slave data? if (isStale) { try { await registryManagerSlave.UpdateDeviceAsync(deviceInfoSlave.Device, true); await PreventIotHubThrottling(); } catch (Exception ex) { _logger.LogError(ex, $"{deviceInfoMaster.Device.Id}: Can not update device info in Slave IoT Hub."); isSuccess = false; } } return isSuccess; } private bool CompareDeviceScopeInIotHub(List<DeviceInfo> deviceListSlave, DeviceInfo deviceInfoMaster, DeviceInfo deviceInfoSlave, bool isStale) { if (!string.IsNullOrEmpty(deviceInfoMaster.Device.Scope)) { var edgeDeviceIdMaster = GetDeviceIdFromScope(deviceInfoMaster.Device.Scope); if (string.IsNullOrEmpty(edgeDeviceIdMaster)) { _logger.LogError($"{deviceInfoMaster.Device.Id} has invalid Edge device scope: {deviceInfoMaster.Device.Scope}."); } else if (deviceInfoMaster.Device.Id != edgeDeviceIdMaster) { var edgeDeviceInfoSlave = deviceListSlave.Find(r => r.Device.Id == edgeDeviceIdMaster); if (edgeDeviceInfoSlave != null) { var scopeEdgeSlave = edgeDeviceInfoSlave.Device.Scope; // Update Device Scope Info if (scopeEdgeSlave != deviceInfoSlave.Device.Scope) { deviceInfoSlave.Device.Scope = scopeEdgeSlave; isStale = true; } } else { _logger.LogWarning($"{deviceInfoMaster.Device.Id}: Device has Edge device parent of {edgeDeviceIdMaster} but that device has not been created in Slave IoT Hub yet. It will be added at next run."); } } } return isStale; } private async Task<bool> CompareTwinDesiredPropertiesInIotHub(bool isSuccess, DeviceInfo deviceInfoMaster, DeviceInfo deviceInfoSlave, RegistryManager registryManagerSlave) { // Compare Twin Desired Properties JObject jsonTwinMaster = JObject.Parse(deviceInfoMaster.Twin.Properties.Desired.ToJson()); jsonTwinMaster.Remove("$metadata"); jsonTwinMaster.Remove("$version"); JObject jsonTwinSlave = JObject.Parse(deviceInfoSlave.Twin.Properties.Desired.ToJson()); jsonTwinSlave.Remove("$metadata"); jsonTwinSlave.Remove("$version"); // Update Device Twin desired properties if (!JToken.DeepEquals(jsonTwinMaster, jsonTwinSlave)) { deviceInfoSlave.Twin.Properties.Desired = deviceInfoMaster.Twin.Properties.Desired; try { await registryManagerSlave.UpdateTwinAsync(deviceInfoSlave.Device.Id, deviceInfoSlave.Twin, deviceInfoSlave.Twin.ETag); await PreventIotHubThrottling(); } catch (Exception ex) { _logger.LogError(ex, $"{deviceInfoMaster.Device.Id}: Can not update device Twin in Slave IoT Hub."); isSuccess = false; } } return isSuccess; } private async Task<bool> DeleteObsoleteDevicesFromIotHub(bool isSuccess, List<DeviceInfo> deviceListSlave, RegistryManager registryManagerSlave) { List<Device> devicesToRemove = new List<Device>(); foreach (var deviceInfoSlave in deviceListSlave) { if (!deviceInfoSlave.ExistsInMaster) { devicesToRemove.Add(deviceInfoSlave.Device); } } // Bulk delete extra/stale devices from Slave IoT Hub. if (devicesToRemove.Count > 0) { var devicesToRemoveSplit = SplitList(devicesToRemove, Constants.SplitListSize); foreach (var splitList in devicesToRemoveSplit) { try { BulkRegistryOperationResult result; result = await registryManagerSlave.RemoveDevices2Async(splitList, true, new System.Threading.CancellationToken()); await PreventIotHubThrottling(); foreach (var error in result.Errors) { _logger.LogError($"{error.DeviceId}: {error.ErrorStatus}"); isSuccess = false; } } catch (Exception ex) { _logger.LogError(ex, $"Can not remove devices."); isSuccess = false; } } } return isSuccess; } private static string GetDeviceIdFromScope(string scope) { var startPoint = scope.LastIndexOf("/", StringComparison.OrdinalIgnoreCase); var endPoint = scope.LastIndexOf("-", StringComparison.OrdinalIgnoreCase); if (startPoint == -1 || endPoint == -1 || startPoint - endPoint >= 0) { return null; } else { return scope.Substring(startPoint + 1, endPoint - startPoint - 1); } } private IEnumerable<List<T>> SplitList<T>(List<T> input, int nSize) { for (int i = 0; i < input.Count; i += nSize) { yield return input.GetRange(i, Math.Min(nSize, input.Count - i)); } } private bool TryGetHostFromConnectionString(string connectionString, out string hostName) { hostName = null; const string hostNameInConnectionString = "HostName="; const string iotHubFqdnInConnectionString = "azure-devices.net"; var from = connectionString.IndexOf(hostNameInConnectionString, StringComparison.OrdinalIgnoreCase); if (from == -1) { return false; } var fromOffset = hostNameInConnectionString.Length; var to = connectionString.IndexOf(iotHubFqdnInConnectionString, StringComparison.OrdinalIgnoreCase); if (to == -1) { return false; } var length = to - from - fromOffset + "azure-devices.net".Length; if (from + fromOffset + length < connectionString.Length) { hostName = connectionString.Substring(from + fromOffset, length); } return hostName != null; } private static async Task PreventIotHubThrottling() { // Wait for 500ms to prevent IoT Hub throttling. await Task.Delay(Constants.IotHubThrottlingTimeoutInMilliseconds); } } }
namespace SFA.DAS.ProviderCommitments.Web.Models.Cohort { public class FileDiscardSuccessViewModel { public long ProviderId { get; set; } } }
using UnityEngine; using System.Collections.Generic; using UINT8 = System.Byte; namespace Ardunity { [ExecuteInEditMode] [AddComponentMenu("ARDUnity/Controller/Motor/GenericServo")] [HelpURL("https://sites.google.com/site/ardunitydoc/references/controller/genericservo")] public class GenericServo : ArdunityController, IWireOutput<float> { public int pin; public bool smooth = false; [Range(-45, 45)] public int calibratedAngle = 0; [Range(-90, 90)] public int minAngle = -90; [Range(-90, 90)] public int maxAngle = 90; [Range(-90, 90)] public float angle = 0; public Transform handleObject; private int _preCalibratedAngle = 0; private int _preMinAngle = -90; private int _preMaxAngle = 90; private float _preAngle = 0; protected override void Awake() { base.Awake(); enableUpdate = false; // only output. } void Start() { _preCalibratedAngle = calibratedAngle; _preMinAngle = minAngle; _preMaxAngle = maxAngle; _preAngle = angle; } void Update() { if(handleObject != null) { angle = handleObject.localRotation.eulerAngles.y; if(angle > 180f) angle -= 360f; } if(_preCalibratedAngle != calibratedAngle) { calibratedAngle = Mathf.Clamp(calibratedAngle, -45, 45); if(_preCalibratedAngle != calibratedAngle) { _preCalibratedAngle = calibratedAngle; SetDirty(); } } if(_preMinAngle != minAngle) { minAngle = Mathf.Clamp(minAngle, -90, _preMaxAngle); if(_preMinAngle != minAngle) { _preMinAngle = minAngle; if(angle < _preMinAngle) angle = _preMinAngle; } } if(_preMaxAngle != maxAngle) { maxAngle = Mathf.Clamp(maxAngle, _preMinAngle, 90); if(_preMaxAngle != maxAngle) { _preMaxAngle = maxAngle; if(angle > _preMaxAngle) angle = _preMaxAngle; } } if(_preAngle != angle) { angle = Mathf.Clamp(angle, _preMinAngle, _preMaxAngle); if(_preAngle != angle) { _preAngle = angle; SetDirty(); } } } protected override void OnPush() { Push((UINT8)Mathf.Clamp(_preAngle + _preCalibratedAngle + 90, 0, 180)); } public override string[] GetCodeIncludes() { List<string> includes = new List<string>(); includes.Add("#include <Servo.h>"); return includes.ToArray(); } public override string GetCodeDeclaration() { string declaration = string.Format("{0} {1}({2:d}, {3:d}, ", this.GetType().Name, GetCodeVariable(), id, pin); if(smooth) declaration += "true);"; else declaration += "false);"; return declaration; } public override string GetCodeVariable() { return string.Format("servo{0:d}", id); } float IWireOutput<float>.output { get { return (float)angle; } set { if(value > 180f) value -= 360f; else if(value < -180f) value += 360f; angle = (int)value; } } protected override void AddNode(List<Node> nodes) { base.AddNode(nodes); nodes.Add(new Node("pin", "", null, NodeType.None, "Arduino Digital Pin")); nodes.Add(new Node("angle", "Angle", typeof(IWireOutput<float>), NodeType.WireTo, "Output<float>")); } protected override void UpdateNode(Node node) { if(node.name.Equals("pin")) { node.updated = true; node.text = string.Format("Pin: {0:d}", pin); return; } else if(node.name.Equals("angle")) { node.updated = true; return; } base.UpdateNode(node); } } }
using System; using Service; using Serilog; using StoreModels; using System.Collections.Generic; using System.Linq; namespace StoreUI { public class InventoryMenu : IMenu { private IService _services; private IValidationUI _validate; private Location _location; public InventoryMenu(IService services, IValidationUI validate) { _services = services; _validate = validate; } public void Start() { try{ List<Object> objectList = _services.GetAllLocations().Cast<Object>().ToList<Object>(); Object ret = SelectFromList.Start(objectList); _location = (Location) ret; }catch(NullReferenceException ex){ Console.WriteLine("Cancelled Location Selection"); return; }catch(Exception ex){ Log.Error(ex, ex.Message); return; } bool repeat = true; string str; do{ Console.Clear(); Console.WriteLine("Inventory Menu For Location:\n{0}",_location.ToString()); Console.WriteLine("[0] Exit"); Console.WriteLine("[1] View Inventory Of Location"); Console.WriteLine("[2] Update Inventory"); Console.WriteLine("[3] Add Product To Inventory"); string input = Console.ReadLine(); switch (input) { case "0": Console.WriteLine("Goodbye"); Log.Information("program exit from menu"); repeat = false; break; case "1": try{ Console.WriteLine("{0} Inventory:", _location.ToString()); foreach (Item item in _location.Inventory) { Console.WriteLine(item.ToString()); } Console.WriteLine(); }catch(Exception ex){ Log.Error("Error Viewing Location", ex.Message); } break; case "2": Item selectedItem; try{ List<Object> objectList = _location.Inventory.Cast<Object>().ToList<Object>(); Object ret = SelectFromList.Start(objectList); selectedItem = (Item) ret; }catch(NullReferenceException ex){ Console.WriteLine("Cancelled Item Selection"); break; }catch(Exception ex){ Log.Error(ex, ex.Message); break; } str = _validate.ValidationPrompt("Enter Amount increase/decrease stock by:", ValidationService.ValidateInt); try{ _services.updateItemInStock(_location, selectedItem, int.Parse(str)); Console.WriteLine("Stock updated"); }catch(Exception ex){ Console.WriteLine("Stock Could Not Be Updated"); } break; case "3": Product prod; try{ List<Object> objectList = _services.GetAllProducts().Cast<Object>().ToList<Object>(); Object ret = SelectFromList.Start(objectList); prod = (Product) ret; }catch(NullReferenceException ex){ Console.WriteLine("Cancelled Product Selection"); break; }catch(Exception ex){ Log.Error(ex, ex.Message); break; } str = _validate.ValidationPrompt("Enter Initial number of products in the stores stock", ValidationService.ValidatePositiveInt); int stock = int.Parse(str); try{ _services.AddProductToInventory(_location,prod, stock); Console.WriteLine("Product Add"); }catch(Exception ex){ Console.WriteLine(ex.Message); } break; default: Console.WriteLine("Choose valid option!"); break; } } while(repeat); } } }
using System.Linq; using System.Windows; using System.Windows.Controls; namespace Lite { /// <summary> /// The Map Bar Control /// </summary> public partial class LiteMapBar : UserControl { /// <summary> /// Default constructor /// </summary> public LiteMapBar() { InitializeComponent(); SetupSubBars(); } /// <summary> /// Setup subbars, subscribe to the changed event /// </summary> private void SetupSubBars() { foreach (var sub in this.GetDescendants<LiteSubMapBar>()) { sub.IsActiveChanged += sub_IsActiveChanged; } } /// <summary> /// Callback from the changed event, make sure only one bar is active /// </summary> void sub_IsActiveChanged(object sender, DependencyPropertyChangedEventArgs e) { var control = sender as LiteSubMapBar; if (control.IsActive) { foreach (var sub in this.GetDescendants<LiteSubMapBar>().Where((a) => a != control && a.IsActive)) { sub.IsActive = false; } } } } }
using System.Linq; using static WynnicTranslator.Core.Languages.Translator; using static WynnicTranslator.Core.Translator.TransUtils; namespace WynnicTranslator.Core { public static class Translator { public static string Translate(Lang lang, string i) { switch (lang) { case Lang.Gavellian: return Gavellian.Translate(i); default: return Wynnic.Translate(i); } } public static class TransUtils { public enum Lang { Wynnic = 0, Gavellian = 1 } public static bool CheckForAllowedChar(char i, Lang language) { switch (language) { case Lang.Gavellian: return char.IsLetter(char.ToLower(i)); case Lang.Wynnic: return char.IsLetter(char.ToLower(i)) || char.IsNumber(i) || i == '?' || i == '.' || i == '!'; default: return false; } } } internal static class Variables { internal static readonly char[] BaseLetters = "abcdefghijklmnopqrstuvwxyz".ToCharArray(); internal static readonly char[] WynnicLetters = "⒜⒝⒞⒟⒠⒡⒢⒣⒤⒥⒦⒧⒨⒩⒪⒫⒬⒭⒮⒯⒰⒱⒲⒳⒴⒵".ToCharArray(); internal static readonly char[] WynnicNumbers = "⑴⑵⑶⑷⑸⑹⑺⑻⑼".ToCharArray(); // internal static readonly char[] WynnicAdditionalNumbers = "⑽⑾⑿".ToCharArray(); internal static readonly char[] WynnicSpecialChars = "012".ToCharArray(); internal static readonly char[] BaseNumbers = "123456789".ToCharArray(); internal static readonly char[] GavellianLetters = "ⓐⓑⓒⓓⓔⓕⓖⓗⓘⓙⓚⓛⓜⓝⓞⓟⓠⓡⓢⓣⓤⓥⓦⓧⓨⓩ".ToCharArray(); internal static readonly char[] BaseSpecialChars = ".!?".ToCharArray(); } private static class Wynnic { internal static string Translate(string i) { return i.ToLower().Aggregate("", (current, c) => current + Converter.Wynnic.AsciiConverter(c)); } } private static class Gavellian { internal static string Translate(string i) { return i.ToLower().Aggregate("", (current, c) => current + Converter.Gavellian.LetterConverter(c)); } } } }
// using PingPongTest; using System; using System.Collections.Generic; namespace PingPong { public class PingPongClass { private int _input; private List<string> _output = new List<string> {}; public PingPongClass(int input) { _input = input; for(int i = 1; i <= input; i++) { if (i % 15 == 0) { _output.Add("ping-pong"); } else if (i % 5 == 0) { _output.Add("pong"); } else if (i % 3 == 0) { _output.Add("ping"); } else { _output.Add(i.ToString()); } } } public List<string> getOutput() { return _output; } } }
using System; namespace TelegramBot.Core { public class AppSettings { public string URL { get; set; } public string NAME { get; set; } public string API_KEY { get; set; } public string CONNECTION_STRING { get; set; } } }
using UnityEngine; using System.Collections; public class SCR_Hostile : MonoBehaviour { public enum EHostileType { HT_Static, HT_Patrol } protected enum EAlertState { AS_Unaware, AS_Chasing } public EHostileType HostileType = EHostileType.HT_Static; protected EAlertState AlertState = EAlertState.AS_Unaware; NavMeshAgent NavAgent; SCR_Manager_Mission Manager_Mission; GameObject Player; float ViewRange = 5.0f; float ViewRangeSquared; bool FoundPlayer = false; Vector3 LastFrameLocation; Vector3 ThisFrameLocation; float ThisFrameSpeed; int DestinationIndex = 0; bool NeedNewTarget = false; Vector3[] Destinations; SCR_MotionSoundSource MotionSoundSource; // Use this for initialization void Start () { LastFrameLocation = gameObject.transform.position; Manager_Mission = GameObject.FindGameObjectWithTag("Manager_Mission").GetComponent<SCR_Manager_Mission> (); NavAgent = GetComponent<NavMeshAgent> (); ViewRangeSquared = ViewRange * ViewRange; Destinations = new Vector3[2]; Destinations [0] = transform.position; Destinations [1] = transform.GetChild (0).transform.position; if (HostileType == EHostileType.HT_Patrol) { NavAgent.SetDestination (Destinations [1]); DestinationIndex = 1; } MotionSoundSource = GetComponent<SCR_MotionSoundSource> (); } // Update is called once per frame void Update () { if (FoundPlayer == false) { Player = GameObject.FindGameObjectWithTag ("Player"); FoundPlayer = true; } if (HostileType == EHostileType.HT_Patrol && AlertState == EAlertState.AS_Unaware) { if (NavAgent.remainingDistance < NavAgent.stoppingDistance) { NeedNewTarget = true; print ("Arrived"); } if(NeedNewTarget == true) { if (DestinationIndex == 0) { NavAgent.SetDestination (Destinations [1]); DestinationIndex = 1; NeedNewTarget = false; } else if (DestinationIndex == 1) { NavAgent.SetDestination (Destinations [0]); DestinationIndex = 0; NeedNewTarget = false; } } } if (AlertState == EAlertState.AS_Unaware) { Vector3 PlayerOffset = Player.transform.position - gameObject.transform.position; //DOES THE PLAYER TRIGGER ME if (PlayerOffset.sqrMagnitude < ViewRangeSquared) { RaycastHit RayHit; Debug.DrawRay (gameObject.transform.position, PlayerOffset * 100, Color.green, 2.0f); if (Physics.Raycast (gameObject.transform.position, PlayerOffset, out RayHit, ViewRange)) { if (RayHit.collider.transform.CompareTag ("Player")) { AlertState = EAlertState.AS_Chasing; } } } } else if (AlertState == EAlertState.AS_Chasing) { NavAgent.SetDestination (Player.transform.position); if (NavAgent.remainingDistance > 15.0f) { NavAgent.SetDestination (Destinations [DestinationIndex]); AlertState = EAlertState.AS_Unaware; } } LastFrameLocation = ThisFrameLocation; ThisFrameLocation = gameObject.transform.position; ThisFrameSpeed = (ThisFrameLocation - LastFrameLocation).magnitude; if (ThisFrameSpeed > 4.50f) { MotionSoundSource.BeginEmitSound2 (1.0f, ThisFrameSpeed); } else { MotionSoundSource.BeginEmitSound2 (1.0f, 4.5f); } } void OnCollisionEnter(Collision colliison) { if(colliison.collider.CompareTag("Player")) { Manager_Mission.Respawn (); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; //using Finisar.SQLite; namespace WPFTemplet.Class { class DataBaseConnection { //public SQLiteConnection GetConnection() //{ // return new SQLiteConnection("Data Source = " + Environment.CurrentDirectory + "\\Database\\SalesInvoiceTracker.db; Version = 3"); //} //public bool CheckDBConnection() //{ // bool ConnectionStatus = false; // dbConnection StartConn = new dbConnection(); // SQLiteConnection MyConnetion = StartConn.GetConnection(); // MyConnetion.Open(); // if (MyConnetion.State == ConnectionState.Open) // { // ConnectionStatus = true; // } // return ConnectionStatus; //} } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Foundry.SourceControl { public interface ISourceObject { string CommitId { get; } string TreeId { get; } string Path { get; } string Name { get; } bool IsDirectory { get; } DateTime DateTime { get; } string Message { get; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class SceneLoader : Singleton<SceneLoader> { private string sceneNameToLoad; public void LoadScene(string _sceneName) { sceneNameToLoad = _sceneName; StartCoroutine(InitializeSceneLoading()); } IEnumerator InitializeSceneLoading() { yield return SceneManager.LoadSceneAsync("Scene_Loading"); //load the target StartCoroutine(LoadTargetScene()); } IEnumerator LoadTargetScene() { var loading = SceneManager.LoadSceneAsync(sceneNameToLoad); loading.allowSceneActivation = false; print("loading progress=" + loading.progress); while (!loading.isDone) { if (loading.progress >= 0.9f) { loading.allowSceneActivation = true; } yield return null; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PredicateParty { class Program { static void Main(string[] args) { Func<string, string, bool> startsWith = (x, y) => x.StartsWith(y); Func<string, string, bool> endsWith = (x, y) => x.EndsWith(y); Func<string, int, bool> lenght = (x, y) => x.Length == y; Action<List<string>, string> remove = (x, y) => x.Remove(y); Action<List<string>, string> doubleName = (x, y) => x.Insert(x.IndexOf(y),y); var list = Console.ReadLine() .Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries) .ToList(); args = Console.ReadLine().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); while (!string.Join("", args).Equals("Party!")) { if(args[0] == "Double") { if(args[1] == "Length") { var len = int.Parse(args[2]); var equalLengthStr = list.Where(x => lenght(x, len)); } } else { } args = Console.ReadLine().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlanetRandomizerComponent : MonoBehaviour { public List<GameObject> PlanetPrefabs = new List<GameObject>(); private void Awake() { int Index = Random.Range(0, PlanetPrefabs.Count); Instantiate(PlanetPrefabs[Index], transform); } // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { } }
using System; using Xunit; using System.Collections; using System.Collections.Generic; using Challenges; namespace myTests { public class TestDataGenerator : IEnumerable<object[]> { private readonly List<object[]> _data = new List<object[]> { new object[] {new List<int>{4},4,1,1}, new object[] {new List<int>{1,2,1,3,2},3,2,2} }; public IEnumerator<object[]> GetEnumerator() => _data.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } public class SubArrayDivisionTests { [Theory] [ClassData(typeof(TestDataGenerator))] public void Test1(List<int> s, int d, int m, int result) { int actualResult = SubArrayDivision.birthday(s,d,m); Assert.Equal(result, actualResult); } } }
using SharpDX; using SharpDX.Toolkit.Graphics; using SharpDX.Toolkit.Input; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProtoCar { class ThirdPersonCamera : ACamera { public Vector3 offset; Vector3 cameraPos; Vector3 direction; public ThirdPersonCamera(GraphicsDevice device, Vector3 offset) { this.offset = offset; projection = Matrix.PerspectiveFovRH( 0.6f, // Field of view (float)device.BackBuffer.Width / (Settings.enablePlayer2 ? (device.BackBuffer.Height/2) : device.BackBuffer.Height), // Aspect ratio //only height/2 because our Viewport is just height / 2 0.1f, // Near clipping plane 500.0f); } public override void updateMatrices(Vector3 position) { if (rotation.X > -0.15f) rotation.X = -0.15f; Matrix rotationM = Matrix.RotationYawPitchRoll(rotation.Y, rotation.X, 0); Vector3 newOffset = Helper.Transform(offset, ref rotationM); this.cameraPos = position - newOffset; this.direction = position - this.cameraPos; this.direction.Normalize(); this.view = Matrix.LookAtRH(this.cameraPos, position, Vector3.Up); } public override Vector3 moved(Vector3 position, Vector3 deltaPos) { Matrix matrix; if (Settings.enableNoclip) matrix = Matrix.RotationYawPitchRoll(rotation.Y, rotation.X, 0); else matrix = Matrix.RotationY(rotation.Y); position += Helper.Transform(deltaPos, ref matrix); return position; } public override Vector2 clampMinMax() { return new Vector2(-1.5f, -0.75f); } public override void zoomIn() { if (offset.Y <= Settings.maxZoomIn) return; offset -= new Vector3(0,Settings.zoomSpeed, -Settings.zoomSpeed); } public override void zoomOut() { if (offset.Y >= Settings.maxZoomOut) return; offset += new Vector3(0, Settings.zoomSpeed, -Settings.zoomSpeed); } public override Vector3 getPosition() { return cameraPos; } public override Vector3 getDirection() { return direction; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Common.Composite; using Common.Composite.Events; namespace Common.Events { public class EventDispatcher : IEventDispatcher, IDisposable { [ThreadStatic] private static List<List<EventDispatcher>> _bubbleChains; private Dictionary<object, List<EventListenerDelegate<Event>>> _eventListeners; private Dictionary<object, List<EventListenerDelegate<Event>>> _nativeEventListeners; protected void MapEvent<T>(object type, EventListenerDelegate<T> listener) where T : Event { if (_nativeEventListeners == null) _nativeEventListeners = new Dictionary<object, List<EventListenerDelegate<Event>>>(); List<EventListenerDelegate<Event>> listeners; if (!_nativeEventListeners.TryGetValue(type, out listeners)) { listeners = new List<EventListenerDelegate<Event>>(); _nativeEventListeners[type] = listeners; } if (!listeners.Contains(listener)) { listeners.Add((EventListenerDelegate<Event>)listener); } } public virtual void Dispose() { RemoveEventListeners(); } public void AddEventListener(object type, EventListenerDelegate<Event> listener) { if (_eventListeners == null) { _eventListeners = new Dictionary<object, List<EventListenerDelegate<Event>>>(); } List<EventListenerDelegate<Event>> listeners; if (!_eventListeners.TryGetValue(type, out listeners)) { listeners = new List<EventListenerDelegate<Event>>(); _eventListeners[type] = listeners; } if (!listeners.Contains(listener)) { listeners.Add(listener); } } public void RemoveEventListener(object type, EventListenerDelegate<Event> listener) { if (_eventListeners != null) { List<EventListenerDelegate<Event>> listeners; if (_eventListeners.TryGetValue(type, out listeners) && listeners != null) { var numListeners = listeners.Count; var index = 0; var restListeners = new List<EventListenerDelegate<Event>>(listeners.Count - 1); for (var i = 0; i < numListeners; ++i) { var otherListener = listeners[i]; if (otherListener != listener) { restListeners[index++] = otherListener; } } _eventListeners[type] = restListeners; } } } public void RemoveEventListeners(object type) { if (type != null && _eventListeners != null) { _eventListeners.Remove(type); } else { _eventListeners = null; } } public void RemoveEventListeners() { RemoveEventListeners(null); } public bool HasEventListener(object type, EventListenerDelegate<Event> listener) { List<EventListenerDelegate<Event>> listeners; _eventListeners.TryGetValue(type, out listeners); List<EventListenerDelegate<Event>> nativeListeners; _nativeEventListeners.TryGetValue(type, out nativeListeners); return HasEventListener(nativeListeners, type, listener) || HasEventListener(listeners, type, listener); } protected bool HasEventListener(List<EventListenerDelegate<Event>> listeners, object type, EventListenerDelegate<Event> listener) { if (listeners != null) { if (listeners.Count != 0) { if (listener != null) { return listeners.Contains(listener); } return true; } } return false; } public bool HasEventListener(object type) { return HasEventListener(type, null); } public void DispatchEvent(Event evt) { var bubbles = evt.Bubbles; if (!bubbles && (_eventListeners == null || !(_eventListeners.ContainsKey(evt.Type)))) { return; } var previousTarget = evt.Target; evt.SetTarget(this); if (bubbles && this is Component) { BubbleEvent(evt); } else { InvokeEvent(evt); } if (previousTarget != null) { evt.SetTarget(previousTarget); } } internal bool InvokeEvent(Event evt) { int numListeners = 0; List<EventListenerDelegate<Event>> listeners = null; if (_eventListeners != null && _eventListeners.TryGetValue(evt.Type, out listeners) && listeners != null) { numListeners = listeners.Count; } int nativeNumListeners = 0; List<EventListenerDelegate<Event>> nativeListeners = null; if (_nativeEventListeners != null && _nativeEventListeners.TryGetValue(evt.Type, out nativeListeners) && nativeListeners != null) { nativeNumListeners = nativeListeners.Count; } if (nativeNumListeners != 0) { evt.SetCurrentTarget(this); for (var i = 0; i < nativeNumListeners; ++i) { var listener = nativeListeners[i]; if (listener != null) { listener(evt); } if (evt.StopsImmediatePropagation) { return true; } } return evt.StopsPropagation; } if (numListeners != 0) { evt.SetCurrentTarget(this); for (var i = 0; i < numListeners; ++i) { var listener = listeners[i]; if (listener != null) { listener(evt); } if (evt.StopsImmediatePropagation) { return true; } } return evt.StopsPropagation; } return false; } internal void BubbleEvent(Event evt) { List<EventDispatcher> chain; var element = this as Component; var length = 1; if (_bubbleChains == null) _bubbleChains = new List<List<EventDispatcher>>(); if (_bubbleChains.Count > 0) { chain = PopFromChains(); chain[0] = element; } else { chain = new List<EventDispatcher>(); chain.Add(element); } while ((element = element.Parent) != null) { chain[length++] = element; } for (var i = 0; i < length; ++i) { var stopPropagation = chain[i].InvokeEvent(evt); if (stopPropagation) { break; } } chain.Clear(); PushToChains(chain); } public void DispatchEvent(object type, bool bubbles = false, object data = null) { if (bubbles || HasEventListener(type)) { var evt = Event.FromPool<Event>(type, bubbles, data); DispatchEvent(evt); if (!evt._disposed) { evt.Dispose(); } Event.ToPool(evt); } } private static List<EventDispatcher> PopFromChains() { var result = _bubbleChains[_bubbleChains.Count - 1]; _bubbleChains.RemoveAt(_bubbleChains.Count - 1); return result; } private void PushToChains(List<EventDispatcher> evt) { _bubbleChains.Add(evt); } } }
using System; using System.Linq.Expressions; namespace Utils.Specification { public class Spec<T> { public virtual Expression<Func<T, bool>> Expression { get; init; } public Spec() { } public Spec(Expression<Func<T,bool>> expression) { Expression = expression ?? throw new ArgumentNullException(nameof(expression)); } public static implicit operator Expression<Func<T, bool>>(Spec<T> spec) => spec?.Expression ?? throw new ArgumentNullException(nameof(spec)); public static implicit operator Func<T, bool>(Spec<T> spec) => spec.IsSatisfiedBy; public static bool operator true(Spec<T> _) => false; public static bool operator false(Spec<T> _) => false; public bool IsSatisfiedBy(T t) => Expression?.AsFunc()(t) ?? false; public static Spec<T> operator &(Spec<T> spec1, Spec<T> spec2) => new AndSpec<T>(spec1, spec2); public static Spec<T> operator |(Spec<T> spec1, Spec<T> spec2) => new OrSpec<T>(spec1, spec2); public static Spec<T> operator !(Spec<T> spec) => new NotSpec<T>(spec); } }
using System; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace XamarinCustomLoader.Views { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class MainPage : ContentPage { public MainPage() { InitializeComponent(); } public async void OnSimpleLoaderButtonClicked(object sender, EventArgs e) { await Navigation.PushAsync(new CustomLoaderExamplePage()); } public async void LoaderWithBlurEffectClicked(object sender, EventArgs e) { await Navigation.PushAsync(new CustomLoaderWithBlurEffect()); } } }
using System; using System.Collections.Generic; namespace DelftTools.Utils { public enum TimeSelectionMode { /// <summary> /// Select a timespan /// </summary> Range, /// <summary> /// Select a single timestep /// </summary> Single } public enum SnappingMode { /// <summary> /// No snapping needed. Navigatable can render any timestep /// </summary> None, /// <summary> /// Values send to SetCurrentTimeSelection should be defined in the Navigatable Values /// </summary> Nearest, /// <summary> /// Takes the first value to the left. Used for intervals that are defined on the first day of the period (1 jan 2001), but that apply to the whole year or whole month, etc. /// </summary> Interval, } /// <summary> /// Object with time dependency. For example a layer or a view /// /// *------------*-----------*----------------*-----------* /// [ ] /// </summary> public interface ITimeNavigatable { /// <summary> /// Used as current time or as selection start time in case of range selection. /// </summary> DateTime? TimeSelectionStart { get; } /// <summary> /// If set - range is selected. /// </summary> DateTime? TimeSelectionEnd { get; } /// <summary> /// If set - the date time format provider to be used when rendering this navigatable in a (time) chart. /// </summary> TimeNavigatableLabelFormatProvider CustomDateTimeFormatProvider { get; } /// <summary> /// Selects range or single time (start). /// </summary> /// <param name="start"></param> /// <param name="end"></param> void SetCurrentTimeSelection(DateTime? start, DateTime? end); event Action CurrentTimeSelectionChanged; /// <summary> /// All possible times. /// </summary> IEnumerable<DateTime> Times { get; } event Action TimesChanged; /// <summary> /// Can the navigatable show a range or just a single timestep /// </summary> TimeSelectionMode SelectionMode { get; } /// <summary> /// Should values send to SetCurrentTimeSelection be snapped to a defined value /// </summary> SnappingMode SnappingMode {get;} } }
using System.Collections; using System.Collections.Generic; using System.Globalization; using UnityEngine; using UnityEngine.UI; public class UIGameManager : MonoBehaviour { public Slider HPbar; public Text HPtext; public playerHealthInformation currentPlayerHP; public Text LvlText; private PlayerStatInfo playerStats; private static bool UIExists; // Start is called before the first frame update /* NAME: Start SYNOPSIS: DESCRIPTION: This start function is used to load the current UI when the game is started. This handles if the UI does not currently exist it creates the handler if it does exist destroy the current gameObject. This is loads player stats that are displayed on the UI. RETURNS: AUTHOR: Thomas Furletti DATE: 07/08/2020 */ void Start() { if (!UIExists) { UIExists = true; // stop player from being destroyed on zone change DontDestroyOnLoad(transform.gameObject); } else { Destroy(gameObject); } playerStats = GetComponent<PlayerStatInfo>(); } // Update is called once per frame /* NAME: Update SYNOPSIS: DESCRIPTION: This function gets the players current stats and health to be displayed on the UI. You can see it on the top right of the screen were there is a working Health bar and some of the players stats including level. RETURNS: AUTHOR: Thomas Furletti DATE: 07/08/2020 */ void Update() { HPbar.maxValue = currentPlayerHP.playerMaxHp; HPbar.value = currentPlayerHP.playerCurrentHp; HPtext.text = "HP: " + currentPlayerHP.playerCurrentHp + "/" + currentPlayerHP.playerMaxHp; LvlText.text = "Lvl: " + playerStats.playerLevel; } }
public enum CursorTransformEnum { None, Translate, Scale, Rotate }
using System; using System.Collections.Generic; using PterodactylEngine; using Xunit; namespace UnitTestEngine { public class TestHorizontalLine { [Fact] public void CorrectData() { string expected = Environment.NewLine + "------" + Environment.NewLine; HorizontalLine testObject = new HorizontalLine(); Assert.Equal(expected, testObject.Create()); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; using CoralBrain; using Noise; using System.Threading; using RWCustom; using Rainbow.Enum; using Rainbow.CreatureOverhaul; namespace Rainbow.CreatureAddition { public class Wolf : AirBreatherCreature { public Wolf(AbstractCreature abstractCreature, World world) : base(abstractCreature, world) { this.feetStuckPos = default; this.standing = false; float num = 0.5f; //* this.slugcatStats.bodyWeightFac; base.bodyChunks = new BodyChunk[2]; base.bodyChunks[0] = new BodyChunk(this, 0, new Vector2(0f, 0f), 4f, num / 2f); base.bodyChunks[1] = new BodyChunk(this, 1, new Vector2(0f, 0f), 4.5f, num / 2f); this.bodyChunkConnections = new PhysicalObject.BodyChunkConnection[1]; this.bodyChunkConnections[0] = new PhysicalObject.BodyChunkConnection(base.bodyChunks[0], base.bodyChunks[1], 12f, PhysicalObject.BodyChunkConnection.Type.Normal, 1f, 0.5f); this.animation = new BlankAnimation(this); this.bodyMode = Wolf.BodyModeIndex.Default; base.airFriction = 0.999f; base.gravity = 0.9f; this.bounce = 0.1f; this.surfaceFriction = 0.5f; this.collisionLayer = 1; base.waterFriction = 0.96f; base.buoyancy = 0.95f; this.airInLungs = 1f; this.flipDirection = UnityEngine.Random.value < 0.5f ? -1 : 1; this.room = world.GetAbstractRoom(abstractCreature.pos.room).realizedRoom; this.swimBits = new CoralCircuit.CircuitBit[2]; if (world.GetAbstractRoom(abstractCreature.pos.room).shelter) { this.sleepCounter = 100; for (int j = 0; j < world.GetAbstractRoom(abstractCreature.pos.room).creatures.Count; j++) { if (world.GetAbstractRoom(abstractCreature.pos.room).creatures[j].creatureTemplate.type != CreatureTemplate.Type.Slugcat || world.GetAbstractRoom(abstractCreature.pos.room).creatures[j].creatureTemplate.type != EnumExt_Rainbow.Wolf) { this.sleepCounter = 0; } } (this.abstractCreature.abstractAI as WolfAbstractAI).lastShelter = this.coord; } this.connections = new List<MovementConnection>(); if ((this.abstractCreature.abstractAI as WolfAbstractAI).guardian != null && (this.abstractCreature.abstractAI as WolfAbstractAI).guardian.realizedCreature != null) { this.slugcat = (this.abstractCreature.abstractAI as WolfAbstractAI).guardian.realizedCreature as Player; Debug.Log("slugcat found"); } } public Player slugcat; public bool standing; private Vector2? feetStuckPos; public CoralCircuit.CircuitBit[] swimBits; public int flipDirection { get; set; } public int sleepCounter; public float sleepCurlUp; public float aerobicLevel; public void AerobicIncrease(float f) { this.aerobicLevel = Mathf.Min(1f, this.aerobicLevel + f / 9f); } public bool moving; public bool submerged; public float drown; public bool exhausted; public int slowMovementStun; public float swimCycle; public bool leftFoot; public Color color => (this.State as WolfState).color; public override void InitiateGraphicsModule() { base.InitiateGraphicsModule(); if (base.graphicsModule == null) { base.graphicsModule = new WolfGraphics(this); } //base.graphicsModule.Reset(); } public override void SpitOutOfShortCut(IntVector2 pos, Room newRoom, bool spitOutAllSticks) { base.SpitOutOfShortCut(pos, newRoom, spitOutAllSticks); Vector2 a = Custom.IntVector2ToVector2(newRoom.ShorcutEntranceHoleDirection(pos)); for (int i = 0; i < base.bodyChunks.Length; i++) { base.bodyChunks[i].HardSetPosition(newRoom.MiddleOfTile(pos) - a * (-0.5f + (float)i) * 5f); base.bodyChunks[i].vel = a * 2f; } if (base.graphicsModule != null) { base.graphicsModule.Reset(); } } public IntVector2 occupyTile; public List<IntVector2> pastPositions; public Vector2 lookPoint; public MovementConnection commitedToMove; public List<MovementConnection> connections; private MovementConnection shortcutComingUp; public int commitToMoveCounter; public int commitedMoveFollowChunk; public bool drop; public int stuckOnShortcutCounter; private int pathWithExitsCounter; private bool pathingWithExits; public override void NewRoom(Room newRoom) { base.NewRoom(newRoom); this.pastPositions = new List<IntVector2>(); this.commitedToMove = new MovementConnection(MovementConnection.MovementType.Standard, new WorldCoordinate(-1, -1, -1, -1), new WorldCoordinate(-1, -1, -1, -1), 1); this.commitToMoveCounter = 0; this.drop = false; this.lookPoint = new Vector2(UnityEngine.Random.value * newRoom.PixelWidth, UnityEngine.Random.value * newRoom.PixelHeight); } public bool nyooming = false; public IntVector2 lastNonSolidTile; public override void Update(bool eu) { if (this.animation == null) { this.animation = new BlankAnimation(this); } if ((this.rainbowState as IRainbowState).malnourished) { if (this.aerobicLevel == 1f) { this.exhausted = true; } else if (this.aerobicLevel < 0.4f) { this.exhausted = false; } if (this.exhausted) { this.slowMovementStun = Math.Max(this.slowMovementStun, (int)Custom.LerpMap(this.aerobicLevel, 0.7f, 0.4f, 6f, 0f)); if (this.aerobicLevel > 0.9f && UnityEngine.Random.value < 0.05f) { this.Stun(7); } if (this.aerobicLevel > 0.9f && UnityEngine.Random.value < 0.1f) { this.standing = false; } if (!this.lungsExhausted || this.animation.idx == Wolf.WolfAnimation.AnimationIndex.SurfaceSwim) { this.swimCycle += 0.05f; } } else { this.slowMovementStun = Math.Max(this.slowMovementStun, (int)Custom.LerpMap(this.aerobicLevel, 1f, 0.4f, 2f, 0f, 2f)); } } else { this.exhausted = false; } if (this.lungsExhausted) { this.aerobicLevel = 1f; } else { this.aerobicLevel = Mathf.Max(1f - this.airInLungs, this.aerobicLevel - ((!this.rainbowState.malnourished) ? 1f : 1.2f) / (this.moving ? 1100f : 400f) * (1f + 3f * Mathf.InverseLerp(0.9f, 1f, this.aerobicLevel))); } base.Update(eu); if (this.room == null) { return; } if (!this.room.GetTile(base.mainBodyChunk.pos).Solid) { this.lastNonSolidTile = this.room.GetTilePosition(base.mainBodyChunk.pos); } else { base.mainBodyChunk.HardSetPosition(this.room.MiddleOfTile(this.lastNonSolidTile)); } this.surfaceFriction = ((!base.Consious) ? 0.3f : 0.5f); if (this.Consious) { this.Act(eu); } else if (base.dead) { if (this.animation.idx != Wolf.WolfAnimation.AnimationIndex.Dead) { this.animation = new Wolf.DeadAnimation(this); } this.bodyMode = Wolf.BodyModeIndex.Dead; } else { if (base.stun > 0) { if (this.animation.idx != WolfAnimation.AnimationIndex.None) { this.animation = new BlankAnimation(this); } this.bodyMode = Wolf.BodyModeIndex.Stunned; } this.LungUpdate(); } if (this.bodyMode == Wolf.BodyModeIndex.WallClimb) { this.wallSlideCounter++; } else { this.wallSlideCounter = 0; } if (this.backwardsCounter > 0) { this.backwardsCounter--; } if (this.forceFeetToHorizontalBeamTile > 0) { this.forceFeetToHorizontalBeamTile--; } } public bool visualize = true; public DebugSprite[] dbsprs; public bool climbingUpComing; public int bodyIdxChangeCounter; //moveModeChangeCounter; public float flip; public int notFollowingPathToCurrentGoalCounter; public float MovementSpeed { get { if (this.animation is CommunicationAnimation && (this.animation as CommunicationAnimation).stop) { return 0f; } return Mathf.Max(this.LittleStuck, Mathf.Lerp(this.AI.runSpeedGoal, 0.3f + 0.7f * base.abstractCreature.personality.energy, Mathf.Abs(base.abstractCreature.personality.energy - 0.5f))); } } private int lastFlipDirection; public int footingCounter; private void Act(bool eu) { if ((this.abstractCreature.abstractAI as WolfAbstractAI).guardian != null && (this.abstractCreature.abstractAI as WolfAbstractAI).guardian.realizedCreature != null) { this.slugcat = (this.abstractCreature.abstractAI as WolfAbstractAI).guardian.realizedCreature as Player; } this.AI.Update(); if (this.drop && base.mainBodyChunk.pos.y <= this.room.MiddleOfTile(this.commitedToMove.destinationCoord).y && base.mainBodyChunk.lastPos.y > this.room.MiddleOfTile(this.commitedToMove.destinationCoord).y && this.room.aimap.getAItile(this.commitedToMove.destinationCoord).acc == AItile.Accessibility.Climb) { this.bodyMode = Wolf.BodyModeIndex.ClimbingOnBeam; this.commitToMoveCounter = 0; this.drop = false; this.dropGrabTile = new IntVector2?(this.room.GetTilePosition(this.mainBodyChunk.pos)); } if (this.commitToMoveCounter < 1 && (!this.commitedToMove.IsDrop || this.room.GetTilePosition(base.mainBodyChunk.pos).y < this.commitedToMove.destinationCoord.y) && base.mainBodyChunk.vel.y < -5f && base.mainBodyChunk.lastPos.y > base.mainBodyChunk.pos.y) { for (int i = this.room.GetTilePosition(base.mainBodyChunk.lastPos).y; i >= this.room.GetTilePosition(base.mainBodyChunk.pos).y; i--) { if (this.room.aimap.getAItile(new IntVector2(this.room.GetTilePosition(base.mainBodyChunk.pos).x, i)).acc == AItile.Accessibility.Climb) { this.bodyMode = Wolf.BodyModeIndex.ClimbingOnBeam; this.drop = false; this.dropGrabTile = new IntVector2?(this.room.GetTilePosition(this.mainBodyChunk.pos)); break; } } } //Get Current Tile this.occupyTile = this.room.GetTilePosition(this.bodyChunks[1].pos); //Get Next Movement MovementConnection cnt = this.FollowPath(this.room.GetWorldCoordinate(this.occupyTile), true); if (cnt != null) { this.commitedToMove = cnt; } MovementConnection movementConnection = null; int chunk; // = -1; if (this.commitToMoveCounter > 0) { this.commitToMoveCounter--; if (!this.drop) { bool flag2 = this.commitToMoveCounter > 0 && this.room.GetTilePosition(base.bodyChunks[this.commitedMoveFollowChunk].pos) != this.commitedToMove.DestTile; int num3 = 0; while (num3 < this.connections.Count && !flag2) { if (this.room.GetTilePosition(base.bodyChunks[this.commitedMoveFollowChunk].pos) != this.connections[num3].DestTile) { flag2 = false; } num3++; } if (flag2) { this.occupyTile = this.commitedToMove.StartTile; movementConnection = this.commitedToMove; //chunk = this.commitedMoveFollowChunk; } else { this.commitToMoveCounter = -5; } } } else { if (this.commitToMoveCounter < 0) { this.commitToMoveCounter++; } this.occupyTile = this.room.GetTilePosition(this.bodyChunks[1].pos); movementConnection = this.FollowPath(this.room.GetWorldCoordinate(this.occupyTile), true); chunk = 0; int num4 = 0; while (num4 < 2 && chunk < 0) { int num5 = 0; while (num5 < 5 && chunk < 0) { if (this.room.aimap.TileAccessibleToCreature(base.bodyChunks[num4].pos + Custom.fourDirectionsAndZero[num5].ToVector2() * base.bodyChunks[num4].rad, base.Template)) { this.occupyTile = this.room.GetTilePosition(base.bodyChunks[num4].pos + Custom.fourDirectionsAndZero[num5].ToVector2() * base.bodyChunks[num4].rad); movementConnection = this.FollowPath(this.room.GetWorldCoordinate(this.occupyTile), true); chunk = num4; } num5++; } num4++; } if (base.Submersion > 0f && (this.occupyTile.y < -100 || this.SwimTile(this.occupyTile))) { this.bodyMode = Wolf.BodyModeIndex.Swimming; } this.connections.Clear(); } bool flag = false; this.moving = (this.AI.pathFinder.GetDestination.room != base.abstractCreature.pos.room || this.room.GetTilePosition(base.mainBodyChunk.pos).FloatDist(this.AI.pathFinder.GetDestination.Tile) >= 3f || this.occupyTile.FloatDist(this.AI.pathFinder.GetDestination.Tile) >= 3f); if (!this.moving && !SharedPhysics.RayTraceTilesForTerrain(this.room, this.room.GetTilePosition(base.mainBodyChunk.pos), this.AI.pathFinder.GetDestination.Tile)) { this.moving = true; } if (this.moving && this.occupyTile.FloatDist(this.AI.pathFinder.GetEffectualDestination.Tile) < 3f && this.AI.agitation < 0.5f) { this.moving = false; } if (this.animation != null && this.animation is Wolf.AttentiveAnimation && (this.animation as Wolf.AttentiveAnimation).stop) { this.moving = false; } if (this.AI.scared > 0.8f) { this.moving = true; } if (movementConnection != null) { if (this.commitToMoveCounter < 1) { MovementConnection movementConnection2 = this.commitedToMove; this.climbingUpComing = false; for (int k = 0; k < 5; k++) { if (!flag && ((this.room.GetTile(movementConnection2.destinationCoord + new IntVector2(0, 1)).Solid && this.room.GetTile(movementConnection2.destinationCoord + new IntVector2(0, -1)).Solid) || (this.room.GetTile(movementConnection2.destinationCoord + new IntVector2(1, 0)).Solid && this.room.GetTile(movementConnection2.destinationCoord + new IntVector2(-1, 0)).Solid))) { flag = true; } if (!this.climbingUpComing && this.moving && this.room.aimap.getAItile(movementConnection2.destinationCoord).acc == AItile.Accessibility.Climb) { this.climbingUpComing = true; } this.connections.Add(movementConnection2); if (this.shortcutComingUp == null && movementConnection2.type == MovementConnection.MovementType.ShortCut) { this.shortcutComingUp = movementConnection2; } movementConnection2 = this.FollowPath(movementConnection2.destinationCoord, false); int num6 = 0; while (num6 < this.connections.Count && movementConnection2 != null) { if (this.connections[num6].destinationCoord == movementConnection2.destinationCoord) { movementConnection2 = null; } num6++; } if (movementConnection2 == null) { break; } } } if (this.commitToMoveCounter < 1) { for (int l = 0; l < 2; l++) { base.bodyChunks[l].vel += Custom.DirVec(base.bodyChunks[l].pos, this.room.MiddleOfTile(this.commitedToMove.destinationCoord)) * this.LittleStuck * (1f - this.ReallyStuck); } } if (this.moving && this.AI.behavior == WolfAI.Behavior.Idle && this.AI.discomfortTracker.DiscomfortOfTile(this.room.GetWorldCoordinate(this.NextTile)) > this.AI.discomfortTracker.DiscomfortOfTile(this.room.GetWorldCoordinate(this.occupyTile))) { this.moving = false; } if (this.connections.Count > 3) { //Remove loop if (this.connections[1].DestTile == this.commitedToMove.StartTile) { this.commitedToMove = this.connections[1]; this.connections.RemoveAt(0); } } //if (this.connections.Count > 2) //{ // this.movement = this.room.MiddleOfTile(this.connections[1].destinationCoord.Tile) - this.room.MiddleOfTile(this.bodyChunks[1].pos); // this.movement = this.movement.normalized; //} //else //{ this.movement = this.room.MiddleOfTile(this.commitedToMove.destinationCoord.Tile) - this.room.MiddleOfTile(this.bodyChunks[1].pos); this.movement = this.movement.normalized; //} if (flag) { //crawl up this.nyooming = true; } } else { this.movement = Vector2.zero; } if (this.drop) { if (movementConnection != null) { this.footingCounter++; if (this.footingCounter > 10 && this.commitToMoveCounter == 0) { this.drop = false; } } else { this.footingCounter = 0; if (this.room.GetTilePosition(base.mainBodyChunk.pos).y < this.commitedToMove.destinationCoord.y + 2) { this.commitToMoveCounter = 0; } } //movementConnection = null; //chunk = -1; this.occupyTile = new IntVector2(-1, -1); } if (this.ReallyStuck > 0f) { for (int j = 0; j < 2; j++) { base.bodyChunks[j].vel += Custom.RNV() * UnityEngine.Random.value * 3f * Mathf.Pow(this.ReallyStuck, 3f); } } this.GetUnstuckRoutine(); this.MovementUpdate(eu); if (visualize) { if (dbsprs == null) { dbsprs = new DebugSprite[4]; dbsprs[0] = new DebugSprite(Vector2.zero, new FSprite("pixel", true), this.room); dbsprs[0].sprite.scale = 10f; dbsprs[0].sprite.alpha = 0.5f; dbsprs[0].sprite.color = Color.blue; this.room.AddObject(this.dbsprs[0]); dbsprs[1] = new DebugSprite(Vector2.zero, new FSprite("pixel", true), this.room); dbsprs[1].sprite.scale = 10f; dbsprs[1].sprite.alpha = 0.5f; dbsprs[1].sprite.color = Color.red; this.room.AddObject(this.dbsprs[1]); dbsprs[2] = new DebugSprite(Vector2.zero, new FSprite("pixel", true), this.room); dbsprs[2].sprite.scale = 10f; dbsprs[2].sprite.alpha = 0.5f; dbsprs[2].sprite.color = Color.magenta; this.room.AddObject(this.dbsprs[2]); dbsprs[3] = new DebugSprite(Vector2.zero, new FSprite("pixel", true), this.room); dbsprs[3].sprite.scaleX = 2f; dbsprs[3].sprite.alpha = 0.5f; dbsprs[3].sprite.color = Color.cyan; dbsprs[3].sprite.anchorY = 0f; this.room.AddObject(this.dbsprs[3]); } dbsprs[0].pos = this.room.MiddleOfTile(this.occupyTile); if (this.commitedToMove != null) { dbsprs[1].pos = this.room.MiddleOfTile(this.commitedToMove.destinationCoord.Tile); } if (this.connections.Count > 1) { dbsprs[2].pos = this.room.MiddleOfTile(this.connections[1].destinationCoord.Tile); } dbsprs[3].pos = this.room.MiddleOfTile(this.occupyTile); dbsprs[3].sprite.scaleY = this.moving ? 30f : 2f; dbsprs[3].sprite.rotation = Custom.VecToDeg(this.movement); } } public Vector2 movement; public float jumpBoost; public float diveForce; private int crawlTurnDelay; public int lowerBodyFramesOnGround; public int lowerBodyFramesOffGround; public int upperBodyFramesOnGround; public int upperBodyFramesOffGround; public int initSlideCounter; public int slideCounter; private bool corridorDrop; private int canCorridorJump; private int verticalCorridorSlideCounter; private int horizontalCorridorSlideCounter; private int backwardsCounter; public int wallSlideCounter; private void BodymodeUpdate() { this.diveForce = Mathf.Max(0f, this.diveForce - 0.05f); this.waterRetardationImmunity = Mathf.InverseLerp(0f, 0.3f, this.diveForce) * 0.85f; if (this.dropGrabTile != null && (!this.Consious || this.bodyMode == BodyModeIndex.Crawl || (this.bodyMode == BodyModeIndex.Stand && Mathf.Sign(this.movement.y) != 1f))) { this.dropGrabTile = default; } switch (this.bodyMode) { case BodyModeIndex.Default: if (this.standing) { BodyChunk bodyChunk = base.bodyChunks[0]; bodyChunk.vel.y += 4f * this.room.gravity; BodyChunk bodyChunk2 = base.bodyChunks[1]; bodyChunk2.vel.y -= 4f * this.room.gravity; this.dynamicRunSpeed[0] = 4.2f * this.MovementSpeed; this.dynamicRunSpeed[1] = 4f * this.MovementSpeed; if (this.movement.y != 0) { this.dynamicRunSpeed[1] = 2f; } if (this.movement.y > 0 && !base.IsTileSolid(0, 0, 1) && base.IsTileSolid(0, -1, 1) && base.IsTileSolid(0, 1, 1)) { base.bodyChunks[0].vel.x = base.bodyChunks[0].vel.x * 0.8f - (base.bodyChunks[0].pos.x - this.room.MiddleOfTile(this.room.GetTilePosition(base.bodyChunks[0].pos)).x) * 0.4f; } } else { this.dynamicRunSpeed[0] = 4f; if (this.movement.y != 0) { this.dynamicRunSpeed[0] = 2.5f; } if (this.animation.idx == Wolf.WolfAnimation.AnimationIndex.CrawlTurn) { this.dynamicRunSpeed[0] *= 0.75f; } this.dynamicRunSpeed[1] = this.dynamicRunSpeed[0]; } if (this.movement.y < 0 && base.mainBodyChunk.ContactPoint.y == 0 && base.mainBodyChunk.ContactPoint.x == 0 && base.bodyChunks[1].ContactPoint.y == 0 && base.bodyChunks[1].ContactPoint.x == 0 && base.mainBodyChunk.vel.y < -6f) { this.diveForce = Mathf.Min(1f, this.diveForce + 0.142857149f); BodyChunk mainBodyChunk = base.mainBodyChunk; mainBodyChunk.vel.y -= 1.2f * this.diveForce; BodyChunk bodyChunk3 = base.bodyChunks[1]; bodyChunk3.vel.y += 1.2f * this.diveForce; } if (this.dropGrabTile != null) { if ((this.room.GetTilePosition(base.mainBodyChunk.pos) == this.dropGrabTile.Value || this.room.GetTilePosition(base.bodyChunks[1].pos) == this.dropGrabTile.Value) && !this.nyooming && base.Consious) { base.mainBodyChunk.pos = this.room.MiddleOfTile(this.dropGrabTile.Value); if (this.room.GetTile(this.dropGrabTile.Value).verticalBeam && this.animation.idx != Wolf.WolfAnimation.AnimationIndex.ClimbOnBeam) { this.animation = new MovementAnimation(this, Wolf.WolfAnimation.AnimationIndex.ClimbOnBeam); } else if (this.room.GetTile(this.dropGrabTile.Value).horizontalBeam && this.animation.idx != Wolf.WolfAnimation.AnimationIndex.HangFromBeam) { this.animation = new MovementAnimation(this, Wolf.WolfAnimation.AnimationIndex.HangFromBeam); } if (base.bodyChunks[1].pos.y > base.mainBodyChunk.pos.y) { BodyChunk bodyChunk4 = base.bodyChunks[1]; bodyChunk4.vel.x += ((base.bodyChunks[1].pos.x >= base.mainBodyChunk.pos.x) ? 2f : -2f); BodyChunk bodyChunk5 = base.bodyChunks[1]; bodyChunk5.pos.x += ((base.bodyChunks[1].pos.x >= base.mainBodyChunk.pos.x) ? 2f : -2f); } this.dropGrabTile = default(IntVector2?); } else if (this.room.GetTilePosition(base.mainBodyChunk.pos).y > this.dropGrabTile.Value.y + 2 || this.room.GetTilePosition(base.mainBodyChunk.pos).y < this.dropGrabTile.Value.y || this.room.GetTilePosition(base.bodyChunks[1].pos).y < this.dropGrabTile.Value.y || (this.room.GetTilePosition(base.mainBodyChunk.pos).x != this.dropGrabTile.Value.x && this.room.GetTilePosition(base.bodyChunks[1].pos).x != this.dropGrabTile.Value.x)) { this.dropGrabTile = default(IntVector2?); } } break; case BodyModeIndex.Crawl: this.dynamicRunSpeed[0] = 2.5f; if (this.movement.y != 0) { this.dynamicRunSpeed[0] = 1f; } if (this.movement.x > 0 == base.bodyChunks[0].pos.x < base.bodyChunks[1].pos.x && base.bodyChunks[0].onSlope == 0 && base.bodyChunks[1].onSlope == 0) { this.dynamicRunSpeed[0] *= 0.75f; if (this.crawlTurnDelay > 5 && !base.IsTileSolid(0, 0, 1) && !base.IsTileSolid(1, 0, 1) && this.movement.x != 0) { this.crawlTurnDelay = 0; if (!base.IsTileSolid(0, -1, 1) || !base.IsTileSolid(0, 1, 1) && this.animation.idx != Wolf.WolfAnimation.AnimationIndex.CrawlTurn) { this.animation = new MovementAnimation(this, Wolf.WolfAnimation.AnimationIndex.CrawlTurn); } } } this.dynamicRunSpeed[1] = this.dynamicRunSpeed[0]; if (base.bodyChunks[0].onSlope != 0 || base.bodyChunks[1].onSlope != 0) { if (this.movement.x > 0 == base.bodyChunks[0].pos.x < base.bodyChunks[1].pos.x) { this.dynamicRunSpeed[0] *= 0.5f; } else { this.dynamicRunSpeed[0] *= 0.75f; } if (base.bodyChunks[0].onSlope != 0) { BodyChunk bodyChunk6 = base.bodyChunks[0]; bodyChunk6.vel.y -= 1.5f; } if (base.bodyChunks[1].onSlope != 0) { BodyChunk bodyChunk7 = base.bodyChunks[1]; bodyChunk7.vel.y -= 1.5f; } } if (base.bodyChunks[0].ContactPoint.y > -1 && this.movement.x != 0 && base.bodyChunks[1].pos.y < base.bodyChunks[0].pos.y - 3f && base.bodyChunks[1].ContactPoint.x == this.movement.x) { BodyChunk bodyChunk8 = base.bodyChunks[1]; bodyChunk8.pos.y += 1f; } if (this.movement.y < 0) { base.GoThroughFloors = true; for (int j = 0; j < 2; j++) { if (!base.IsTileSolid(j, 0, -1) && (base.IsTileSolid(j, -1, -1) || base.IsTileSolid(j, 1, -1))) { base.bodyChunks[j].vel.x = base.bodyChunks[j].vel.x * 0.8f - (base.bodyChunks[j].pos.x - this.room.MiddleOfTile(this.room.GetTilePosition(base.bodyChunks[j].pos)).x) * 0.4f; BodyChunk bodyChunk9 = base.bodyChunks[j]; bodyChunk9.vel.y -= 1f; break; } } } if (this.AI.DecideSneak() > 0.5f && (this.lowerBodyFramesOnGround >= 3 || (base.bodyChunks[1].ContactPoint.y < 0 && this.room.GetTile(this.room.GetTilePosition(base.bodyChunks[1].pos) + new IntVector2(0, -1)).Terrain != Room.Tile.TerrainType.Air && this.room.GetTile(this.room.GetTilePosition(base.bodyChunks[0].pos) + new IntVector2(0, -1)).Terrain != Room.Tile.TerrainType.Air)) && this.animation.idx != Wolf.WolfAnimation.AnimationIndex.StandUp) { this.standing = true; this.room.PlaySound(SoundID.Slugcat_Stand_Up, base.mainBodyChunk, false, 0.8f, 1.1f); this.animation = new MovementAnimation(this, Wolf.WolfAnimation.AnimationIndex.StandUp); if (this.movement.x == 0) { if (base.bodyChunks[1].ContactPoint.y == -1 && base.IsTileSolid(1, 0, -1) && !base.IsTileSolid(1, 0, 1)) { this.feetStuckPos = new Vector2?(this.room.MiddleOfTile(this.room.GetTilePosition(base.bodyChunks[1].pos)) + new Vector2(0f, -10f + base.bodyChunks[1].rad)); } else if (base.bodyChunks[0].ContactPoint.y == -1 && base.IsTileSolid(0, 0, -1) && !base.IsTileSolid(0, 0, 1)) { this.feetStuckPos = new Vector2?(base.bodyChunks[0].pos + new Vector2(0f, -1f)); } } } if (base.bodyChunks[1].onSlope != 0 && base.bodyChunks[1].ContactPoint.y > -1 && this.movement.x == 0) { BodyChunk bodyChunk10 = base.bodyChunks[0]; bodyChunk10.vel.x += (float)base.bodyChunks[1].onSlope; } if (this.movement.x != 0 && Mathf.Abs(base.bodyChunks[1].pos.x - base.bodyChunks[1].lastPos.x) > 0.5f) { this.animation.animationFrame++; } else { this.animation.animationFrame = 0; } if (this.animation.animationFrame > 10) { this.animation.animationFrame = 0; this.room.PlaySound(SoundID.Slugcat_Crawling_Step, base.mainBodyChunk); } break; case BodyModeIndex.Stand: BodyChunk bodyChunk11 = base.bodyChunks[0]; bodyChunk11.vel.y += 1.5f * this.room.gravity; BodyChunk bodyChunk12 = base.bodyChunks[1]; bodyChunk12.vel.y -= 4.5f * this.room.gravity; if (!this.standing && this.lowerBodyFramesOnGround >= 5 && this.upperBodyFramesOffGround >= 5) { bool flag = true; if (this.room.GetTilePosition(base.mainBodyChunk.pos).y == this.room.GetTilePosition(base.bodyChunks[1].pos).y + 1 && base.IsTileSolid(1, this.flipDirection, 0) && base.IsTileSolid(0, this.flipDirection, -1)) { bool flag2 = this.room.GetTile(this.room.GetTilePosition(base.bodyChunks[1].pos)).Terrain != Room.Tile.TerrainType.Slope && this.room.GetTile(this.room.GetTilePosition(base.bodyChunks[1].pos) + new IntVector2(0, -1)).Terrain != Room.Tile.TerrainType.Slope && this.room.GetTile(this.room.GetTilePosition(base.bodyChunks[1].pos) + new IntVector2(this.flipDirection, 0)).Terrain != Room.Tile.TerrainType.Slope; if (!flag2) { flag2 = (base.IsTileSolid(0, this.flipDirection, 0) && base.IsTileSolid(1, this.flipDirection, 0)); } if (flag2) { flag = false; if (this.room.GetTile(this.room.GetTilePosition(base.bodyChunks[1].pos) + new IntVector2(-this.flipDirection, 0)).Terrain == Room.Tile.TerrainType.Air) { if (this.room.GetTile(this.room.GetTilePosition(base.bodyChunks[1].pos) + new IntVector2(-this.flipDirection, -1)).Terrain != Room.Tile.TerrainType.Air) { BodyChunk bodyChunk13 = base.bodyChunks[1]; bodyChunk13.vel.x += -1.1f * (float)this.flipDirection; } else if (this.movement.x != this.flipDirection) { if (base.IsTileSolid(0, this.flipDirection, 1)) { this.flipDirection *= -1; } else if (this.movement.y < 0) { BodyChunk bodyChunk14 = base.bodyChunks[1]; bodyChunk14.vel.x += -0.4f * (float)this.flipDirection; BodyChunk bodyChunk15 = base.bodyChunks[0]; bodyChunk15.vel.y -= 1f; } } } } } if (flag && this.AI.DecideSneak() < 0.5f && this.animation.idx != Wolf.WolfAnimation.AnimationIndex.DownOnFours) { this.animation = new MovementAnimation(this, Wolf.WolfAnimation.AnimationIndex.DownOnFours); } } this.dynamicRunSpeed[0] = 4.2f * this.MovementSpeed; this.dynamicRunSpeed[1] = 4f * this.MovementSpeed; if (this.movement.y != 0) { this.dynamicRunSpeed[1] = 2f; } if (base.bodyChunks[1].onSlope != 0) { this.dynamicRunSpeed[0] *= 0.75f; this.dynamicRunSpeed[1] *= 0.75f; if (base.bodyChunks[0].ContactPoint.y == 1) { this.standing = false; } if (this.movement.x == base.bodyChunks[1].onSlope) { base.bodyChunks[1].vel.y -= base.gravity; } base.bodyChunks[1].pos.y -= 2f; } if (this.movement.x != 0) { if (base.bodyChunks[1].ContactPoint.x == this.movement.x) { base.bodyChunks[0].vel.x += this.movement.x; base.bodyChunks[0].vel.y += 2f * this.room.gravity; base.bodyChunks[1].vel.y += 2f * this.room.gravity; } this.animation.animationFrame++; } else { this.animation.animationFrame = 0; } if (this.animation.animationFrame > 6) { this.animation.animationFrame = 0; this.room.PlaySound((!this.leftFoot) ? SoundID.Slugcat_Step_B : SoundID.Slugcat_Step_A, base.mainBodyChunk, false, 0.8f, 1.1f); this.leftFoot = !this.leftFoot; if (this.aerobicLevel < 0.7f) { this.AerobicIncrease(0.05f); } this.room.InGameNoise(new InGameNoise(base.bodyChunks[1].pos, 100f, this, 0.5f)); } if (this.slideCounter > 0) { this.slideCounter++; if (this.slideCounter > 20 || (int)Mathf.Sign(this.movement.x) != -this.slideDirection) { this.slideCounter = 0; } float num = -Mathf.Sin((float)this.slideCounter / 20f * 3.14159274f * 0.5f) + 0.5f; base.mainBodyChunk.vel.x += (num * 3.5f * (float)this.slideDirection - (float)this.slideDirection * ((num >= 0f) ? 0.5f : 0.8f)); base.bodyChunks[1].vel.x += (num * 3.5f * (float)this.slideDirection + (float)this.slideDirection * 0.5f); if ((this.slideCounter == 4 || this.slideCounter == 7 || this.slideCounter == 11) && UnityEngine.Random.value < Mathf.InverseLerp(0f, 0.5f, this.room.roomSettings.CeilingDrips)) { this.room.AddObject(new WaterDrip(base.bodyChunks[1].pos + new Vector2(0f, -base.bodyChunks[1].rad + 1f), Custom.DegToVec((float)this.slideDirection * Mathf.Lerp(30f, 70f, UnityEngine.Random.value)) * Mathf.Lerp(6f, 11f, UnityEngine.Random.value), false)); } } else if (this.movement.x != 0) { if ((int)Mathf.Sign(this.movement.x) == this.slideDirection) { if (this.initSlideCounter < 30) { this.initSlideCounter++; } } else { if (this.initSlideCounter > 10 && base.mainBodyChunk.vel.x > 0f == this.slideDirection > 0 && Mathf.Abs(base.mainBodyChunk.vel.x) > 1f) { this.slideCounter = 1; this.room.PlaySound(SoundID.Slugcat_Skid_On_Ground_Init, base.mainBodyChunk, false, 0.8f, 1.1f); } else { this.slideDirection = (int)Mathf.Sign(this.movement.x); } this.initSlideCounter = 0; } } else if (this.initSlideCounter > 0) { this.initSlideCounter--; } break; case BodyModeIndex.CorridorClimb: base.GoThroughFloors = true; //this.rollDirection = 0; if (this.corridorTurnDir != null) { for (int k = 0; k < 2; k++) { base.bodyChunks[k].vel.y += base.gravity; } } else { if (this.movement.y < 0 && !base.IsTileSolid(0, 0, -1) && !base.IsTileSolid(0, 0, -2) && !base.IsTileSolid(0, 0, -3) && ((base.mainBodyChunk.pos.y < base.bodyChunks[1].pos.y && base.IsTileSolid(0, -1, 1) && base.IsTileSolid(0, 1, 1) && (!base.IsTileSolid(0, -1, 0) || !base.IsTileSolid(0, 1, 0))) || (base.mainBodyChunk.pos.y > base.bodyChunks[1].pos.y && base.IsTileSolid(1, -1, 1) && base.IsTileSolid(1, 1, 1) && (!base.IsTileSolid(1, -1, 0) || !base.IsTileSolid(1, 1, 0))))) { if (base.mainBodyChunk.pos.y < base.bodyChunks[1].pos.y) { if (this.room.GetTile(base.mainBodyChunk.pos).AnyBeam) { this.dropGrabTile = new IntVector2?(this.room.GetTilePosition(base.mainBodyChunk.pos)); } else if (this.room.GetTile(base.mainBodyChunk.pos + new Vector2(0f, -20f)).AnyBeam) { this.dropGrabTile = new IntVector2?(this.room.GetTilePosition(base.mainBodyChunk.pos + new Vector2(0f, -20f))); } } else if (this.room.GetTile(base.bodyChunks[1].pos).AnyBeam) { this.dropGrabTile = new IntVector2?(this.room.GetTilePosition(base.bodyChunks[1].pos)); } else if (this.room.GetTile(base.bodyChunks[1].pos + new Vector2(0f, -20f)).AnyBeam) { this.dropGrabTile = new IntVector2?(this.room.GetTilePosition(base.bodyChunks[1].pos + new Vector2(0f, -20f))); } } else { this.dropGrabTile = default(IntVector2?); } bool flag3 = Mathf.Abs(base.bodyChunks[0].pos.x - base.bodyChunks[1].pos.x) < 5f && base.IsTileSolid(0, -1, 0) && base.IsTileSolid(0, 1, 0); bool flag4 = Mathf.Abs(base.bodyChunks[0].pos.y - base.bodyChunks[1].pos.y) < 7.5f && base.IsTileSolid(0, 0, -1) && base.IsTileSolid(0, 0, 1); bool flag5 = false; if (this.nyooming && this.room.gravity > 0f && this.movement.y < 0 && !base.IsTileSolid(0, 0, -1) && !base.IsTileSolid(1, 0, -1)) { this.corridorDrop = true; this.canCorridorJump = 0; } else if (flag3) { if (base.bodyChunks[0].pos.y > base.bodyChunks[1].pos.y) { flag5 = base.IsTileSolid(1, 0, -1); } else { if (this.room.gravity == 0f) { flag5 = base.IsTileSolid(1, 0, 1); } if (base.bodyChunks[0].pos.y < base.bodyChunks[1].pos.y && this.movement.y > 0) { this.corridorTurnDir = new IntVector2?(new IntVector2(0, 1)); this.canCorridorJump = 0; } } } else if (flag4) { if (this.movement.x != 0 && base.bodyChunks[0].pos.x < base.bodyChunks[1].pos.x == this.movement.x > 0) { this.corridorTurnDir = new IntVector2?(new IntVector2((int)Mathf.Sign(this.movement.x), 0)); this.canCorridorJump = 0; } else { flag5 = (base.IsTileSolid(1, -this.flipDirection, 0) && !base.IsTileSolid(0, this.flipDirection, 0)); } } if (flag5) { this.canCorridorJump = 5; } else if (this.canCorridorJump > 0) { this.canCorridorJump--; } if (this.nyooming && this.slowMovementStun < 1) { if (this.room.gravity == 0f) { Vector2 a = new Vector2(0f, 0f); if (flag3 && base.IsTileSolid(1, 0, (int)Mathf.Sign(base.bodyChunks[1].pos.y - base.bodyChunks[0].pos.y))) { a = new Vector2(0f, -Mathf.Sign(base.bodyChunks[1].pos.y - base.bodyChunks[0].pos.y)); } else if (flag4 && base.IsTileSolid(1, (int)Mathf.Sign(base.bodyChunks[1].pos.x - base.bodyChunks[0].pos.x), 0)) { a = new Vector2(-Mathf.Sign(base.bodyChunks[1].pos.x - base.bodyChunks[0].pos.x), 0f); } if (a.x != 0f || a.y != 0f) { Vector2 pos = this.room.MiddleOfTile(base.bodyChunks[1].pos) - a * 9f; for (int l = 0; l < 4; l++) { if (UnityEngine.Random.value < Mathf.InverseLerp(0f, 0.5f, this.room.roomSettings.CeilingDrips)) { this.room.AddObject(new WaterDrip(pos, a * 5f + Custom.RNV() * 3f, false)); } } this.room.PlaySound(SoundID.Slugcat_Corridor_Horizontal_Slide_Success, base.mainBodyChunk); base.bodyChunks[0].pos += 12f * a; base.bodyChunks[1].pos += 12f * a; base.bodyChunks[0].vel += 7f * a; base.bodyChunks[1].vel += 7f * a; this.horizontalCorridorSlideCounter = 25; this.slowMovementStun = 5; } else { if (flag4 && this.movement.x != 0 && this.movement.y == 0) { a.x = this.movement.x; } else if (flag3 && this.movement.y != 0 && this.movement.x == 0) { a.y = this.movement.y; } if (a.x != 0f || a.y != 0f) { this.room.PlaySound(SoundID.Slugcat_Corridor_Horizontal_Slide_Fail, base.mainBodyChunk); base.bodyChunks[0].vel += 6f * a; base.bodyChunks[1].vel += 4f * a; this.horizontalCorridorSlideCounter = 15; this.slowMovementStun = 15; } } } else if (this.verticalCorridorSlideCounter < 1) { if (flag3 && this.movement.y > -1 && base.bodyChunks[0].pos.y > base.bodyChunks[1].pos.y) { BodyChunk bodyChunk23 = base.bodyChunks[0]; bodyChunk23.vel.y += 15f; BodyChunk bodyChunk24 = base.bodyChunks[1]; bodyChunk24.vel.y += 10f; if (this.canCorridorJump > 0) { Vector2 pos2 = this.room.MiddleOfTile(base.bodyChunks[1].pos) + new Vector2(0f, -9f); for (int m = 0; m < 4; m++) { if (UnityEngine.Random.value < Mathf.InverseLerp(0f, 0.5f, this.room.roomSettings.CeilingDrips)) { this.room.AddObject(new WaterDrip(pos2, new Vector2(Mathf.Lerp(-3f, 3f, UnityEngine.Random.value), 5f), false)); } } this.room.PlaySound(SoundID.Slugcat_Vertical_Chute_Jump_Success, base.mainBodyChunk); this.verticalCorridorSlideCounter = 22; this.slowMovementStun = 2; } else { this.room.PlaySound(SoundID.Slugcat_Vertical_Chute_Jump_Fail, base.mainBodyChunk); this.verticalCorridorSlideCounter = 34; this.slowMovementStun = 18; } this.canCorridorJump = 0; } else if (flag4) { this.flipDirection = ((base.bodyChunks[0].pos.x <= base.bodyChunks[1].pos.x) ? -1 : 1); if ((int)Mathf.Sign(this.movement.x) == this.flipDirection || this.movement.x == 0) { if (this.canCorridorJump > 0 && this.movement.x != 0) { Vector2 pos3 = this.room.MiddleOfTile(base.bodyChunks[1].pos) + new Vector2(-9f * (float)this.flipDirection, 0f); for (int n = 0; n < 4; n++) { if (UnityEngine.Random.value < Mathf.InverseLerp(0f, 0.5f, this.room.roomSettings.CeilingDrips)) { this.room.AddObject(new WaterDrip(pos3, new Vector2((float)this.flipDirection * 5f, Mathf.Lerp(-3f, 3f, UnityEngine.Random.value)), false)); } } this.room.PlaySound(SoundID.Slugcat_Corridor_Horizontal_Slide_Success, base.mainBodyChunk); base.bodyChunks[0].pos.x += 12f * (float)this.flipDirection; base.bodyChunks[1].pos.x += 12f * (float)this.flipDirection; base.bodyChunks[0].pos.y = this.room.MiddleOfTile(base.bodyChunks[0].pos).y; base.bodyChunks[1].pos.y = base.bodyChunks[0].pos.y; base.bodyChunks[0].vel.x += 7f * (float)this.flipDirection; base.bodyChunks[1].vel.x += 7f * (float)this.flipDirection; this.horizontalCorridorSlideCounter = 25; this.slowMovementStun = 5; } else { this.room.PlaySound(SoundID.Slugcat_Corridor_Horizontal_Slide_Fail, base.mainBodyChunk); base.bodyChunks[0].vel.x += 6f * (float)this.flipDirection; base.bodyChunks[1].vel.x += 4f * (float)this.flipDirection; this.horizontalCorridorSlideCounter = 15; this.slowMovementStun = 15; } } } } } if (this.verticalCorridorSlideCounter == 1 || this.horizontalCorridorSlideCounter == 1) { this.slowMovementStun = 15; } float num2 = Mathf.InverseLerp(0f, 10f, (float)Math.Max(this.verticalCorridorSlideCounter, this.horizontalCorridorSlideCounter)); base.bodyChunks[0].vel *= 0.9f - 0.3f * this.surfaceFriction * (1f - num2); base.bodyChunks[1].vel *= 0.9f - 0.3f * this.surfaceFriction * (1f - num2); base.bodyChunks[0].vel.y += base.gravity * Mathf.Clamp(this.surfaceFriction * 8f, 0.2f, 1f) * Mathf.Lerp(1f, 0.2f, Mathf.InverseLerp(0f, 10f, (float)this.verticalCorridorSlideCounter)); base.bodyChunks[1].vel.y += base.gravity * Mathf.Clamp(this.surfaceFriction * 8f, 0.2f, 1f) * Mathf.Lerp(1f, 0.2f, Mathf.InverseLerp(0f, 10f, (float)this.verticalCorridorSlideCounter)); base.bodyChunks[0].vel.y -= base.buoyancy * base.bodyChunks[0].submersion; base.bodyChunks[1].vel.y -= base.buoyancy * base.bodyChunks[1].submersion; this.dynamicRunSpeed[0] = 0f; this.dynamicRunSpeed[1] = 0f; float num3 = 2.4f * Mathf.Clamp(this.surfaceFriction + 0.2f, 0.2f, 0.5f) * 1.05f * this.MovementSpeed; num3 *= Mathf.Lerp(0.1f, 1f, Mathf.InverseLerp(10f, 0f, (float)this.slowMovementStun)); if (this.movement.x != 0 && this.movement.y != 0) { num3 *= 0.4f; } if (this.movement.x != 0 && this.movement.x > 0 == base.bodyChunks[0].pos.x < base.bodyChunks[1].pos.x) { this.backwardsCounter += 2; } else if (this.movement.y > 0 && base.bodyChunks[0].pos.y < base.bodyChunks[1].pos.y) { this.backwardsCounter += 2; } if (this.backwardsCounter > 20) { this.backwardsCounter = 20; } if (this.backwardsCounter > 10) { num3 *= 0.6f; } for (int num4 = 0; num4 < 2; num4++) { if (this.movement.x != 0 && !base.IsTileSolid(num4, (int)Mathf.Sign(this.movement.x), 0)) { base.bodyChunks[num4].vel.x += num3 * this.movement.x; base.bodyChunks[num4].vel.y = base.bodyChunks[num4].vel.y * 0.8f - (base.bodyChunks[num4].pos.y - this.room.MiddleOfTile(this.room.GetTilePosition(base.bodyChunks[num4].pos)).y) * 0.2f; if (this.movement.y == 0) { base.bodyChunks[1 - num4].vel.y = base.bodyChunks[1 - num4].vel.y * 0.8f - (base.bodyChunks[num4].pos.y - this.room.MiddleOfTile(this.room.GetTilePosition(base.bodyChunks[num4].pos)).y) * 0.2f; } break; } if (this.movement.y != 0 && !base.IsTileSolid(num4, 0, (int)Mathf.Sign(this.movement.y))) { base.bodyChunks[num4].vel.y += num3 * (float)this.movement.y; base.bodyChunks[num4].vel.x = base.bodyChunks[num4].vel.x * 0.8f - (base.bodyChunks[num4].pos.x - this.room.MiddleOfTile(this.room.GetTilePosition(base.bodyChunks[num4].pos)).x) * 0.2f; if (this.movement.x == 0) { base.bodyChunks[1 - num4].vel.x = base.bodyChunks[1 - num4].vel.x * 0.8f - (base.bodyChunks[num4].pos.x - this.room.MiddleOfTile(this.room.GetTilePosition(base.bodyChunks[num4].pos)).x) * 0.2f; } break; } } base.bodyChunks[0].vel.x += num3 * (float)this.movement.x * 0.1f; base.bodyChunks[0].vel.y += num3 * (float)this.movement.y * 0.1f; this.standing = (base.bodyChunks[0].pos.y > base.bodyChunks[1].pos.y + 5f); if ((this.movement != Vector2.zero || this.moving) && this.verticalCorridorSlideCounter < 16) { this.animation.animationFrame++; } else { this.animation.animationFrame = 0; } if (this.animation.animationFrame > 12) { this.animation.animationFrame = 1; this.room.PlaySound(SoundID.Slugcat_In_Corridor_Step, base.mainBodyChunk); } if (this.movement.y > 0 && (!base.IsTileSolid(0, -1, 0) || !base.IsTileSolid(0, 1, 0)) && this.room.GetTile(base.mainBodyChunk.pos).verticalBeam && this.animation.idx != Wolf.WolfAnimation.AnimationIndex.ClimbOnBeam) {// && this.shootUpCounter < 1 this.room.PlaySound(SoundID.Slugcat_Grab_Beam, base.mainBodyChunk, false, 0.2f, 1.1f); this.bodyMode = BodyModeIndex.ClimbingOnBeam; this.animation = new MovementAnimation(this, Wolf.WolfAnimation.AnimationIndex.ClimbOnBeam); } else if (this.movement.x != 0 && this.room.GetTile(base.mainBodyChunk.pos).horizontalBeam && base.IsTileSolid(1, 0, -1) && base.IsTileSolid(1, 0, 1) && !base.IsTileSolid(0, (int)Mathf.Sign(this.movement.x), -1) && this.animation.idx != Wolf.WolfAnimation.AnimationIndex.HangFromBeam) { this.bodyMode = BodyModeIndex.ClimbingOnBeam; this.animation = new MovementAnimation(this, Wolf.WolfAnimation.AnimationIndex.HangFromBeam); } } break; case BodyModeIndex.WallClimb: if (base.bodyChunks[0].pos.y > base.bodyChunks[1].pos.y) { if (this.movement.x != 0 && this.movement.x == base.bodyChunks[0].ContactPoint.x) { //this.canWallJump = this.movement.x * -15; } //this.canJump = 1; } if (this.movement.x != 0 && base.IsTileSolid(0, (int)Mathf.Sign(this.movement.x), 0) && base.IsTileSolid(1, (int)Mathf.Sign(this.movement.x), 0)) { base.bodyChunks[0].pos.y += base.gravity * Custom.LerpMap((float)this.wallSlideCounter, 0f, 30f, 0.8f, 0f) * this.room.gravity; base.bodyChunks[0].vel.x += this.movement.x * 0.8f; base.bodyChunks[1].pos.y += base.gravity * Custom.LerpMap((float)this.wallSlideCounter, 0f, 30f, 0.8f, 0f) * this.room.gravity; base.bodyChunks[1].vel.x += this.movement.x * 0.5f; } base.bodyChunks[1].vel.y += base.bodyChunks[1].submersion * this.room.gravity; break; case BodyModeIndex.ClimbingOnBeam: if ((this.animation.idx == Wolf.WolfAnimation.AnimationIndex.GetUpOnBeam || this.animation.idx == Wolf.WolfAnimation.AnimationIndex.StandOnBeam) && !this.room.GetTile(base.bodyChunks[1].pos).horizontalBeam) { if (this.forceFeetToHorizontalBeamTile > 0 && this.room.GetTile(base.bodyChunks[1].pos + new Vector2((float)this.flipDirection * 20f, 0f)).horizontalBeam) { base.bodyChunks[1].pos.x = this.room.MiddleOfTile(base.bodyChunks[1].pos + new Vector2((float)this.flipDirection * 20f, 0f)).x - (float)this.flipDirection * 8f; base.bodyChunks[1].vel.x = 0f; this.forceFeetToHorizontalBeamTile = 20; } else if (this.forceFeetToHorizontalBeamTile > 0 && this.room.GetTile(base.bodyChunks[1].pos - new Vector2((float)this.flipDirection * 20f, 0f)).horizontalBeam) { base.bodyChunks[1].pos.x = this.room.MiddleOfTile(base.bodyChunks[1].pos - new Vector2((float)this.flipDirection * 20f, 0f)).x + (float)this.flipDirection * 8f; base.bodyChunks[1].vel.x = 0f; this.forceFeetToHorizontalBeamTile = 20; } else if (!this.room.GetTile(base.bodyChunks[1].pos + new Vector2(0f, 20f)).horizontalBeam || this.animation.idx != Wolf.WolfAnimation.AnimationIndex.GetUpOnBeam) { this.animation = new BlankAnimation(this); } } if (this.animation.idx != Wolf.WolfAnimation.AnimationIndex.BeamTip && this.animation.idx != Wolf.WolfAnimation.AnimationIndex.ClimbOnBeam && this.animation.idx != Wolf.WolfAnimation.AnimationIndex.GetUpOnBeam && this.animation.idx != Wolf.WolfAnimation.AnimationIndex.HangFromBeam && this.animation.idx != Wolf.WolfAnimation.AnimationIndex.StandOnBeam && this.animation.idx != Wolf.WolfAnimation.AnimationIndex.GetUpToBeamTip && this.animation.idx != Wolf.WolfAnimation.AnimationIndex.HangUnderVerticalBeam) { this.bodyMode = BodyModeIndex.Default; } break; case BodyModeIndex.Swimming: this.GravitateToOpening(); base.GoThroughFloors = true; break; case BodyModeIndex.ZeroG: this.GravitateToOpening(); base.GoThroughFloors = true; if (this.room.gravity > 0f) { this.bodyMode = BodyModeIndex.Default; this.animation = new BlankAnimation(this); } break; } } public IntVector2? dropGrabTile; public int forceFeetToHorizontalBeamTile; #pragma warning disable IDE0060 private void MovementUpdate(bool eu) #pragma warning restore IDE0060 { this.DirectIntoHoles(); int dir = 0 + (int)Mathf.Sign(this.movement.x); this.lastFlipDirection = this.flipDirection; if (dir != this.flipDirection && dir != 0) { this.flipDirection = dir; } int num2 = 0; for (int i = 0; i < 4; i++) { for (int j = 0; j < 2; j++) { if (base.IsTileSolid(j, Custom.eightDirections[i].x, Custom.eightDirections[i].y) && base.IsTileSolid(j, Custom.eightDirections[i + 4].x, Custom.eightDirections[i + 4].y)) { num2++; } } } bool flag = base.bodyChunks[1].onSlope == 0 && !this.moving && this.standing && base.stun < 1 && base.bodyChunks[1].ContactPoint.y == -1; if (this.feetStuckPos != null && !flag) { this.feetStuckPos = default(Vector2?); } else if (this.feetStuckPos == null && flag) { this.feetStuckPos = new Vector2?(new Vector2(base.bodyChunks[1].pos.x, this.room.MiddleOfTile(this.room.GetTilePosition(base.bodyChunks[1].pos)).y + -10f + base.bodyChunks[1].rad)); } if (this.feetStuckPos != null) { this.feetStuckPos = new Vector2?(this.feetStuckPos.Value + new Vector2((base.bodyChunks[1].pos.x - this.feetStuckPos.Value.x) * (1f - this.surfaceFriction), 0f)); base.bodyChunks[1].pos = this.feetStuckPos.Value; if (!base.IsTileSolid(1, 0, -1)) { bool flag2 = base.IsTileSolid(1, 1, -1) && !base.IsTileSolid(1, 1, 0); bool flag3 = base.IsTileSolid(1, -1, -1) && !base.IsTileSolid(1, -1, 0); if (flag3 && !flag2) { this.feetStuckPos = new Vector2?(this.feetStuckPos.Value + new Vector2(-1.6f * this.surfaceFriction, 0f)); } else if (flag2 && !flag3) { this.feetStuckPos = new Vector2?(this.feetStuckPos.Value + new Vector2(1.6f * this.surfaceFriction, 0f)); } else { this.feetStuckPos = default(Vector2?); } } } if ((num2 > 1 && base.bodyChunks[0].onSlope == 0 && base.bodyChunks[1].onSlope == 0 && (!base.IsTileSolid(0, 0, 0) || !base.IsTileSolid(1, 0, 0))) || (base.IsTileSolid(0, -1, 0) && base.IsTileSolid(0, 1, 0)) || (base.IsTileSolid(1, -1, 0) && base.IsTileSolid(1, 1, 0))) { this.goIntoCorridorClimb++; } else { this.goIntoCorridorClimb = 0; bool flag4 = base.bodyChunks[0].ContactPoint.y == -1 || base.bodyChunks[1].ContactPoint.y == -1; this.bodyMode = Wolf.BodyModeIndex.Default; if (flag4) { if (base.bodyChunks[0].pos.y > base.bodyChunks[1].pos.y + 3f && !base.IsTileSolid(1, 0, 1) && this.animation.idx != Wolf.WolfAnimation.AnimationIndex.CrawlTurn && base.bodyChunks[0].ContactPoint.y > -1) { this.bodyMode = Wolf.BodyModeIndex.Stand; } else { this.bodyMode = Wolf.BodyModeIndex.Crawl; } } else if (this.jumpBoost > 0f && this.nyooming) // && (this.input[0].jmp || this.simulateHoldJumpButton > 0) { this.jumpBoost -= 1.5f; base.bodyChunks[0].vel.y += (this.jumpBoost + 1f) * 0.3f; base.bodyChunks[1].vel.y += (this.jumpBoost + 1f) * 0.3f; } else { this.jumpBoost = 0f; } if (base.bodyChunks[0].ContactPoint.x != 0 && base.bodyChunks[0].ContactPoint.x == (int)Mathf.Sign(this.movement.x)) { if (base.bodyChunks[0].lastContactPoint.x != (int)Mathf.Sign(this.movement.x)) { this.room.PlaySound(SoundID.Slugcat_Enter_Wall_Slide, base.mainBodyChunk, false, 0.8f, 1.1f); } this.bodyMode = Wolf.BodyModeIndex.WallClimb; } if (this.movement.x != 0 && base.bodyChunks[0].pos.y > base.bodyChunks[1].pos.y && this.animation.idx != Wolf.WolfAnimation.AnimationIndex.CrawlTurn && !base.IsTileSolid(0, (int)Mathf.Sign(this.movement.x), 0) && base.IsTileSolid(1, (int)Mathf.Sign(this.movement.x), 0) && base.bodyChunks[1].ContactPoint.x == (int)Mathf.Sign(this.movement.x) && this.animation.idx != Wolf.WolfAnimation.AnimationIndex.LedgeCrawl) { this.bodyMode = Wolf.BodyModeIndex.Crawl; this.animation = new MovementAnimation(this, Wolf.WolfAnimation.AnimationIndex.LedgeCrawl); } if (this.movement.y > 0 && base.IsTileSolid(0, 0, 1) && !base.IsTileSolid(1, 0, 1) && (base.IsTileSolid(1, -1, 1) || base.IsTileSolid(1, 1, 1))) { this.animation = new BlankAnimation(this); base.bodyChunks[1].vel.y += 2f * this.room.gravity; base.bodyChunks[0].vel.x -= (base.bodyChunks[0].pos.x - base.bodyChunks[1].pos.x) * 0.25f * this.room.gravity; base.bodyChunks[0].vel.y -= this.room.gravity; } } if (this.movement.y > 0 && this.movement.x == 0 && this.bodyMode == BodyModeIndex.Default && base.firstChunk.pos.y - base.firstChunk.lastPos.y < 2f && base.bodyChunks[1].ContactPoint.y == 0 && !base.IsTileSolid(0, 0, 1) && base.IsTileSolid(0, -1, 1) && base.IsTileSolid(0, 1, 1) && !base.IsTileSolid(1, -1, 0) && !base.IsTileSolid(1, 1, 0) && this.room.GetTilePosition(base.firstChunk.pos) == this.room.GetTilePosition(base.bodyChunks[1].pos) + new IntVector2(0, 1) && Mathf.Abs(base.firstChunk.pos.x - this.room.MiddleOfTile(base.firstChunk.pos).x) < 5f && this.room.gravity > 0f) { base.firstChunk.pos.x = this.room.MiddleOfTile(base.firstChunk.pos).x; base.firstChunk.pos.y += 1f; base.firstChunk.vel.y += 1f; base.bodyChunks[1].vel.y += 1f; base.bodyChunks[1].pos.y += 1f; } if (this.AI.DecideSneak() > 0.5f) { if (base.bodyChunks[1].onSlope == 0 || !base.IsTileSolid(0, 0, 1)) { this.standing = true; } } else if (this.AI.DecideSneak() < 0.3f) { if (this.standing && this.bodyMode == BodyModeIndex.Stand) { this.room.PlaySound(SoundID.Slugcat_Down_On_Fours, base.mainBodyChunk); } this.standing = false; } if (this.room.gravity > 0f && this.animation.idx == Wolf.WolfAnimation.AnimationIndex.ZeroGPoleGrab) { this.bodyMode = BodyModeIndex.ClimbingOnBeam; if (this.room.GetTile(base.mainBodyChunk.pos).horizontalBeam && this.animation.idx != Wolf.WolfAnimation.AnimationIndex.HangFromBeam) { this.animation = new MovementAnimation(this, Wolf.WolfAnimation.AnimationIndex.HangFromBeam); } else if (this.animation.idx != Wolf.WolfAnimation.AnimationIndex.ClimbOnBeam) { this.animation = new MovementAnimation(this, Wolf.WolfAnimation.AnimationIndex.ClimbOnBeam); } } if (this.goIntoCorridorClimb > 2 && !this.corridorDrop) { this.bodyMode = BodyModeIndex.CorridorClimb; if (this.corridorTurnDir == null) { this.animation = new BlankAnimation(this); } else if (this.animation.idx != WolfAnimation.AnimationIndex.CorridorTurn) { this.animation = new MovementAnimation(this, Wolf.WolfAnimation.AnimationIndex.CorridorTurn); } } if (this.corridorDrop) { this.bodyMode = BodyModeIndex.Default; this.animation = new BlankAnimation(this); if (this.movement.y >= 0 || this.goIntoCorridorClimb < 2) { this.corridorDrop = false; } if (base.bodyChunks[0].pos.y < base.bodyChunks[1].pos.y) { for (int k = 0; k < Custom.IntClamp((int)(base.bodyChunks[0].vel.y * -0.3f), 1, 10); k++) { if (base.IsTileSolid(0, 0, -k)) { this.corridorDrop = false; break; } } } } if (this.bodyMode != BodyModeIndex.WallClimb || base.bodyChunks[0].submersion == 1f) { bool flag5 = this.movement.y < 0 || this.movement.y <= 0f; if ((base.bodyChunks[0].submersion > 0.2f || base.bodyChunks[1].submersion > 0.2f) && this.bodyMode != BodyModeIndex.CorridorClimb) { if ((this.animation.idx != WolfAnimation.AnimationIndex.SurfaceSwim || flag5 || base.bodyChunks[0].pos.y < this.room.FloatWaterLevel(base.bodyChunks[0].pos.x) - 80f) && base.bodyChunks[0].pos.y < this.room.FloatWaterLevel(base.bodyChunks[0].pos.x) - ((!flag5) ? 30f : 10f) && base.bodyChunks[1].submersion > ((!flag5) ? 0.6f : -1f) && this.animation.idx != Wolf.WolfAnimation.AnimationIndex.DeepSwim) { this.bodyMode = BodyModeIndex.Swimming; this.animation = new MovementAnimation(this, WolfAnimation.AnimationIndex.DeepSwim); } else if ((!base.IsTileSolid(1, 0, -1) || base.bodyChunks[1].submersion == 1f) && this.animation.idx != WolfAnimation.AnimationIndex.BeamTip && this.animation.idx != WolfAnimation.AnimationIndex.ClimbOnBeam && this.animation.idx != WolfAnimation.AnimationIndex.GetUpOnBeam && this.animation.idx != WolfAnimation.AnimationIndex.GetUpToBeamTip && this.animation.idx != WolfAnimation.AnimationIndex.HangFromBeam && this.animation.idx != WolfAnimation.AnimationIndex.StandOnBeam && this.animation.idx != WolfAnimation.AnimationIndex.LedgeGrab && this.animation.idx != WolfAnimation.AnimationIndex.HangUnderVerticalBeam && this.animation.idx != Wolf.WolfAnimation.AnimationIndex.SurfaceSwim) { this.bodyMode = BodyModeIndex.Swimming; this.animation = new MovementAnimation(this, WolfAnimation.AnimationIndex.SurfaceSwim); } } } if (this.room.gravity == 0f && this.bodyMode != BodyModeIndex.CorridorClimb && this.animation.idx != Wolf.WolfAnimation.AnimationIndex.VineGrab) { this.bodyMode = BodyModeIndex.ZeroG; if (this.animation.idx != WolfAnimation.AnimationIndex.ZeroGSwim && this.animation.idx != WolfAnimation.AnimationIndex.ZeroGPoleGrab) { this.animation = new MovementAnimation(this, ((!this.room.GetTile(base.mainBodyChunk.pos).horizontalBeam && !this.room.GetTile(base.mainBodyChunk.pos).verticalBeam) ? WolfAnimation.AnimationIndex.ZeroGSwim : WolfAnimation.AnimationIndex.ZeroGPoleGrab)); } } if (this.vineGrabDelay > 0) { this.vineGrabDelay--; } if (this.animation.idx != WolfAnimation.AnimationIndex.VineGrab && this.vineGrabDelay == 0 && this.room.climbableVines != null) { if (this.room.gravity > 0f && this.wantToGrab > 0) { int num4 = Custom.IntClamp((int)(Vector2.Distance(base.mainBodyChunk.lastPos, base.mainBodyChunk.pos) / 5f), 1, 10); for (int l = 0; l < num4; l++) { Vector2 pos = Vector2.Lerp(base.mainBodyChunk.lastPos, base.mainBodyChunk.pos, (num4 <= 1) ? 0f : ((float)l / (float)(num4 - 1))); ClimbableVinesSystem.VinePosition vinePosition = this.room.climbableVines.VineOverlap(pos, base.mainBodyChunk.rad); if (vinePosition != null) { if (this.room.climbableVines.GetVineObject(vinePosition) is CoralNeuron) { this.room.PlaySound(SoundID.Grab_Neuron, base.mainBodyChunk); } else if (this.room.climbableVines.GetVineObject(vinePosition) is CoralStem) { this.room.PlaySound(SoundID.Grab_Coral_Stem, base.mainBodyChunk); } else if (this.room.climbableVines.GetVineObject(vinePosition) is DaddyCorruption.ClimbableCorruptionTube) { this.room.PlaySound(SoundID.Grab_Corruption_Tube, base.mainBodyChunk); } if (this.animation.idx != Wolf.WolfAnimation.AnimationIndex.VineGrab) { this.animation = new MovementAnimation(this, WolfAnimation.AnimationIndex.VineGrab); } (this.animation as MovementAnimation).vinePos = vinePosition; this.wantToGrab = 0; break; } } } else if (this.animation.idx != Wolf.WolfAnimation.AnimationIndex.VineGrab && (this.movement != Vector2.zero || this.moving) && this.room.gravity == 0f) { ClimbableVinesSystem.VinePosition vinePosition2 = this.room.climbableVines.VineOverlap(base.mainBodyChunk.pos, base.mainBodyChunk.rad); if (vinePosition2 != null) { if (this.room.climbableVines.GetVineObject(vinePosition2) is CoralNeuron) { this.room.PlaySound(SoundID.Grab_Neuron, base.mainBodyChunk); } else if (this.room.climbableVines.GetVineObject(vinePosition2) is CoralStem) { this.room.PlaySound(SoundID.Grab_Coral_Stem, base.mainBodyChunk); } else if (this.room.climbableVines.GetVineObject(vinePosition2) is DaddyCorruption.ClimbableCorruptionTube) { this.room.PlaySound(SoundID.Grab_Corruption_Tube, base.mainBodyChunk); } if (this.animation.idx != Wolf.WolfAnimation.AnimationIndex.VineGrab) { this.animation = new MovementAnimation(this, WolfAnimation.AnimationIndex.VineGrab); } (this.animation as MovementAnimation).vinePos = vinePosition2; this.wantToGrab = 0; } } } this.dynamicRunSpeed[0] = 3.6f; this.dynamicRunSpeed[1] = 3.6f; float friction = 2.4f; //Animation Update if (!this.animation.Continue) { this.animation = new BlankAnimation(this); } else { this.animation.Update(); } if (base.bodyChunks[0].ContactPoint.x == (int)Mathf.Sign(this.movement.x) && this.movement.x != 0 && base.bodyChunks[0].pos.y > this.room.MiddleOfTile(this.room.GetTilePosition(base.bodyChunks[0].pos)).y && (this.bodyMode == BodyModeIndex.Default || this.bodyMode == BodyModeIndex.WallClimb) && !base.IsTileSolid(0, -(int)Mathf.Sign(this.movement.x), 0) && !base.IsTileSolid(0, 0, -2) && !base.IsTileSolid(0, (int)Mathf.Sign(this.movement.x), 1) && this.animation.idx != Wolf.WolfAnimation.AnimationIndex.LedgeGrab) { this.animation = new MovementAnimation(this, Wolf.WolfAnimation.AnimationIndex.LedgeGrab); this.bodyMode = BodyModeIndex.Default; } if (this.bodyMode == BodyModeIndex.Crawl) { this.crawlTurnDelay++; } else { this.crawlTurnDelay = 0; } if (this.standing && base.IsTileSolid(1, 0, 1)) { this.standing = false; } if (this.slugcat != null && this.slugcat.animation == Player.AnimationIndex.BeamTip && !this.room.GetTile(base.bodyChunks[1].pos).verticalBeam && this.room.GetTile(base.bodyChunks[1].pos + new Vector2(0f, -20f)).verticalBeam && this.animation.idx != Wolf.WolfAnimation.AnimationIndex.BeamTip) { this.animation = new MovementAnimation(this, Wolf.WolfAnimation.AnimationIndex.BeamTip); base.bodyChunks[1].vel.x = 0f; base.bodyChunks[1].vel.y = 0f; this.wantToGrab = -1; } this.BodymodeUpdate(); this.bodyChunkConnections[0].type = this.corridorTurnDir == null ? PhysicalObject.BodyChunkConnection.Type.Normal : PhysicalObject.BodyChunkConnection.Type.Pull; this.wantToGrab = ((this.movement.y <= 0) ? 0 : 1); if (this.wantToGrab > 0 && (this.bodyMode == BodyModeIndex.Default || this.bodyMode == BodyModeIndex.WallClimb || this.bodyMode == BodyModeIndex.Stand || this.bodyMode == BodyModeIndex.ClimbingOnBeam || this.bodyMode == BodyModeIndex.Swimming) && (base.bodyChunks[1].pos.y <= base.firstChunk.pos.y || this.room.GetTilePosition(base.bodyChunks[0].pos).x != this.room.GetTilePosition(base.bodyChunks[1].pos).x) && this.animation.idx != WolfAnimation.AnimationIndex.ClimbOnBeam && this.animation.idx != WolfAnimation.AnimationIndex.HangFromBeam && this.animation.idx != WolfAnimation.AnimationIndex.GetUpOnBeam && this.animation.idx != WolfAnimation.AnimationIndex.DeepSwim && this.animation.idx != WolfAnimation.AnimationIndex.HangUnderVerticalBeam && this.animation.idx != WolfAnimation.AnimationIndex.GetUpToBeamTip && this.animation.idx != WolfAnimation.AnimationIndex.VineGrab) { int x = this.room.GetTilePosition(base.bodyChunks[0].pos).x; int num6 = this.room.GetTilePosition(base.bodyChunks[0].lastPos).y; int num7 = this.room.GetTilePosition(base.bodyChunks[0].pos).y; if (num7 > num6) { int num8 = num6; num6 = num7; num7 = num8; } for (int m = num6; m >= num7; m--) { if (this.room.GetTile(x, m).horizontalBeam && this.animation.idx != Wolf.WolfAnimation.AnimationIndex.HangFromBeam) { this.animation = new MovementAnimation(this, Wolf.WolfAnimation.AnimationIndex.HangFromBeam); this.room.PlaySound(SoundID.Slugcat_Grab_Beam, base.mainBodyChunk, false, 0.8f, 1.1f); base.bodyChunks[0].vel.y = 0f; base.bodyChunks[1].vel.y *= 0.25f; base.bodyChunks[0].pos.y = this.room.MiddleOfTile(new IntVector2(x, m)).y; break; } } this.GrabVerticalPole(); if (this.slugcat != null && this.slugcat.animation == Player.AnimationIndex.HangUnderVerticalBeam && this.animation.idx != WolfAnimation.AnimationIndex.HangFromBeam && this.animation.idx != WolfAnimation.AnimationIndex.ClimbOnBeam && this.room.GetTile(base.bodyChunks[0].pos + new Vector2(0f, 20f)).verticalBeam && !this.room.GetTile(base.bodyChunks[0].pos).verticalBeam && this.animation.idx != Wolf.WolfAnimation.AnimationIndex.HangUnderVerticalBeam) { base.bodyChunks[0].pos = this.room.MiddleOfTile(base.bodyChunks[0].pos) + new Vector2(0f, 5f); base.bodyChunks[0].vel *= 0f; base.bodyChunks[1].vel = Vector2.ClampMagnitude(base.bodyChunks[1].vel, 9f); this.animation = new MovementAnimation(this, Wolf.WolfAnimation.AnimationIndex.HangUnderVerticalBeam); } } bool flag7 = false; if (this.bodyMode != BodyModeIndex.CorridorClimb) { flag7 = true; } if (this.animation.idx == Wolf.WolfAnimation.AnimationIndex.ClimbOnBeam || this.animation.idx == Wolf.WolfAnimation.AnimationIndex.HangFromBeam || this.animation.idx == Wolf.WolfAnimation.AnimationIndex.GetUpOnBeam || this.animation.idx == Wolf.WolfAnimation.AnimationIndex.LedgeGrab) { flag7 = false; } if (base.grasps[0] != null && this.HeavyCarry(base.grasps[0].grabbed)) { float num9 = 1f + Mathf.Max(0f, base.grasps[0].grabbed.TotalMass - 0.2f); if (this.Grabability(base.grasps[0].grabbed) == Wolf.ObjectGrabability.Drag) { if (this.bodyMode == BodyModeIndex.Default || this.bodyMode == BodyModeIndex.CorridorClimb || this.bodyMode == BodyModeIndex.Stand || this.bodyMode == BodyModeIndex.Crawl) { num9 = 1f; } if (this.room.aimap.getAItile(base.mainBodyChunk.pos).narrowSpace) { base.grasps[0].grabbedChunk.vel += this.movement.normalized * 1.05f * 4f * this.MovementSpeed / Mathf.Max(0.75f, base.grasps[0].grabbed.TotalMass); } for (int n = 0; n < base.grasps[0].grabbed.bodyChunks.Length; n++) { if (this.room.aimap.getAItile(base.grasps[0].grabbed.bodyChunks[n].pos).narrowSpace) { base.grasps[0].grabbed.bodyChunks[n].vel *= 0.8f; base.grasps[0].grabbed.bodyChunks[n].vel.y += this.room.gravity * base.grasps[0].grabbed.gravity * 0.85f; base.grasps[0].grabbed.bodyChunks[n].vel += this.movement.normalized * 1.05f * 1.5f * this.MovementSpeed / ((float)base.grasps[0].grabbed.bodyChunks.Length * Mathf.Max(1f, (base.grasps[0].grabbed.TotalMass + 1f) / 2f)); base.grasps[0].grabbed.bodyChunks[n].pos += this.movement.normalized * 1.05f * 1.1f * this.MovementSpeed / ((float)base.grasps[0].grabbed.bodyChunks.Length * Mathf.Max(1f, (base.grasps[0].grabbed.TotalMass + 2f) / 3f)); } } } if (this.shortcutDelay < 1 && this.enteringShortCut == null && (this.movement.x == 0 || this.movement.y == 0) && (this.movement.x != 0 || this.movement.y != 0)) { for (int num10 = 0; num10 < base.grasps[0].grabbed.bodyChunks.Length; num10++) { if (this.room.GetTile(this.room.GetTilePosition(base.grasps[0].grabbed.bodyChunks[num10].pos) + new IntVector2((int)Mathf.Sign(this.movement.x), (int)Mathf.Sign(this.movement.y))).Terrain == Room.Tile.TerrainType.ShortcutEntrance && this.room.ShorcutEntranceHoleDirection(this.room.GetTilePosition(base.grasps[0].grabbed.bodyChunks[num10].pos) + new IntVector2((int)Mathf.Sign(this.movement.x), (int)Mathf.Sign(this.movement.y))) == new IntVector2(-(int)Mathf.Sign(this.movement.x), -(int)Mathf.Sign(this.movement.y))) { ShortcutData.Type shortCutType = this.room.shortcutData(this.room.GetTilePosition(base.grasps[0].grabbed.bodyChunks[num10].pos) + new IntVector2((int)Mathf.Sign(this.movement.x), (int)Mathf.Sign(this.movement.y))).shortCutType; if (shortCutType == ShortcutData.Type.RoomExit || shortCutType == ShortcutData.Type.Normal) { this.enteringShortCut = new IntVector2?(this.room.GetTilePosition(base.grasps[0].grabbed.bodyChunks[num10].pos) + new IntVector2((int)Mathf.Sign(this.movement.x), (int)Mathf.Sign(this.movement.y))); Debug.Log("wolf pulled into shortcut by carried object"); break; } } } } this.dynamicRunSpeed[0] /= num9; this.dynamicRunSpeed[1] /= num9; } if (flag7 && (this.dynamicRunSpeed[0] > 0f || this.dynamicRunSpeed[1] > 0f)) { if (this.slowMovementStun > 0) { this.dynamicRunSpeed[0] *= 0.5f + 0.5f * Mathf.InverseLerp(10f, 0f, (float)this.slowMovementStun); this.dynamicRunSpeed[1] *= 0.5f + 0.5f * Mathf.InverseLerp(10f, 0f, (float)this.slowMovementStun); friction *= 0.4f + 0.6f * Mathf.InverseLerp(10f, 0f, (float)this.slowMovementStun); } if (this.bodyMode == BodyModeIndex.Default && base.bodyChunks[0].ContactPoint.x == 0 && base.bodyChunks[0].ContactPoint.y == 0 && base.bodyChunks[1].ContactPoint.x == 0 && base.bodyChunks[1].ContactPoint.y == 0) { friction *= this.room.gravity; } for (int i = 0; i < 2; i++) { if (dir < 0) { float friction0 = friction * this.surfaceFriction; if (base.bodyChunks[i].vel.x - friction0 < -this.dynamicRunSpeed[i]) { friction0 = this.dynamicRunSpeed[i] + base.bodyChunks[i].vel.x; } if (friction0 > 0f) { base.bodyChunks[i].vel.x -= friction0; } } else if (dir > 0) { float friction1 = friction * this.surfaceFriction; if (base.bodyChunks[i].vel.x + friction1 > this.dynamicRunSpeed[i]) { friction1 = this.dynamicRunSpeed[i] - base.bodyChunks[i].vel.x; } if (friction1 > 0f) { base.bodyChunks[i].vel.x += friction1; } } if (base.bodyChunks[0].ContactPoint.y != 0 || base.bodyChunks[1].ContactPoint.y != 0) { float num14 = 0f; if (this.movement.x != 0) { num14 = Mathf.Clamp(base.bodyChunks[i].vel.x, -this.dynamicRunSpeed[i], this.dynamicRunSpeed[i]); } base.bodyChunks[i].vel.x += (num14 - base.bodyChunks[i].vel.x) * Mathf.Pow(this.surfaceFriction, 1.5f); } } } if (this.commitedToMove != null && this.shortcutDelay < 1 && (this.commitedToMove.type == MovementConnection.MovementType.ShortCut || this.commitedToMove.type == MovementConnection.MovementType.NPCTransportation || (this.commitedToMove.type == MovementConnection.MovementType.RegionTransportation))) { this.enteringShortCut = new IntVector2?(this.commitedToMove.StartTile); if (this.commitedToMove.type == MovementConnection.MovementType.NPCTransportation) { this.NPCTransportationDestination = this.commitedToMove.destinationCoord; } else if (this.room.shortcutData(this.commitedToMove.StartTile).shortCutType == ShortcutData.Type.RegionTransportation) { this.NPCTransportationDestination = this.AI.pathFinder.BestRegionTransportationGoal(); } this.shortcutDelay = 100; return; } //Additional for Wolf if (this.commitedToMove != null) { if (this.movement.y == 0 && this.bodyMode == BodyModeIndex.ClimbingOnBeam) { if (this.room.GetTile(this.bodyChunks[1].pos).horizontalBeam && this.animation.idx != Wolf.WolfAnimation.AnimationIndex.StandOnBeam) { this.animation = new MovementAnimation(this, Wolf.WolfAnimation.AnimationIndex.StandOnBeam); } else if (this.room.GetTile(this.mainBodyChunk.pos).horizontalBeam && this.animation.idx != Wolf.WolfAnimation.AnimationIndex.HangFromBeam) { this.animation = new MovementAnimation(this, Wolf.WolfAnimation.AnimationIndex.HangFromBeam); } else if (this.room.GetTile(this.bodyChunks[1].pos + new Vector2(0f, -30f)).Solid || this.room.GetTile(this.bodyChunks[1].pos + new Vector2(0f, -30f)).AnyWater) { this.bodyMode = Wolf.BodyModeIndex.Default; this.animation = new BlankAnimation(this); } else if (this.room.GetTile(this.bodyChunks[1].pos + new Vector2(Mathf.Sign(this.movement.x) * 40f, -30f)).Solid) { //Jump off this.bodyMode = Wolf.BodyModeIndex.Default; this.animation = new BlankAnimation(this); this.AerobicIncrease(1f); base.bodyChunks[0].vel.y = 8f; base.bodyChunks[1].vel.y = 7f; base.bodyChunks[0].vel.x = 6f * this.flipDirection * 0.7f; base.bodyChunks[1].vel.x = 5f * this.flipDirection * 0.7f; this.room.PlaySound(SoundID.Slugcat_From_Vertical_Pole_Jump, base.mainBodyChunk, false, 1f, 1.1f); } } if (this.bodyMode != BodyModeIndex.Default && this.room.gravity > 0f && this.movement.y > 0f) { if (this.connections.Count > 2) { Vector2 xdir = this.room.MiddleOfTile(this.connections[1].DestTile) - this.room.MiddleOfTile(this.connections[1].StartTile); if (this.IsTileSolid(1, (int)Mathf.Sign(xdir.x), 0)) // && this.bodyChunks[1].onSlope != 0 { this.bodyMode = Wolf.BodyModeIndex.Default; this.animation = new BlankAnimation(this); this.AerobicIncrease(1f); base.bodyChunks[0].vel.y = 8f; base.bodyChunks[1].vel.y = 7f; base.bodyChunks[0].vel.x = 5f * Mathf.Sign(xdir.x); base.bodyChunks[1].vel.x = 4f * Mathf.Sign(xdir.x); this.room.PlaySound(SoundID.Slugcat_Normal_Jump, base.bodyChunks[1], false, 0.8f, 1.1f); } } } } //this.GrabUpdate(eu); } private int goIntoCorridorClimb; public int vineGrabDelay; public int wantToGrab; private void DirectIntoHoles() { for (int i = 0; i < 4; i++) { if (this.room.GetTile(base.mainBodyChunk.pos + Custom.fourDirections[i].ToVector2() * 20f).Solid) { return; } } if (((this.movement.x != 0 && this.movement.y == 0) || (this.movement.y != 0 && this.movement.x == 0)) && !this.room.GetTile(base.mainBodyChunk.pos + new Vector2(20f * Mathf.Sign(this.movement.x), 20f * Mathf.Sign(this.movement.y))).Solid && ((this.room.GetTile(base.mainBodyChunk.pos + new Vector2(20f * Mathf.Sign(this.movement.x), 20f * Mathf.Sign(this.movement.y)) + new Vector2(-20f, 0f)).Solid && this.room.GetTile(base.mainBodyChunk.pos + new Vector2(20f * Mathf.Sign(this.movement.x), 20f * Mathf.Sign(this.movement.y)) + new Vector2(20f, 0f)).Solid) || (this.room.GetTile(base.mainBodyChunk.pos + new Vector2(20f * Mathf.Sign(this.movement.x), 20f * Mathf.Sign(this.movement.y)) + new Vector2(0f, -20f)).Solid && this.room.GetTile(base.mainBodyChunk.pos + new Vector2(20f * Mathf.Sign(this.movement.x), 20f * Mathf.Sign(this.movement.y)) + new Vector2(0f, 20f)).Solid))) { if (this.room.GetTile(base.mainBodyChunk.pos + new Vector2(40f * Mathf.Sign(this.movement.x), 40f * Mathf.Sign(this.movement.y))).Terrain == Room.Tile.TerrainType.ShortcutEntrance) { ShortcutData.Type shortCutType = this.room.shortcutData(this.room.GetTilePosition(base.mainBodyChunk.pos + new Vector2(40f * Mathf.Sign(this.movement.x), 40f * Mathf.Sign(this.movement.y)))).shortCutType; if (shortCutType != ShortcutData.Type.Normal && shortCutType != ShortcutData.Type.RoomExit) { return; } } base.mainBodyChunk.vel += (this.room.MiddleOfTile(base.mainBodyChunk.pos + new Vector2(20f * Mathf.Sign(this.movement.x), 20f * Mathf.Sign(this.movement.y))) - base.mainBodyChunk.pos) / 10f; } } private void GrabVerticalPole() { IntVector2 tilePosition = this.room.GetTilePosition(base.mainBodyChunk.pos); bool flag = base.bodyChunks[1].ContactPoint.y < 0 && this.movement.x == 0; for (int i = 0; i < ((!flag) ? 1 : 3); i++) { int num = (i <= 0) ? 0 : ((i != 1) ? 1 : -1); if (this.room.GetTile(tilePosition + new IntVector2(num, 0)).verticalBeam && this.animation.idx != Wolf.WolfAnimation.AnimationIndex.ClimbOnBeam) { IntVector2 pos = tilePosition + new IntVector2(num, 0); this.room.PlaySound(SoundID.Slugcat_Grab_Beam, base.mainBodyChunk, false, 0.8f, 1.1f); this.animation = new MovementAnimation(this, Wolf.WolfAnimation.AnimationIndex.ClimbOnBeam); if (num == 0 && Mathf.Abs(base.bodyChunks[0].vel.x) > 5f) { if (base.bodyChunks[0].vel.x < 0f) { this.flipDirection = -1; } else { this.flipDirection = 1; } } else if (base.bodyChunks[0].pos.x < this.room.MiddleOfTile(pos).x) { this.flipDirection = -1; } else { this.flipDirection = 1; } base.bodyChunks[0].vel = new Vector2(0f, 0f); base.bodyChunks[0].pos.x = this.room.MiddleOfTile(pos).x; } } } private void GravitateToOpening() { if (this.movement.x != 0 && this.movement.y == 0) { if (!base.IsTileSolid(0, (int)Mathf.Sign(this.movement.x), 0) && base.IsTileSolid(0, (int)Mathf.Sign(this.movement.x), 1) && base.IsTileSolid(0, (int)Mathf.Sign(this.movement.x), -1) && (!base.IsTileSolid(0, 0, 1) || !base.IsTileSolid(0, 0, -1))) { Vector2 vector = this.room.MiddleOfTile(this.room.GetTilePosition(base.bodyChunks[0].pos) + new IntVector2((int)Mathf.Sign(this.movement.x), 0)); int num = -1; float dst = float.MaxValue; for (int i = 0; i < 2; i++) { if (Custom.DistLess(base.bodyChunks[i].pos, vector, dst)) { num = i; dst = Vector2.Distance(base.bodyChunks[i].pos, vector); } } base.bodyChunks[num].vel += Custom.DirVec(base.bodyChunks[num].pos, vector) * Mathf.Lerp(0.5f, 1f, this.room.gravity); for (int j = 0; j < 2; j++) { base.bodyChunks[j].vel.y -= (base.bodyChunks[j].pos.y - this.room.MiddleOfTile(base.bodyChunks[j].pos).y) * Mathf.Lerp(0.01f, 0.1f, this.room.gravity); base.bodyChunks[j].vel = Vector2.Lerp(base.bodyChunks[j].vel, Vector2.ClampMagnitude(base.bodyChunks[j].vel, 2f), 0.5f); } } } else if (this.movement.y != 0 && this.movement.x == 0 && !base.IsTileSolid(0, 0, (int)Mathf.Sign(this.movement.y)) && base.IsTileSolid(0, 1, (int)Mathf.Sign(this.movement.y)) && base.IsTileSolid(0, -1, (int)Mathf.Sign(this.movement.y)) && (!base.IsTileSolid(0, 1, 0) || !base.IsTileSolid(0, -1, 0))) { Vector2 vector2 = this.room.MiddleOfTile(this.room.GetTilePosition(base.bodyChunks[0].pos) + new IntVector2(0, (int)Mathf.Sign(this.movement.y))); int num2 = -1; float dst2 = float.MaxValue; for (int k = 0; k < 2; k++) { if (Custom.DistLess(base.bodyChunks[k].pos, vector2, dst2)) { num2 = k; dst2 = Vector2.Distance(base.bodyChunks[k].pos, vector2); } } base.bodyChunks[num2].vel += Custom.DirVec(base.bodyChunks[num2].pos, vector2) * Mathf.Lerp(0.5f, 1f, this.room.gravity); for (int l = 0; l < 2; l++) { base.bodyChunks[l].vel.x -= (base.bodyChunks[l].pos.x - this.room.MiddleOfTile(base.bodyChunks[l].pos).x) * Mathf.Lerp(0.01f, 0.1f, this.room.gravity); base.bodyChunks[l].vel = Vector2.Lerp(base.bodyChunks[l].vel, Vector2.ClampMagnitude(base.bodyChunks[l].vel, 2f), 0.5f); } } } public override void ReleaseGrasp(int grasp) { if (base.grasps[grasp] != null && this.room != null) { this.room.PlaySound(SoundID.Slugcat_Lose_Grasp, base.mainBodyChunk, false, 1f, 1.1f); } base.ReleaseGrasp(grasp); } private MovementConnection FollowPath(WorldCoordinate origin, bool actuallyFollowingThisPath) { if (this.pathingWithExits) { return this.AI.pathFinder.PathWithExits(origin, false); } return (this.AI.pathFinder as StandardPather).FollowPath(origin, actuallyFollowingThisPath); } private bool SwimTile(IntVector2 tl) { return this.room.GetTile(tl).DeepWater || (this.room.GetTile(tl).AnyWater && !this.room.GetTile(tl + new IntVector2(0, -1)).Solid); } private void GetUnstuckRoutine() { if (this.ReallyStuck > 0.1f && this.ReallyStuck < 0.9f && this.connections.Count < 3) { this.LookForAndMoveToUnstuckTile(); } if (this.pathingWithExits) { if (this.pathWithExitsCounter < 0) { this.pathWithExitsCounter++; } if ((this.pathWithExitsCounter > -1 && this.stuckCounter == 0) || this.ReallyStuck >= 1f) { this.pathingWithExits = false; this.pathWithExitsCounter = 200; } } else if (this.ReallyStuck > 0.5f && this.pathWithExitsCounter < 1) { this.pathingWithExits = true; this.pathWithExitsCounter = -50; this.AI.pathFinder.InitiAccessibilityMapping(this.room.GetWorldCoordinate(this.occupyTile), null); } else if (this.pathWithExitsCounter > 0) { this.pathWithExitsCounter--; } if (this.ReallyStuck > 0.2f) { ShortcutData? shortcutData = default(ShortcutData?); int num = 0; while (num < 3 && shortcutData == null) { int num2 = 0; while (num2 < 9 && shortcutData == null) { if (this.room.GetTile(this.room.GetTilePosition(base.bodyChunks[num].pos) + Custom.eightDirectionsAndZero[num2]).Terrain == Room.Tile.TerrainType.ShortcutEntrance) { shortcutData = new ShortcutData?(this.room.shortcutData(this.room.GetTilePosition(base.bodyChunks[num].pos) + Custom.eightDirectionsAndZero[num2])); } num2++; } num++; } if (shortcutData != null) { this.stuckOnShortcutCounter = Math.Min(this.stuckOnShortcutCounter + 1, 100); if (this.stuckOnShortcutCounter > 25) { for (int i = 0; i < base.bodyChunks.Length; i++) { base.bodyChunks[i].vel += this.room.ShorcutEntranceHoleDirection(shortcutData.Value.StartTile).ToVector2() * 7f + Custom.RNV() * UnityEngine.Random.value * 5f; } } } } else if (this.stuckOnShortcutCounter > 0) { this.stuckOnShortcutCounter--; } if (this.stuckOnShortcutCounter > 25) { for (int j = 0; j < base.bodyChunks.Length; j++) { base.bodyChunks[j].vel += Custom.RNV() * 6f * UnityEngine.Random.value; } } } private void LookForAndMoveToUnstuckTile() { IntVector2 pos = this.room.GetTilePosition(base.mainBodyChunk.pos); int num = 0; for (int i = 0; i < 2; i++) { for (int j = 0; j < 8; j++) { if (this.room.aimap.TileAccessibleToCreature(this.room.GetTilePosition(base.bodyChunks[i].pos) + Custom.eightDirections[j], base.Template)) { IntVector2 intVector = this.room.GetTilePosition(base.bodyChunks[i].pos) + Custom.eightDirections[j]; MovementConnection movementConnection = this.FollowPath(this.room.GetWorldCoordinate(intVector), true); List<MovementConnection> list = new List<MovementConnection>(); if (movementConnection != null) { for (int k = 0; k < 15; k++) { list.Add(movementConnection); movementConnection = this.FollowPath(movementConnection.destinationCoord, false); int num2 = 0; while (num2 < list.Count && movementConnection != null) { if (list[num2].destinationCoord == movementConnection.destinationCoord) { movementConnection = null; } num2++; } if (movementConnection == null) { break; } } } if (list.Count > num) { num = list.Count; pos = intVector; } } } } if (num > 2) { for (int l = 0; l < base.bodyChunks.Length; l++) { base.bodyChunks[l].vel += Custom.DirVec(base.mainBodyChunk.pos, this.room.MiddleOfTile(pos)) * (1f + this.ReallyStuck * UnityEngine.Random.value); } } } public void Blink(int blink) { if (base.graphicsModule == null) { return; } if ((base.graphicsModule as WolfGraphics).blink < blink) { (base.graphicsModule as WolfGraphics).blink = blink; } } public float airInLungs; public bool lungsExhausted; private void LungUpdate() { this.airInLungs = Mathf.Min(this.airInLungs, 1f - this.rainDeath); if (base.firstChunk.submersion > 0.9f && !this.room.game.setupValues.invincibility) { if (!this.submerged) { this.swimForce = Mathf.InverseLerp(0f, 8f, Mathf.Abs(base.firstChunk.vel.x)); this.swimCycle = 0f; } float num = this.airInLungs; this.airInLungs -= 1f / (40f * ((!this.lungsExhausted) ? 9f : 4.5f) * ((this.moving || this.airInLungs >= 0.333333343f) ? 1f : 1.5f) * ((float)this.room.game.setupValues.lungs / 100f)) * 2f; if (this.movement.x != 0 || this.airInLungs < 0.6666667f && num >= 0.6666667f) { this.room.AddObject(new Bubble(base.firstChunk.pos, base.firstChunk.vel, false, false)); } bool flag = this.airInLungs <= 0f && this.room.FloatWaterLevel(base.mainBodyChunk.pos.x) - base.mainBodyChunk.pos.y < 200f; if (flag) { for (int i = this.room.GetTilePosition(base.mainBodyChunk.pos).y; i <= this.room.defaultWaterLevel; i++) { if (this.room.GetTile(this.room.GetTilePosition(base.mainBodyChunk.pos).x, i).Solid) { flag = false; break; } } } if (this.airInLungs <= ((!flag) ? 0f : -0.3f) && base.mainBodyChunk.submersion == 1f && base.bodyChunks[1].submersion > 0.5f) { this.airInLungs = 0f; this.Stun(80); this.drown += 0.002f; //You can save if (this.drown >= 1f) { this.Die(); } } else if (this.airInLungs < 0.333333343f) { if (this.slowMovementStun < 1) { this.slowMovementStun = 1; } if (UnityEngine.Random.value < 0.5f) { base.firstChunk.vel += Custom.DegToVec(UnityEngine.Random.value * 360f) * UnityEngine.Random.value; } if (this.movement.y < 1) { base.bodyChunks[1].vel *= Mathf.Lerp(1f, 0.9f, Mathf.InverseLerp(0f, 0.333333343f, this.airInLungs)); } if ((UnityEngine.Random.value > this.airInLungs * 2f || this.lungsExhausted) && UnityEngine.Random.value > 0.5f) { this.room.AddObject(new Bubble(base.firstChunk.pos, base.firstChunk.vel + Custom.DegToVec(UnityEngine.Random.value * 360f) * Mathf.Lerp(6f, 0f, this.airInLungs), false, false)); } } this.submerged = true; } else { if (this.submerged && this.airInLungs < 0.333333343f) { this.lungsExhausted = true; } if (!this.lungsExhausted && this.airInLungs > 0.9f) { this.airInLungs = 1f; } if (this.airInLungs <= 0f) { this.airInLungs = 0f; } this.airInLungs += 1f / (float)((!this.lungsExhausted) ? 60 : 240); if (this.airInLungs >= 1f) { this.airInLungs = 1f; this.lungsExhausted = false; this.drown = 0f; } this.submerged = false; if (this.lungsExhausted && this.animation.idx != Wolf.WolfAnimation.AnimationIndex.SurfaceSwim) { this.swimCycle += 0.1f; } } if (this.lungsExhausted) { if (this.slowMovementStun < 5) { this.slowMovementStun = 5; } if (this.drown > 0f && this.slowMovementStun < 10) { this.slowMovementStun = 10; } } } public override void GraphicsModuleUpdated(bool actuallyViewed, bool eu) { for (int i = 0; i < 2; i++) { if (base.grasps[i] != null) { if (this.HeavyCarry(base.grasps[i].grabbed)) { Vector2 a = Custom.DirVec(base.mainBodyChunk.pos, base.grasps[i].grabbedChunk.pos); float num = Vector2.Distance(base.mainBodyChunk.pos, base.grasps[i].grabbedChunk.pos); float num2 = 5f + base.grasps[i].grabbedChunk.rad; if (base.grasps[i].grabbed is Cicada) { num2 = 30f; } num2 *= 25f; float num3 = base.grasps[i].grabbedChunk.mass / (base.mainBodyChunk.mass + base.grasps[i].grabbedChunk.mass); if (this.enteringShortCut != null) { num3 = 0f; } else if (base.grasps[i].grabbed.TotalMass < base.TotalMass) { num3 /= 2f; } if (this.enteringShortCut == null || num > num2) { base.mainBodyChunk.pos += a * (num - num2) * num3; base.mainBodyChunk.vel += a * (num - num2) * num3; base.grasps[i].grabbedChunk.pos -= a * (num - num2) * (1f - num3); base.grasps[i].grabbedChunk.vel -= a * (num - num2) * (1f - num3); } if (this.bodyMode == Wolf.BodyModeIndex.ClimbingOnBeam && this.animation.idx != Wolf.WolfAnimation.AnimationIndex.BeamTip && this.animation.idx != Wolf.WolfAnimation.AnimationIndex.StandOnBeam) { base.grasps[i].grabbedChunk.vel.y += base.grasps[i].grabbed.gravity * (1f - base.grasps[i].grabbedChunk.submersion) * 0.75f; } if (this.Grabability(base.grasps[i].grabbed) == Wolf.ObjectGrabability.Drag && num > num2 * 2f + 30f) { this.ReleaseGrasp(i); } } else if (actuallyViewed) { base.grasps[i].grabbed.firstChunk.vel = (base.graphicsModule as PlayerGraphics).hands[i].vel; base.grasps[i].grabbed.firstChunk.MoveFromOutsideMyUpdate(eu, (base.graphicsModule as PlayerGraphics).hands[i].pos); if (base.grasps[i].grabbed is Weapon) { Vector2 vector = Custom.DirVec(base.mainBodyChunk.pos, base.grasps[i].grabbed.bodyChunks[0].pos) * ((i != 0) ? 1f : -1f); if (this.animation.idx != Wolf.WolfAnimation.AnimationIndex.HangFromBeam) { vector = Custom.PerpendicularVector(vector); } if (this.bodyMode == Wolf.BodyModeIndex.Crawl) { vector = Custom.DirVec(base.bodyChunks[1].pos, Vector2.Lerp(base.grasps[i].grabbed.bodyChunks[0].pos, base.bodyChunks[0].pos, 0.8f)); } else if (this.animation.idx != Wolf.WolfAnimation.AnimationIndex.ClimbOnBeam) { vector.y = Mathf.Abs(vector.y); vector = Vector3.Slerp(vector, Custom.DirVec(base.bodyChunks[1].pos, base.bodyChunks[0].pos), 0.75f); } else if (base.grasps[i].grabbed is Spear) { vector = Vector3.Slerp(vector, Custom.DegToVec((80f + Mathf.Cos((float)(this.animation.animationFrame + ((!this.leftFoot) ? 3 : 9)) / 12f * 2f * 3.14159274f) * 4f * (base.graphicsModule as PlayerGraphics).spearDir) * (base.graphicsModule as PlayerGraphics).spearDir), Mathf.Abs((base.graphicsModule as PlayerGraphics).spearDir)); } (base.grasps[i].grabbed as Weapon).setRotation = new Vector2?(vector); (base.grasps[i].grabbed as Weapon).rotationSpeed = 0f; } } else { base.grasps[i].grabbed.firstChunk.pos = base.bodyChunks[0].pos; base.grasps[i].grabbed.firstChunk.vel = base.mainBodyChunk.vel; } } } } public override void Grabbed(Creature.Grasp grasp) { base.Grabbed(grasp); } public override void Violence(BodyChunk source, Vector2? directionAndMomentum, BodyChunk hitChunk, PhysicalObject.Appendage.Pos hitAppendage, Creature.DamageType type, float damage, float stunBonus) { base.Violence(source, directionAndMomentum, hitChunk, hitAppendage, type, damage, stunBonus); } public override void TerrainImpact(int chunk, IntVector2 direction, float speed, bool firstContact) { if (base.graphicsModule != null && speed > 12f) { } base.TerrainImpact(chunk, direction, speed, firstContact); } public override void Die() { Room room = this.room; if (room == null) { room = base.abstractCreature.world.GetAbstractRoom(base.abstractCreature.pos).realizedRoom; } if (room != null) { if (room.game.setupValues.invincibility) { return; } if (!base.dead) { //room.PlaySound(SoundID.UI_Slugcat_Die, base.mainBodyChunk); room.PlaySound(SoundID.HUD_Game_Over_Prompt, 0f, 0.5f, 1.1f); } } base.Die(); } public override Color ShortCutColor() { return this.color; } public Wolf.WolfAnimation animation; public Wolf.BodyModeIndex bodyMode; private int ledgeGrabCounter; public WolfAI AI; public IRainbowState rainbowState => this.State as IRainbowState; public bool Malnourished => this.rainbowState.malnourished; public override float VisibilityBonus { get { return darknessBonus - (1f - this.AI.DecideSneak()); } } public float darknessBonus = 0f; public abstract class WolfAnimation { protected WolfAnimation(Wolf wolf, Wolf.WolfAnimation.AnimationIndex idx) { this.idx = idx; this.wolf = wolf; this.animationFrame = 0; } public virtual bool Continue { get { return true; } } public virtual bool Active { get { return true; } } public virtual void Update() { this.age++; } public Wolf wolf; public Wolf.WolfAnimation.AnimationIndex idx; public int age; public int animationFrame; public enum AnimationIndex { None, CrawlTurn, StandUp, DownOnFours, LedgeCrawl, LedgeGrab, HangFromBeam, GetUpOnBeam, StandOnBeam, ClimbOnBeam, GetUpToBeamTip, HangUnderVerticalBeam, BeamTip, CorridorTurn, SurfaceSwim, DeepSwim, Flip, Dance, //RocketJump, BellySlide, Charm, // Stab, //GrapplingSwing, // ZeroGSwim, ZeroGPoleGrab, Hungry, // VineGrab, Play, GeneralPoint, Eat, Dead } } public class DeadAnimation : WolfAnimation { public DeadAnimation(Wolf wolf) : base(wolf, AnimationIndex.Dead) { } public override void Update() { base.Update(); this.wolf.bodyMode = BodyModeIndex.Dead; } } public class BlankAnimation : WolfAnimation { public BlankAnimation(Wolf wolf) : base(wolf, Wolf.WolfAnimation.AnimationIndex.None) { } } public class EatAnimation : WolfAnimation { public EatAnimation(Wolf wolf) : base(wolf, Wolf.WolfAnimation.AnimationIndex.Eat) { } } private bool straightUpOnHorizontalBeam; private Vector2 upOnHorizontalBeamPos; private IntVector2? corridorTurnDir; private float swimForce; public int slideDirection; public class MovementAnimation : WolfAnimation { public MovementAnimation(Wolf wolf, AnimationIndex idx) : base(wolf, idx) { this.stop = false; this.slideUpPole = 0; this.corridorTurnCounter = 0; } public bool stop; public int slideUpPole; public int corridorTurnCounter; public bool flipFromSlide; public float circuitSwimResistance; public float curcuitJumpMeter; public IntVector2 zeroGPoleGrabDir; public ClimbableVinesSystem.VinePosition vinePos; public Vector2 vineClimbCursor; public int vineGrabDelay; public override void Update() { base.Update(); switch (this.idx) { case AnimationIndex.CrawlTurn: this.wolf.bodyMode = Wolf.BodyModeIndex.Default; this.wolf.bodyChunks[0].vel.x += (float)this.wolf.flipDirection; this.wolf.bodyChunks[1].vel.x -= 2f * (float)this.wolf.flipDirection; if (this.wolf.movement.x > 0 != this.wolf.bodyChunks[0].pos.x < this.wolf.bodyChunks[1].pos.x) { BodyChunk bodyChunk3 = this.wolf.bodyChunks[0]; bodyChunk3.vel.y -= 3f; if (this.wolf.bodyChunks[0].pos.y < this.wolf.bodyChunks[1].pos.y + 2f) { this.wolf.animation = new BlankAnimation(this.wolf); this.wolf.bodyChunks[0].vel.y -= 1f; } } else { this.wolf.bodyChunks[0].vel.y += 2f; } if (this.wolf.movement.x == 0 || this.wolf.IsTileSolid(1, 0, 1)) { this.wolf.animation = new BlankAnimation(this.wolf); } break; case AnimationIndex.StandUp: if (this.wolf.standing) { this.wolf.bodyChunks[0].vel.x *= 0.7f; if (!this.wolf.IsTileSolid(0, 0, 1) && this.wolf.bodyChunks[1].onSlope == 0) { this.wolf.bodyMode = Wolf.BodyModeIndex.Stand; if (this.wolf.bodyChunks[0].pos.y > this.wolf.bodyChunks[1].pos.y + 3f) { this.wolf.animation = new BlankAnimation(this.wolf); this.wolf.room.PlaySound(SoundID.Slugcat_Regain_Footing, this.wolf.bodyChunks[1], false, 0.8f, 1.1f); } } else { this.wolf.animation = new BlankAnimation(this.wolf); } } else { this.wolf.animation = new MovementAnimation(this.wolf, AnimationIndex.DownOnFours); } break; case AnimationIndex.DownOnFours: if (!this.wolf.standing) { this.wolf.bodyChunks[0].vel.y -= 2f; this.wolf.bodyChunks[0].vel.x += (float)this.wolf.flipDirection; this.wolf.bodyChunks[1].vel.x -= (float)this.wolf.flipDirection; if (this.wolf.bodyChunks[0].pos.y < this.wolf.bodyChunks[1].pos.y || this.wolf.bodyChunks[0].ContactPoint.y == -1) { this.wolf.animation = new BlankAnimation(this.wolf); } } else { this.wolf.animation = new MovementAnimation(this.wolf, AnimationIndex.StandUp); } break; case AnimationIndex.LedgeCrawl: this.wolf.bodyChunks[0].vel.x += (float)this.wolf.flipDirection * 2f; this.wolf.bodyMode = BodyModeIndex.Crawl; if (!this.wolf.IsTileSolid(0, this.wolf.flipDirection, 0)) { if ((this.wolf.IsTileSolid(0, 0, -1) && this.wolf.IsTileSolid(1, 0, -1) && this.wolf.room.GetTilePosition(this.wolf.bodyChunks[0].pos).y == this.wolf.room.GetTilePosition(this.wolf.bodyChunks[0].pos).y) || (this.wolf.bodyChunks[0].ContactPoint.x == this.wolf.flipDirection && this.wolf.movement.x != 0) || (this.wolf.bodyChunks[0].ContactPoint.y > -1 && this.wolf.bodyChunks[1].ContactPoint.y > -1)) { this.wolf.animation = new BlankAnimation(this.wolf); } } break; case AnimationIndex.LedgeGrab: this.wolf.bodyMode = BodyModeIndex.Default; if (this.wolf.IsTileSolid(0, this.wolf.flipDirection, 0) && !this.wolf.IsTileSolid(0, this.wolf.flipDirection, 1)) { this.wolf.bodyChunks[0].vel *= 0.5f; this.wolf.bodyChunks[0].pos = (this.wolf.bodyChunks[0].pos + (this.wolf.room.MiddleOfTile(this.wolf.room.GetTilePosition(this.wolf.bodyChunks[0].pos)) + new Vector2((float)this.wolf.flipDirection * (float)this.wolf.ledgeGrabCounter, 8f + (float)this.wolf.ledgeGrabCounter))) / 2f; this.wolf.bodyChunks[0].lastPos = this.wolf.bodyChunks[0].pos; this.wolf.bodyChunks[1].vel.x += (float)this.wolf.flipDirection; //this.wolf.canJump = 1; if ((int)Mathf.Sign(this.wolf.movement.x) == this.wolf.flipDirection || this.wolf.movement.y > 0) { this.wolf.ledgeGrabCounter++; this.wolf.bodyChunks[1].vel += new Vector2(-0.5f * (float)this.wolf.flipDirection, -0.5f); } else if (this.wolf.ledgeGrabCounter > 0) { this.wolf.ledgeGrabCounter--; } if (this.wolf.movement.y < 0) { this.wolf.bodyChunks[0].pos.y -= 10f; this.wolf.animation = new BlankAnimation(this.wolf); this.wolf.ledgeGrabCounter = 0; } else if ((int)Mathf.Sign(this.wolf.movement.x) == -this.wolf.flipDirection) { this.wolf.bodyChunks[0].vel.y += 10f; this.wolf.animation = new BlankAnimation(this.wolf); } this.wolf.standing = true; } else { this.wolf.animation = new BlankAnimation(this.wolf); } break; case AnimationIndex.HangFromBeam: this.wolf.bodyMode = BodyModeIndex.ClimbingOnBeam; this.wolf.standing = true; this.wolf.bodyChunks[0].vel.y = 0f; this.wolf.bodyChunks[0].vel.x *= 0.2f; this.wolf.bodyChunks[0].pos.y = this.wolf.room.MiddleOfTile(this.wolf.bodyChunks[0].pos).y; if (this.wolf.movement.x != 0 && this.wolf.bodyChunks[0].ContactPoint.x != (int)Mathf.Sign(this.wolf.movement.x)) { if (this.wolf.bodyChunks[1].ContactPoint.x != (int)Mathf.Sign(this.wolf.movement.x)) { this.wolf.bodyChunks[0].vel.x += this.wolf.movement.x * 1.2f * 1.2f * this.wolf.MovementSpeed * Custom.LerpMap((float)this.wolf.slowMovementStun, 0f, 10f, 1f, 0.5f); } this.animationFrame++; if (this.animationFrame > 20) { this.animationFrame = 1; this.wolf.room.PlaySound(SoundID.Slugcat_Climb_Along_Horizontal_Beam, this.wolf.mainBodyChunk, false, 1f, 1.1f); this.wolf.AerobicIncrease(0.05f); } this.wolf.bodyChunks[1].vel.x += (float)this.wolf.flipDirection * (0.5f + 0.5f * Mathf.Sin((float)this.animationFrame / 20f * 3.14159274f * 2f)) * -0.5f; } else if (this.animationFrame < 10) { this.animationFrame++; } else if (this.animationFrame > 10) { this.animationFrame--; } bool flag = false; if (this.wolf.movement.y < 0) { this.wolf.animation = new BlankAnimation(this.wolf); } else if (this.wolf.movement.y > 0) { if (this.wolf.room.GetTile(this.wolf.bodyChunks[0].pos).verticalBeam && this.wolf.animation.idx != Wolf.WolfAnimation.AnimationIndex.ClimbOnBeam) { this.wolf.animation = new MovementAnimation(this.wolf, AnimationIndex.ClimbOnBeam); if (this.wolf.bodyChunks[0].pos.x < this.wolf.room.MiddleOfTile(this.wolf.bodyChunks[0].pos).x) { this.wolf.flipDirection = -1; } else { this.wolf.flipDirection = 1; } } else { flag = true; } } else if (this.wolf.nyooming) { flag = true; } if (flag && this.wolf.animation.idx != Wolf.WolfAnimation.AnimationIndex.GetUpOnBeam) { this.wolf.room.PlaySound(SoundID.Slugcat_Get_Up_On_Horizontal_Beam, this.wolf.mainBodyChunk, false, 0.8f, 1.1f); this.wolf.animation = new MovementAnimation(this.wolf, AnimationIndex.GetUpOnBeam); this.wolf.straightUpOnHorizontalBeam = false; if (this.wolf.room.GetTile(this.wolf.bodyChunks[0].pos + new Vector2((float)this.wolf.flipDirection * 20f, 0f)).Terrain == Room.Tile.TerrainType.Solid || !this.wolf.room.GetTile(this.wolf.bodyChunks[0].pos + new Vector2((float)this.wolf.flipDirection * 20f, 0f)).horizontalBeam) { this.wolf.flipDirection = -this.wolf.flipDirection; } if (this.wolf.room.GetTile(this.wolf.bodyChunks[0].pos + new Vector2((float)this.wolf.flipDirection * 20f, 0f)).Terrain == Room.Tile.TerrainType.Solid || !this.wolf.room.GetTile(this.wolf.bodyChunks[0].pos + new Vector2((float)this.wolf.flipDirection * 20f, 0f)).horizontalBeam) { this.wolf.flipDirection = -this.wolf.flipDirection; this.wolf.straightUpOnHorizontalBeam = true; } if (!this.wolf.straightUpOnHorizontalBeam && this.wolf.room.GetTile(this.wolf.bodyChunks[0].pos + new Vector2((float)this.wolf.flipDirection * 20f, 20f)).Solid) { this.wolf.straightUpOnHorizontalBeam = true; } this.wolf.upOnHorizontalBeamPos = new Vector2(this.wolf.bodyChunks[0].pos.x, this.wolf.room.MiddleOfTile(this.wolf.bodyChunks[0].pos).y + 20f); } if (!this.wolf.room.GetTile(this.wolf.bodyChunks[0].pos).horizontalBeam) { this.wolf.animation = new BlankAnimation(this.wolf); } break; case AnimationIndex.GetUpOnBeam: this.wolf.bodyMode = BodyModeIndex.ClimbingOnBeam; this.wolf.bodyChunks[0].vel.x = 0f; this.wolf.bodyChunks[0].vel.y = 0f; this.wolf.forceFeetToHorizontalBeamTile = 20; if (this.wolf.straightUpOnHorizontalBeam) { if (this.wolf.movement.y < 0 || this.wolf.mainBodyChunk.ContactPoint.y > 0) { this.wolf.straightUpOnHorizontalBeam = false; } if (this.wolf.room.GetTile(this.wolf.upOnHorizontalBeamPos).Solid) { for (int i = 1; i >= -1; i -= 2) { if (!this.wolf.room.GetTile(this.wolf.upOnHorizontalBeamPos + new Vector2((float)(this.wolf.flipDirection * i) * 20f, 0f)).Solid) { this.wolf.upOnHorizontalBeamPos.x += (float)(this.wolf.flipDirection * i) * 20f; break; } } } this.wolf.mainBodyChunk.vel += Custom.DirVec(this.wolf.mainBodyChunk.pos, this.wolf.upOnHorizontalBeamPos) * 1.8f; this.wolf.bodyChunks[1].vel += Custom.DirVec(this.wolf.bodyChunks[1].pos, this.wolf.upOnHorizontalBeamPos + new Vector2(0f, -20f)) * 1.8f; if (this.wolf.room.GetTile(this.wolf.bodyChunks[1].pos).horizontalBeam && this.wolf.bodyChunks[1].pos.y > this.wolf.upOnHorizontalBeamPos.y - 25f && this.wolf.animation.idx != Wolf.WolfAnimation.AnimationIndex.StandOnBeam) { //this.wolf.noGrabCounter = 15; this.wolf.animation = new MovementAnimation(this.wolf, AnimationIndex.StandOnBeam); this.wolf.bodyChunks[1].pos.y = this.wolf.room.MiddleOfTile(this.wolf.bodyChunks[1].pos).y + 5f; this.wolf.bodyChunks[1].vel.y = 0f; } else if ((!this.wolf.room.GetTile(this.wolf.bodyChunks[0].pos).horizontalBeam && !this.wolf.room.GetTile(this.wolf.bodyChunks[1].pos).horizontalBeam) || !Custom.DistLess(this.wolf.mainBodyChunk.pos, this.wolf.upOnHorizontalBeamPos, 25f)) { this.wolf.animation = new BlankAnimation(this.wolf); } } else { this.wolf.bodyChunks[0].pos.y = this.wolf.room.MiddleOfTile(this.wolf.bodyChunks[0].pos).y; this.wolf.bodyChunks[1].vel.y += 2f; this.wolf.bodyChunks[1].vel.x += (float)this.wolf.flipDirection * 0.5f; if (this.wolf.bodyChunks[1].pos.y > this.wolf.mainBodyChunk.pos.y - 15f && !this.wolf.room.GetTile(this.wolf.mainBodyChunk.pos + new Vector2(Mathf.Sign(this.wolf.bodyChunks[1].pos.x - this.wolf.mainBodyChunk.pos.x) * 35f, 0f)).horizontalBeam && this.wolf.room.GetTile(this.wolf.mainBodyChunk.pos + new Vector2(Mathf.Sign(this.wolf.bodyChunks[1].pos.x - this.wolf.mainBodyChunk.pos.x) * -15f, 0f)).horizontalBeam) { this.wolf.mainBodyChunk.vel.x -= Mathf.Sign(this.wolf.bodyChunks[1].pos.x - this.wolf.mainBodyChunk.pos.x) * 1.5f; this.wolf.bodyChunks[1].vel.x -= Mathf.Sign(this.wolf.bodyChunks[1].pos.x - this.wolf.mainBodyChunk.pos.x) * 0.5f; } if (this.wolf.bodyChunks[1].ContactPoint.y > 0) { if (!this.wolf.room.GetTile(this.wolf.mainBodyChunk.pos + new Vector2(0f, 20f)).Solid) { this.wolf.straightUpOnHorizontalBeam = true; } else if (this.wolf.animation.idx != Wolf.WolfAnimation.AnimationIndex.HangFromBeam) { this.wolf.animation = new MovementAnimation(this.wolf, AnimationIndex.HangFromBeam); } } if (this.wolf.bodyChunks[1].pos.y > this.wolf.bodyChunks[0].pos.y && this.wolf.animation.idx != Wolf.WolfAnimation.AnimationIndex.StandOnBeam) { //this.wolf.noGrabCounter = 15; this.wolf.animation = new MovementAnimation(this.wolf, AnimationIndex.StandOnBeam); this.wolf.bodyChunks[1].pos.y = this.wolf.room.MiddleOfTile(this.wolf.bodyChunks[0].pos).y + 5f; this.wolf.bodyChunks[1].vel.y = 0f; } if (!this.wolf.room.GetTile(this.wolf.bodyChunks[0].pos).horizontalBeam) { this.wolf.animation = new BlankAnimation(this.wolf); } } break; case AnimationIndex.StandOnBeam: this.wolf.bodyMode = BodyModeIndex.ClimbingOnBeam; this.wolf.standing = true; //this.wolf.canJump = 5; this.wolf.bodyChunks[1].vel.x *= 0.5f; if (this.wolf.bodyChunks[0].ContactPoint.y < 1 || !this.wolf.IsTileSolid(1, 0, 1)) { this.wolf.bodyChunks[1].vel.y = 0f; this.wolf.bodyChunks[1].pos.y = this.wolf.room.MiddleOfTile(this.wolf.bodyChunks[1].pos).y + 5f; this.wolf.bodyChunks[0].vel.y += 2f; this.wolf.dynamicRunSpeed[0] = 2.1f * this.wolf.MovementSpeed; this.wolf.dynamicRunSpeed[1] = 2.1f * this.wolf.MovementSpeed; if (this.wolf.drop || (this.wolf.commitedToMove != null && this.wolf.commitedToMove.IsDrop)) { this.wolf.animation = new BlankAnimation(this.wolf); } } else { this.wolf.animation = new BlankAnimation(this.wolf); } if (this.wolf.movement.x != 0) { this.animationFrame++; } else { this.animationFrame = 0; } if (this.animationFrame > 6) { this.animationFrame = 0; this.wolf.room.PlaySound(SoundID.Slugcat_Walk_On_Horizontal_Beam, this.wolf.mainBodyChunk, false, 0.8f, 1.1f); } if (this.wolf.movement.y > 0 && this.wolf.room.GetTile(this.wolf.room.GetTilePosition(this.wolf.bodyChunks[0].pos) + new IntVector2(0, 1)).horizontalBeam) { //climb up BodyChunk bodyChunk22 = this.wolf.bodyChunks[0]; bodyChunk22.pos.y += 8f; BodyChunk bodyChunk23 = this.wolf.bodyChunks[1]; bodyChunk23.pos.y += 8f; this.wolf.animation = new MovementAnimation(this.wolf, AnimationIndex.HangFromBeam); } break; case AnimationIndex.ClimbOnBeam: this.wolf.bodyMode = BodyModeIndex.ClimbingOnBeam; this.wolf.standing = true; //this.wolf.canJump = 1; for (int j = 0; j < 2; j++) { if (this.wolf.bodyChunks[j].ContactPoint.x != 0) { this.wolf.flipDirection = -this.wolf.bodyChunks[j].ContactPoint.x; } } this.wolf.bodyChunks[0].vel.x = 0f; bool flag2 = true; if (!this.wolf.IsTileSolid(0, 0, 1) && this.wolf.movement.y > 0 && (this.wolf.bodyChunks[0].ContactPoint.y < 0 || this.wolf.IsTileSolid(0, this.wolf.flipDirection, 1))) { flag2 = false; } if (flag2 && this.wolf.IsTileSolid(0, this.wolf.flipDirection, 0)) { this.wolf.flipDirection = -this.wolf.flipDirection; } if (flag2) { this.wolf.bodyChunks[0].pos.x = (this.wolf.bodyChunks[0].pos.x + this.wolf.room.MiddleOfTile(this.wolf.bodyChunks[0].pos).x + (float)this.wolf.flipDirection * 5f) / 2f; this.wolf.bodyChunks[1].pos.x = (this.wolf.bodyChunks[1].pos.x * 7f + this.wolf.room.MiddleOfTile(this.wolf.bodyChunks[0].pos).x + (float)this.wolf.flipDirection * 5f) / 8f; } else { this.wolf.bodyChunks[0].pos.x = (this.wolf.bodyChunks[0].pos.x + this.wolf.room.MiddleOfTile(this.wolf.bodyChunks[0].pos).x) / 2f; this.wolf.bodyChunks[1].pos.x = (this.wolf.bodyChunks[1].pos.x * 7f + this.wolf.room.MiddleOfTile(this.wolf.bodyChunks[0].pos).x) / 8f; } this.wolf.bodyChunks[0].vel.y *= 0.5f; if (this.wolf.movement.y > 0) { this.animationFrame++; if (this.animationFrame > 20) { this.animationFrame = 0; this.wolf.room.PlaySound(SoundID.Slugcat_Climb_Up_Vertical_Beam, this.wolf.mainBodyChunk, false, 0.8f, 1.1f); this.wolf.AerobicIncrease(0.1f); } this.wolf.bodyChunks[0].vel.y += Custom.LerpMap((float)this.wolf.slowMovementStun, 0f, 10f, 1f, 0.2f) * this.wolf.MovementSpeed; } else if (this.wolf.movement.y < 0) { this.wolf.bodyChunks[0].vel.y -= 2.2f * (0.2f + 0.8f * this.wolf.room.gravity); } this.wolf.bodyChunks[0].vel.y += (1f + this.wolf.gravity); this.wolf.bodyChunks[1].vel.y -= (1f - this.wolf.gravity); if (this.slideUpPole > 0) { this.slideUpPole--; if (this.slideUpPole > 8) { this.animationFrame = 12; } if (this.slideUpPole == 0) { this.wolf.slowMovementStun = Math.Max(this.wolf.slowMovementStun, 16); } if (this.slideUpPole > 14) { this.wolf.bodyChunks[0].pos.y += 2f; this.wolf.bodyChunks[1].pos.y += 2f; } this.wolf.bodyChunks[0].vel.y += Custom.LerpMap((float)this.slideUpPole, 17f, 0f, 3f, -1.2f, 0.45f); this.wolf.bodyChunks[1].vel.y += Custom.LerpMap((float)this.slideUpPole, 17f, 0f, 1.5f, -1.4f, 0.45f); } this.wolf.GoThroughFloors = (this.wolf.movement.x == 0 && this.wolf.movement.y == 0); if (this.wolf.movement.x != 0 && (int)Mathf.Sign(this.wolf.movement.x) == this.wolf.flipDirection && (int)Mathf.Sign(this.wolf.movement.x) == this.wolf.lastFlipDirection) { if (this.wolf.room.GetTile(this.wolf.bodyChunks[0].pos).horizontalBeam && !this.wolf.IsTileSolid(0, 0, -1)) { this.wolf.animation = new MovementAnimation(this.wolf, AnimationIndex.HangFromBeam); } else if (this.wolf.room.GetTile(this.wolf.bodyChunks[1].pos).horizontalBeam) { this.wolf.animation = new MovementAnimation(this.wolf, AnimationIndex.StandOnBeam); } } if ((int)Mathf.Sign(this.wolf.movement.x) == this.wolf.flipDirection && this.wolf.flipDirection == this.wolf.lastFlipDirection && this.wolf.room.GetTile(this.wolf.room.GetTilePosition(this.wolf.bodyChunks[0].pos) + new IntVector2(this.wolf.flipDirection, 0)).verticalBeam) { this.wolf.bodyChunks[0].pos.x = this.wolf.room.MiddleOfTile(this.wolf.room.GetTilePosition(this.wolf.bodyChunks[0].pos) + new IntVector2(this.wolf.flipDirection, 0)).x - (float)this.wolf.flipDirection * 5f; this.wolf.flipDirection = -this.wolf.flipDirection; //this.wolf.jumpStun = 11 * this.wolf.flipDirection; } if (this.wolf.bodyChunks[1].ContactPoint.y < 0 && this.wolf.movement.y < 0) { this.wolf.room.PlaySound(SoundID.Slugcat_Regain_Footing, this.wolf.mainBodyChunk, false, 0.8f, 1.1f); this.wolf.animation = new MovementAnimation(this.wolf, AnimationIndex.StandUp); } if (!this.wolf.room.GetTile(this.wolf.bodyChunks[0].pos).verticalBeam) { this.wolf.animation = new BlankAnimation(this.wolf); if (this.wolf.room.GetTile(this.wolf.room.GetTilePosition(this.wolf.bodyChunks[0].pos) + new IntVector2(0, -1)).verticalBeam) { this.wolf.room.PlaySound(SoundID.Slugcat_Get_Up_On_Top_Of_Vertical_Beam_Tip, this.wolf.mainBodyChunk, false, 0.8f, 1.1f); this.wolf.animation = new MovementAnimation(this.wolf, AnimationIndex.GetUpToBeamTip); } else if (this.wolf.room.GetTile(this.wolf.room.GetTilePosition(this.wolf.bodyChunks[0].pos) + new IntVector2(0, 1)).verticalBeam) { this.wolf.animation = new MovementAnimation(this.wolf, AnimationIndex.HangUnderVerticalBeam); } } break; case AnimationIndex.GetUpToBeamTip: this.wolf.bodyMode = BodyModeIndex.ClimbingOnBeam; this.wolf.standing = true; //this.wolf.canJump = 5; this.wolf.bodyChunks[0].vel.y += this.wolf.gravity; this.wolf.bodyChunks[1].vel.y += this.wolf.gravity; Vector2 p = new Vector2(0f, 0f); for (int k = 0; k < 2; k++) { if (!this.wolf.room.GetTile(this.wolf.bodyChunks[k].pos).verticalBeam && this.wolf.room.GetTile(this.wolf.bodyChunks[k].pos + new Vector2(0f, -20f)).verticalBeam) { p = this.wolf.room.MiddleOfTile(this.wolf.bodyChunks[k].pos); break; } } if (p.x != 0f || p.y != 0f) { this.wolf.bodyChunks[0].pos.x = (this.wolf.bodyChunks[0].pos.x * 14f + p.x) / 15f; this.wolf.bodyChunks[1].pos.x = (this.wolf.bodyChunks[1].pos.x * 4f + p.x) / 5f; this.wolf.bodyChunks[0].vel.y += 0.1f; this.wolf.bodyChunks[1].pos.y = (this.wolf.bodyChunks[1].pos.y * 4f + p.y) / 5f; if (Custom.DistLess(this.wolf.bodyChunks[1].pos, p, 6f)) { this.wolf.animation = new MovementAnimation(this.wolf, AnimationIndex.BeamTip); this.wolf.room.PlaySound(SoundID.Slugcat_Regain_Footing, this.wolf.mainBodyChunk, false, 0.3f, 1.1f); } } else { this.wolf.animation = new BlankAnimation(this.wolf); } break; case AnimationIndex.HangUnderVerticalBeam: //dance this.wolf.bodyMode = BodyModeIndex.ClimbingOnBeam; this.wolf.standing = false; if (this.wolf.movement.y < 0 || this.wolf.bodyChunks[1].vel.magnitude > 10f || this.wolf.bodyChunks[0].vel.magnitude > 10f || !this.wolf.room.GetTile(this.wolf.bodyChunks[0].pos + new Vector2(0f, 20f)).verticalBeam) { this.wolf.animation = new BlankAnimation(this.wolf); this.wolf.standing = true; } else { this.wolf.bodyChunks[0].pos.x = Mathf.Lerp(this.wolf.bodyChunks[0].pos.x, this.wolf.room.MiddleOfTile(this.wolf.bodyChunks[0].pos).x, 0.5f); this.wolf.bodyChunks[0].pos.y = Mathf.Max(this.wolf.bodyChunks[0].pos.y, this.wolf.room.MiddleOfTile(this.wolf.bodyChunks[0].pos).y + 5f + this.wolf.bodyChunks[0].vel.y); this.wolf.bodyChunks[0].vel.x *= 0f; this.wolf.bodyChunks[0].vel.y *= 0.5f; this.wolf.bodyChunks[1].vel.x += (float)this.wolf.slugcat.input[1].x; //Mimic Sluggo if (this.wolf.movement.y > 0) { this.wolf.bodyChunks[0].vel.y += 2.5f; } if (this.wolf.room.GetTile(this.wolf.bodyChunks[0].pos).verticalBeam && this.wolf.animation.idx != Wolf.WolfAnimation.AnimationIndex.ClimbOnBeam) { this.wolf.animation = new MovementAnimation(this.wolf, AnimationIndex.ClimbOnBeam); } } if (this.wolf.nyooming) { this.wolf.animation = new BlankAnimation(this.wolf); if (this.wolf.movement.x == 0) { this.wolf.bodyChunks[0].pos.y += 16f; this.wolf.bodyChunks[0].vel.y = 10f; this.wolf.standing = true; } else { this.wolf.bodyChunks[1].vel.y += 4f; this.wolf.bodyChunks[1].vel.x += 2f * (float)this.wolf.movement.x; this.wolf.bodyChunks[0].vel.y += 6f; this.wolf.bodyChunks[0].vel.x += 3f * (float)this.wolf.movement.x; } } break; case AnimationIndex.BeamTip: //mimic sluggp this.wolf.bodyMode = BodyModeIndex.ClimbingOnBeam; this.wolf.standing = true; //this.wolf.canJump = 5; this.wolf.bodyChunks[1].vel *= 0.5f; this.wolf.bodyChunks[1].pos = (this.wolf.bodyChunks[1].pos + this.wolf.room.MiddleOfTile(this.wolf.bodyChunks[1].pos)) / 2f; this.wolf.bodyChunks[0].vel.y += 1.5f; this.wolf.bodyChunks[0].vel.y += (float)this.wolf.slugcat.input[1].y * 0.1f; this.wolf.bodyChunks[0].vel.x += (float)this.wolf.slugcat.input[1].x * 0.1f; if (this.wolf.movement.y > 0) { this.wolf.bodyChunks[1].vel.y -= 1f; //this.wolf.canJump = 0; this.wolf.animation = new BlankAnimation(this.wolf); } if (this.wolf.movement.y < 0 || this.wolf.bodyChunks[0].pos.y < this.wolf.bodyChunks[1].pos.y || !this.wolf.room.GetTile(this.wolf.bodyChunks[1].pos + new Vector2(0f, -20f)).verticalBeam) { this.wolf.animation = new BlankAnimation(this.wolf); } break; case AnimationIndex.CorridorTurn: if (this.wolf.corridorTurnDir != null && this.wolf.bodyMode == BodyModeIndex.CorridorClimb && this.corridorTurnCounter < 40) { this.wolf.slowMovementStun = Math.Max(10, this.wolf.slowMovementStun); this.wolf.mainBodyChunk.vel *= 0.5f; this.wolf.bodyChunks[1].vel *= 0.5f; if (this.corridorTurnCounter < 30) { this.wolf.mainBodyChunk.vel += Custom.DegToVec(UnityEngine.Random.value * 360f); } else { this.wolf.mainBodyChunk.vel += this.wolf.corridorTurnDir.Value.ToVector2() * 0.5f; this.wolf.bodyChunks[1].vel -= this.wolf.corridorTurnDir.Value.ToVector2() * 0.5f; } this.corridorTurnCounter++; } else { this.wolf.mainBodyChunk.vel += this.wolf.corridorTurnDir.Value.ToVector2() * 6f; this.wolf.bodyChunks[1].vel += this.wolf.corridorTurnDir.Value.ToVector2() * 5f; if (this.wolf.graphicsModule != null) { for (int l = 0; l < this.wolf.graphicsModule.bodyParts.Length; l++) { this.wolf.graphicsModule.bodyParts[l].vel -= this.wolf.corridorTurnDir.Value.ToVector2() * 10f; } } this.wolf.corridorTurnDir = default(IntVector2?); this.wolf.animation = new BlankAnimation(this.wolf); this.wolf.room.PlaySound(SoundID.Slugcat_Turn_In_Corridor, this.wolf.mainBodyChunk, false, 0.8f, 1.1f); } break; case AnimationIndex.SurfaceSwim: //this.wolf.canJump = 0; this.wolf.swimCycle += 0.025f; this.wolf.waterFriction = 0.96f; this.wolf.swimForce *= 0.5f; if (this.wolf.movement.y == -1) { this.wolf.bodyChunks[0].vel.y -= 0.2f; this.wolf.bodyChunks[1].vel.y += 0.1f; } else if (this.wolf.movement.y > 0) { this.wolf.bodyChunks[0].vel.y += 0.5f; } this.wolf.dynamicRunSpeed[0] = 2.7f; this.wolf.dynamicRunSpeed[1] = 0f; if (this.wolf.movement.x != 0) { this.wolf.bodyChunks[1].vel.x -= this.wolf.movement.x * 0.3f; this.wolf.swimCycle += 0.0333333351f; } if (this.wolf.bodyMode != BodyModeIndex.Swimming) { this.wolf.animation = new BlankAnimation(this.wolf); } break; case AnimationIndex.DeepSwim: this.wolf.dynamicRunSpeed[0] = 0f; this.wolf.dynamicRunSpeed[1] = 0f; //this.wolf.canJump = 0; this.wolf.standing = false; this.wolf.GoThroughFloors = true; float num = (Mathf.Abs(Vector2.Dot(this.wolf.bodyChunks[0].vel.normalized, (this.wolf.bodyChunks[0].pos - this.wolf.bodyChunks[1].pos).normalized)) + Mathf.Abs(Vector2.Dot(this.wolf.bodyChunks[1].vel.normalized, (this.wolf.bodyChunks[0].pos - this.wolf.bodyChunks[1].pos).normalized))) / 2f; this.wolf.swimCycle += 0.01f; if (this.wolf.movement != Vector2.zero || this.wolf.moving) { float value = Vector2.Angle(this.wolf.bodyChunks[0].lastPos - this.wolf.bodyChunks[1].lastPos, this.wolf.bodyChunks[0].pos - this.wolf.bodyChunks[1].pos); float num2 = 0.2f + Mathf.InverseLerp(0f, 12f, value) * 0.8f; if (this.wolf.slowMovementStun > 0) { num2 *= 0.5f; } num2 *= 1.1f; if (num2 > this.wolf.swimForce) { this.wolf.swimForce = Mathf.Lerp(this.wolf.swimForce, num2, 0.7f); } else { this.wolf.swimForce = Mathf.Lerp(this.wolf.swimForce, num2, 0.05f); } this.wolf.swimCycle += 0.1f; if (this.wolf.airInLungs < 0.5f && this.wolf.airInLungs > 0.166666672f) { this.wolf.swimCycle += 0.05f; } if (this.wolf.bodyChunks[0].ContactPoint.x != 0 || this.wolf.bodyChunks[0].ContactPoint.y != 0) { this.wolf.swimForce *= 0.5f; } if (this.wolf.swimCycle > 4f) { this.wolf.swimCycle = 0f; } else if (this.wolf.swimCycle > 3f) { this.wolf.bodyChunks[0].vel += Custom.DirVec(this.wolf.bodyChunks[1].pos, this.wolf.bodyChunks[0].pos) * 0.7f * Mathf.Lerp(this.wolf.swimForce, 1f, 0.5f) * this.wolf.bodyChunks[0].submersion; } Vector2 vector = this.SwimDir(true); if (this.wolf.airInLungs < 0.3f) { vector = Vector3.Slerp(vector, new Vector2(0f, 1f), Mathf.InverseLerp(0.3f, 0f, this.wolf.airInLungs)); } this.wolf.bodyChunks[0].vel += vector * 0.5f * this.wolf.swimForce * Mathf.Lerp(num, 1f, 0.5f) * this.wolf.bodyChunks[0].submersion; this.wolf.bodyChunks[1].vel -= vector * 0.1f * this.wolf.bodyChunks[0].submersion; this.wolf.bodyChunks[0].vel += Custom.DirVec(this.wolf.bodyChunks[1].pos, this.wolf.bodyChunks[0].pos) * 0.4f * this.wolf.swimForce * num * this.wolf.bodyChunks[0].submersion; if (this.wolf.bodyChunks[0].vel.magnitude < 3f) { this.wolf.bodyChunks[0].vel += vector * 0.2f * Mathf.InverseLerp(3f, 1.5f, this.wolf.bodyChunks[0].vel.magnitude); this.wolf.bodyChunks[1].vel -= vector * 0.1f * Mathf.InverseLerp(3f, 1.5f, this.wolf.bodyChunks[0].vel.magnitude); } } this.wolf.waterFriction = Mathf.Lerp(0.92f, 0.96f, num); if (this.wolf.bodyMode != BodyModeIndex.Swimming) { this.wolf.animation = new BlankAnimation(this.wolf); } break; case AnimationIndex.Flip: this.wolf.bodyMode = BodyModeIndex.Default; Vector2 a = Custom.PerpendicularVector(this.wolf.bodyChunks[1].pos, this.wolf.bodyChunks[0].pos); this.wolf.bodyChunks[0].vel -= a * (float)this.wolf.slideDirection * 0.4f * ((!this.flipFromSlide) ? 1f : 2.5f); this.wolf.bodyChunks[1].vel += a * (float)this.wolf.slideDirection * 0.4f * ((!this.flipFromSlide) ? 1f : 2.5f); this.wolf.standing = false; for (int n = 0; n < 2; n++) { if (this.wolf.bodyChunks[n].ContactPoint.x != 0 || this.wolf.bodyChunks[n].ContactPoint.y != 0) { this.wolf.animation = new BlankAnimation(this.wolf); this.wolf.standing = (this.wolf.bodyChunks[0].pos.y > this.wolf.bodyChunks[1].pos.y); break; } } break; case AnimationIndex.ZeroGSwim: this.wolf.dynamicRunSpeed[0] = 0f; this.wolf.dynamicRunSpeed[1] = 0f; this.wolf.bodyMode = BodyModeIndex.ZeroG; this.wolf.standing = false; this.circuitSwimResistance *= Mathf.InverseLerp(this.wolf.mainBodyChunk.vel.magnitude + this.wolf.bodyChunks[1].vel.magnitude, 15f, 9f); bool flag4 = false; //this.wolf.canJump > 0; for (int num5 = 0; num5 < 2; num5++) { if (this.wolf.swimBits[num5] != null && !Custom.DistLess(this.wolf.mainBodyChunk.pos, this.wolf.swimBits[num5].pos, 50f)) { this.wolf.swimBits[num5] = null; } this.wolf.bodyChunks[num5].vel *= Mathf.Lerp(1f, 0.9f, this.circuitSwimResistance); if (this.wolf.bodyChunks[num5].ContactPoint.x != 0 || this.wolf.bodyChunks[num5].ContactPoint.y != 0) { flag4 = true; //this.wolf.canJump = 12; if (this.wolf.bodyChunks[num5].lastContactPoint.x != this.wolf.bodyChunks[num5].ContactPoint.x || this.wolf.bodyChunks[num5].lastContactPoint.y != this.wolf.bodyChunks[num5].ContactPoint.y) { this.wolf.Blink(5); this.wolf.room.PlaySound(SoundID.Slugcat_Regain_Footing, this.wolf.mainBodyChunk); } } } if (!flag4 && (this.wolf.room.GetTile(this.wolf.mainBodyChunk.pos).verticalBeam || this.wolf.room.GetTile(this.wolf.mainBodyChunk.pos).horizontalBeam)) { flag4 = true; } int num6 = 0; while (num6 < 9 && !flag4) { if (this.wolf.room.GetTile(this.wolf.mainBodyChunk.pos + Custom.eightDirectionsAndZero[num6].ToVector2() * 10f).Solid) { flag4 = true; } num6++; } this.wolf.swimCycle += 4f / Custom.LerpMap(this.wolf.mainBodyChunk.vel.magnitude, 0f, 2f, 120f, 60f); if (this.wolf.movement != Vector2.zero) { this.wolf.swimCycle += 1f / Mathf.Lerp(2f, 6f, UnityEngine.Random.value); Vector2 vector2 = this.SwimDir(false); this.wolf.mainBodyChunk.vel += this.SwimDir(false) * this.circuitSwimResistance * 0.5f; if (flag4) { this.wolf.mainBodyChunk.vel += vector2 * 0.2f * 4f; } else { this.wolf.mainBodyChunk.vel += vector2 * Custom.LerpMap(Vector2.Distance(this.wolf.mainBodyChunk.vel, this.wolf.bodyChunks[1].vel), 1f, 4f, 0.1f, Custom.LerpMap((this.wolf.mainBodyChunk.vel + this.wolf.bodyChunks[1].vel).magnitude, 4f, 8f, 0.15f, 0.1f)); } this.wolf.bodyChunks[1].vel -= vector2 * 0.1f; for (int num7 = 0; num7 < 5; num7++) { if (this.wolf.room.GetTile(this.wolf.mainBodyChunk.pos + Custom.fourDirectionsAndZero[0].ToVector2() * 15f).AnyBeam) { this.wolf.mainBodyChunk.vel *= 0.8f; this.wolf.mainBodyChunk.vel += vector2 * 0.2f; break; } } if ((this.wolf.movement.x != 0 || (this.wolf.movement.y != 0 && Mathf.Sign(this.wolf.movement.y) != Mathf.Sign(this.wolf.mainBodyChunk.vel.y))) && this.wolf.room.GetTile(this.wolf.mainBodyChunk.pos).horizontalBeam && !this.wolf.room.GetTile(this.wolf.mainBodyChunk.lastPos).horizontalBeam && this.wolf.animation.idx != Wolf.WolfAnimation.AnimationIndex.ZeroGPoleGrab) { this.wolf.room.PlaySound(SoundID.Slugcat_Grab_Beam, this.wolf.mainBodyChunk); this.wolf.animation = new MovementAnimation(this.wolf, AnimationIndex.ZeroGPoleGrab); this.wolf.standing = false; } else if ((this.wolf.movement.y != 0 || (this.wolf.movement.x != 0 && Mathf.Sign(this.wolf.movement.x) != Mathf.Sign(this.wolf.mainBodyChunk.vel.x))) && this.wolf.room.GetTile(this.wolf.mainBodyChunk.pos).verticalBeam && !this.wolf.room.GetTile(this.wolf.mainBodyChunk.lastPos).verticalBeam && this.wolf.animation.idx != Wolf.WolfAnimation.AnimationIndex.ZeroGPoleGrab) { this.wolf.room.PlaySound(SoundID.Slugcat_Grab_Beam, this.wolf.mainBodyChunk); this.wolf.animation = new MovementAnimation(this.wolf, AnimationIndex.ZeroGPoleGrab); this.wolf.standing = true; } } if (this.wolf.swimCycle > 4f) { this.wolf.swimCycle = 0f; } this.circuitSwimResistance = 0f; if (this.curcuitJumpMeter >= 0f) { this.curcuitJumpMeter = Mathf.Clamp(this.curcuitJumpMeter - 0.5f, 0f, 4f); } else { this.curcuitJumpMeter = Mathf.Min(this.curcuitJumpMeter + 0.5f, 0f); } break; case AnimationIndex.ZeroGPoleGrab: this.wolf.dynamicRunSpeed[0] = 0f; this.wolf.dynamicRunSpeed[1] = 0f; this.wolf.bodyMode = BodyModeIndex.ZeroG; this.wolf.mainBodyChunk.vel *= Custom.LerpMap(this.wolf.mainBodyChunk.vel.magnitude, 2f, 5f, 0.7f, 0.3f); bool flag5 = false; if (this.wolf.movement != Vector2.zero || this.wolf.moving) { if (this.wolf.movement.x != 0) { this.zeroGPoleGrabDir.x = (int)Mathf.Sign(this.wolf.movement.x); } if (this.wolf.movement.y != 0) { this.zeroGPoleGrabDir.y = (int)Mathf.Sign(this.wolf.movement.y); } } if (!this.wolf.room.GetTile(this.wolf.mainBodyChunk.pos).horizontalBeam && !this.wolf.room.GetTile(this.wolf.mainBodyChunk.pos).verticalBeam && this.wolf.animation.idx != Wolf.WolfAnimation.AnimationIndex.ZeroGSwim) { this.wolf.standing = false; this.wolf.animation = new MovementAnimation(this.wolf, AnimationIndex.ZeroGSwim); } else { if (!this.wolf.room.GetTile(this.wolf.mainBodyChunk.pos).horizontalBeam && this.wolf.room.GetTile(this.wolf.mainBodyChunk.pos).verticalBeam) { this.wolf.standing = true; } else if (this.wolf.room.GetTile(this.wolf.mainBodyChunk.pos).horizontalBeam && !this.wolf.room.GetTile(this.wolf.mainBodyChunk.pos).verticalBeam) { this.wolf.standing = false; } else if (this.wolf.movement.x != 0 && this.wolf.movement.y == 0) { this.wolf.standing = false; } else if (this.wolf.movement.x == 0 && this.wolf.movement.y != 0) { this.wolf.standing = true; } if (this.wolf.standing) { if (this.wolf.room.readyForAI && this.wolf.room.aimap.getAItile(this.wolf.mainBodyChunk.pos + new Vector2(0f, this.wolf.movement.y * 20f)).narrowSpace) { this.wolf.mainBodyChunk.vel.x += (this.wolf.room.MiddleOfTile(this.wolf.mainBodyChunk.pos).x - this.wolf.mainBodyChunk.pos.x) * 0.1f; } else { this.wolf.mainBodyChunk.vel.x += (this.wolf.room.MiddleOfTile(this.wolf.mainBodyChunk.pos).x + 5f * (float)this.zeroGPoleGrabDir.x - this.wolf.mainBodyChunk.pos.x) * 0.1f; } if (this.wolf.movement.y != 0) { if (this.wolf.room.GetTile(this.wolf.mainBodyChunk.pos + new Vector2(0f, (float)this.wolf.movement.y * 10f)).verticalBeam) { this.wolf.mainBodyChunk.vel.y += (float)this.wolf.movement.y * 1.1f * this.wolf.MovementSpeed; this.animationFrame++; if (this.animationFrame > 20) { this.animationFrame = 0; this.wolf.room.PlaySound(SoundID.Slugcat_Climb_Up_Vertical_Beam, this.wolf.mainBodyChunk, false, 0.8f, 1.1f); } } else if (this.wolf.movement != Vector2.zero || this.wolf.moving) { flag5 = true; } } if (!flag5 && this.wolf.room.GetTile(this.wolf.bodyChunks[1].pos).verticalBeam) { this.wolf.bodyChunks[1].vel *= 0.7f; this.wolf.bodyChunks[1].vel.x += (this.wolf.room.MiddleOfTile(this.wolf.bodyChunks[1].pos).x - 5f * (float)this.zeroGPoleGrabDir.x - this.wolf.bodyChunks[1].pos.x) * 0.1f; } } else { if (this.wolf.room.readyForAI && this.wolf.room.aimap.getAItile(this.wolf.mainBodyChunk.pos + new Vector2(this.wolf.movement.x * 20f, 0f)).narrowSpace) { this.wolf.mainBodyChunk.vel.y += (this.wolf.room.MiddleOfTile(this.wolf.mainBodyChunk.pos).y - this.wolf.mainBodyChunk.pos.y) * 0.1f; } else { this.wolf.mainBodyChunk.vel.y += (this.wolf.room.MiddleOfTile(this.wolf.mainBodyChunk.pos).y + 5f * (float)this.zeroGPoleGrabDir.y - this.wolf.mainBodyChunk.pos.y) * 0.1f; } if (this.wolf.movement.x != 0) { if (this.wolf.room.GetTile(this.wolf.mainBodyChunk.pos + new Vector2(this.wolf.movement.x * 10f, 0f)).horizontalBeam) { this.wolf.mainBodyChunk.vel.x += (float)this.wolf.movement.x * 1.1f * this.wolf.MovementSpeed; this.animationFrame++; if (this.animationFrame > 20) { this.animationFrame = 0; this.wolf.room.PlaySound(SoundID.Slugcat_Climb_Up_Vertical_Beam, this.wolf.mainBodyChunk, false, 0.8f, 1.1f); } } else if (this.wolf.movement != Vector2.zero || this.wolf.moving) { flag5 = true; } } if (!flag5 && this.wolf.room.GetTile(this.wolf.bodyChunks[1].pos).horizontalBeam) { this.wolf.bodyChunks[1].vel *= 0.7f; this.wolf.bodyChunks[1].vel.y += (this.wolf.room.MiddleOfTile(this.wolf.bodyChunks[1].pos).y - 5f * (float)this.zeroGPoleGrabDir.y - this.wolf.bodyChunks[1].pos.y) * 0.1f; } } if (this.wolf.nyooming) { if (this.wolf.movement != Vector2.zero || this.wolf.moving) { Vector2 a3 = this.SwimDir(true); if (!flag5 && (!this.wolf.room.GetTile(this.wolf.mainBodyChunk.pos).horizontalBeam || !this.wolf.room.GetTile(this.wolf.mainBodyChunk.pos).verticalBeam)) { if (this.wolf.standing && this.wolf.movement.x == 0f) { a3.y *= 0.1f; } else if (!this.wolf.standing && this.wolf.movement.y == 0f) { a3.x *= 0.1f; } } this.wolf.mainBodyChunk.vel = Vector2.ClampMagnitude(this.wolf.mainBodyChunk.vel + a3 * 5.4f, 5.4f); this.wolf.bodyChunks[1].vel = Vector2.ClampMagnitude(this.wolf.bodyChunks[1].vel + a3 * 5f, 5f); this.wolf.room.PlaySound(SoundID.Slugcat_From_Horizontal_Pole_Jump, this.wolf.mainBodyChunk); } else { this.wolf.room.PlaySound(SoundID.Slugcat_Climb_Along_Horizontal_Beam, this.wolf.mainBodyChunk); } this.wolf.standing = false; if (this.wolf.animation.idx != Wolf.WolfAnimation.AnimationIndex.ZeroGSwim) { this.wolf.animation = new MovementAnimation(this.wolf, AnimationIndex.ZeroGSwim); } } if (this.wolf.room.readyForAI && this.wolf.room.aimap.getAItile(this.wolf.mainBodyChunk.pos).narrowSpace && this.wolf.room.aimap.getAItile(this.wolf.mainBodyChunk.pos + new Vector2(Mathf.Sign(this.wolf.movement.x) * 20f, Mathf.Sign(this.wolf.movement.y) * 20f)).narrowSpace) { this.wolf.bodyMode = BodyModeIndex.CorridorClimb; this.wolf.animation = new BlankAnimation(this.wolf); } } break; case AnimationIndex.VineGrab: { this.wolf.dynamicRunSpeed[0] = 0f; this.wolf.dynamicRunSpeed[1] = 0f; this.wolf.bodyMode = BodyModeIndex.Default; Vector2 vector5 = this.SwimDir(true); this.wolf.room.climbableVines.VineBeingClimbedOn(this.vinePos, this.wolf); if (vector5.magnitude > 0f) { this.vineClimbCursor = Vector2.ClampMagnitude(this.vineClimbCursor + vector5 * Custom.LerpMap(Vector2.Dot(vector5, this.vineClimbCursor.normalized), -1f, 1f, 10f, 3f), 30f); Vector2 a4 = this.wolf.room.climbableVines.OnVinePos(this.vinePos); this.vinePos.floatPos += this.wolf.room.climbableVines.ClimbOnVineSpeed(this.vinePos, this.wolf.mainBodyChunk.pos + this.vineClimbCursor) * Mathf.Lerp(2.1f, 1.5f, this.wolf.room.gravity) / this.wolf.room.climbableVines.TotalLength(this.vinePos.vine); this.vinePos.floatPos = Mathf.Clamp(this.vinePos.floatPos, 0f, 1f); this.wolf.room.climbableVines.PushAtVine(this.vinePos, (a4 - this.wolf.room.climbableVines.OnVinePos(this.vinePos)) * 0.05f); if (this.vineGrabDelay == 0) { ClimbableVinesSystem.VinePosition vinePosition = this.wolf.room.climbableVines.VineSwitch(this.vinePos, this.wolf.mainBodyChunk.pos + this.vineClimbCursor, this.wolf.mainBodyChunk.rad); if (vinePosition != null) { this.vinePos = vinePosition; this.vineGrabDelay = 10; } } this.animationFrame++; if (this.animationFrame > 30) { this.animationFrame = 0; } } else { this.vineClimbCursor *= 0.8f; } this.wolf.mainBodyChunk.vel += this.vineClimbCursor / 190f; this.wolf.bodyChunks[1].vel -= this.vineClimbCursor / 190f; Vector2 p2 = this.wolf.room.climbableVines.OnVinePos(this.vinePos); if (this.wolf.movement.x != 0) { this.zeroGPoleGrabDir.x = (int)Mathf.Sign(this.wolf.movement.x); } if (this.wolf.movement.y != 0) { this.zeroGPoleGrabDir.y = (int)Mathf.Sign(this.wolf.movement.y); } bool flag6 = false; if (this.wolf.nyooming) { flag6 = true; if (vector5.magnitude > 0f) { this.wolf.mainBodyChunk.vel = this.wolf.mainBodyChunk.vel + vector5.normalized * 4f; this.wolf.bodyChunks[1].vel = this.wolf.bodyChunks[1].vel + vector5.normalized * 3.5f; this.wolf.mainBodyChunk.vel = Vector2.Lerp(this.wolf.mainBodyChunk.vel, Vector2.ClampMagnitude(this.wolf.mainBodyChunk.vel, 5f), 0.5f); this.wolf.bodyChunks[1].vel = Vector2.Lerp(this.wolf.bodyChunks[1].vel, Vector2.ClampMagnitude(this.wolf.bodyChunks[1].vel, 5f), 0.5f); this.wolf.room.climbableVines.PushAtVine(this.vinePos, -vector5.normalized * 15f); this.vineGrabDelay = 10; } } else if (!this.wolf.room.climbableVines.VineCurrentlyClimbable(this.vinePos)) { flag6 = true; this.vineGrabDelay = 10; } if (!flag6 && Custom.DistLess(this.wolf.mainBodyChunk.pos, p2, 40f + this.wolf.room.climbableVines.VineRad(this.vinePos))) { this.wolf.room.climbableVines.ConnectChunkToVine(this.wolf.mainBodyChunk, this.vinePos, this.wolf.room.climbableVines.VineRad(this.vinePos)); Vector2 a5 = Custom.PerpendicularVector(this.wolf.room.climbableVines.VineDir(this.vinePos)); this.wolf.bodyChunks[0].vel += a5 * 0.2f * (float)((Mathf.Abs(a5.x) <= Mathf.Abs(a5.y)) ? this.zeroGPoleGrabDir.y : this.zeroGPoleGrabDir.x); if (this.wolf.room.gravity == 0f) { Vector2 vector6 = this.wolf.room.climbableVines.OnVinePos(new ClimbableVinesSystem.VinePosition(this.vinePos.vine, this.vinePos.floatPos - 20f / this.wolf.room.climbableVines.TotalLength(this.vinePos.vine))); Vector2 vector7 = this.wolf.room.climbableVines.OnVinePos(new ClimbableVinesSystem.VinePosition(this.vinePos.vine, this.vinePos.floatPos + 20f / this.wolf.room.climbableVines.TotalLength(this.vinePos.vine))); if (Vector2.Distance(this.wolf.bodyChunks[1].pos, vector6) < Vector2.Distance(this.wolf.bodyChunks[1].pos, vector7)) { this.wolf.bodyChunks[0].vel -= Vector2.ClampMagnitude(vector6 - this.wolf.bodyChunks[1].pos, 5f) / 20f; this.wolf.bodyChunks[1].vel += Vector2.ClampMagnitude(vector6 - this.wolf.bodyChunks[1].pos, 5f) / 20f; } else { this.wolf.bodyChunks[0].vel -= Vector2.ClampMagnitude(vector7 - this.wolf.bodyChunks[1].pos, 5f) / 20f; this.wolf.bodyChunks[1].vel += Vector2.ClampMagnitude(vector7 - this.wolf.bodyChunks[1].pos, 5f) / 20f; } } } else { this.wolf.animation = new BlankAnimation(this.wolf); } break; } } } public Vector2 SwimDir(bool normalize) { Vector2 result = this.wolf.movement; if (result.x != 0f || result.y != 0f) { if (normalize) { result = result.normalized; } return result; } if (this.wolf.movement != Vector2.zero) { return new Vector2(Mathf.Sign(this.wolf.movement.x), Mathf.Sign(this.wolf.movement.y)).normalized; } return new Vector2(0f, 0f); } } public float[] dynamicRunSpeed = new float[2]; public int stuckCounter; public float LittleStuck { get { return Mathf.InverseLerp(5f, 20f, (float)this.stuckCounter); } } public float ReallyStuck { get { return Mathf.InverseLerp(40f, 200f, (float)this.stuckCounter); } } public IntVector2 NextTile { get { if (this.connections.Count > 0) { return this.connections[this.connections.Count - 1].DestTile; } return this.occupyTile; } } public bool Playing { get { return this.animation != null && this.animation.Active && this.animation.idx == Wolf.WolfAnimation.AnimationIndex.Play; } } public class PlayAnimation : Wolf.WolfAnimation { public PlayAnimation(Wolf wolf) : base(wolf, Wolf.WolfAnimation.AnimationIndex.Play) { this.sitPos = wolf.room.GetWorldCoordinate(wolf.occupyTile); } public static bool PlayPossible(Wolf wolf) { return wolf.bodyMode == BodyModeIndex.Default && wolf.AI.behavior == WolfAI.Behavior.Idle && wolf.AI.discomfortWithOtherCreatures <= 0.2f && wolf.AI.scared <= 0.2f && !wolf.moving && wolf.room.GetTile(wolf.occupyTile + new IntVector2(0, -1)).Solid && wolf.room.aimap.getAItile(wolf.bodyChunks[1].pos).acc == AItile.Accessibility.Floor; } public override bool Continue { get { return Wolf.PlayAnimation.PlayPossible(this.wolf); } } public WorldCoordinate sitPos; public Vector2? playAtPos; public int pause; public int freeze; public override void Update() { base.Update(); if (this.pause > 0) { this.pause--; } else { this.wolf.bodyChunks[1].vel *= 0.8f; this.wolf.bodyChunks[1].vel += Vector2.ClampMagnitude(this.wolf.room.MiddleOfTile(this.sitPos) + new Vector2(0f, -6f) - this.wolf.bodyChunks[1].pos, 10f) / 5f; } } #pragma warning disable IDE0051 private void FindNewPlayAtPos(Vector2 aimAt) #pragma warning restore IDE0051 { Vector2? vector = SharedPhysics.ExactTerrainRayTracePos(this.wolf.room, this.wolf.mainBodyChunk.pos, aimAt); if (vector != null && Custom.DistLess(this.wolf.mainBodyChunk.pos, vector.Value, 60f) && !Custom.DistLess(this.wolf.bodyChunks[1].pos, vector.Value, 30f) && vector.Value.y > this.wolf.bodyChunks[1].pos.y - 20f) { this.playAtPos = vector; } } } public enum BodyModeIndex { Default, Crawl, Stand, Swimming, ClimbingOnBeam, CorridorClimb, WallClimb, PrepareJump, ZeroG, Stunned, Dead } public abstract class AttentiveAnimation : Wolf.WolfAnimation { protected AttentiveAnimation(Wolf wolf, Tracker.CreatureRepresentation creatureRep, Vector2 point, bool stop, Wolf.WolfAnimation.AnimationIndex idx) : base(wolf, idx) { this.point = point; this.creatureRep = creatureRep; this.stop = stop; wolf.bodyChunks[1].pos = Vector2.Lerp(wolf.bodyChunks[1].pos, wolf.bodyChunks[0].pos + Custom.DirVec(wolf.bodyChunks[0].pos, this.LookPoint) * wolf.bodyChunkConnections[0].distance, 0.1f + 0.4f); wolf.bodyChunks[1].vel *= 0.5f; wolf.bodyChunks[1].vel += Custom.DirVec(wolf.bodyChunks[0].pos, this.LookPoint) * 1.1f; } public Vector2 LookPoint { get { if (this.creatureRep == null) { return this.point; } if (this.creatureRep.VisualContact && this.creatureRep.representedCreature.realizedCreature != null) { return this.creatureRep.representedCreature.realizedCreature.DangerPos; } return this.wolf.room.MiddleOfTile(this.creatureRep.BestGuessForPosition()); } } public Tracker.CreatureRepresentation creatureRep; public Vector2 point; public bool stop; } public abstract class PointingAnimation : Wolf.AttentiveAnimation { protected PointingAnimation(Wolf wolf, Tracker.CreatureRepresentation creatureRep, Vector2 point, Wolf.WolfAnimation.AnimationIndex idx) : base(wolf, creatureRep, point, true, idx) { this.pointingArm = ((UnityEngine.Random.value >= 0.5f) ? 1 : 0); } public int PointingArm { get { if (this.wolf.grasps[0] != null) { return (!(this.wolf.grasps[0].grabbed is Spear)) ? 1 : 0; } return this.pointingArm; } } public override void Update() { this.cycle += Mathf.Lerp(0.5f, 1.5f, Mathf.Pow(this.wolf.abstractCreature.personality.energy * this.wolf.AI.agitation, 0.5f)); base.Update(); } protected int pointingArm; public float cycle; } public class GeneralPointAnimation : Wolf.PointingAnimation { public GeneralPointAnimation(Wolf wolf, Tracker.CreatureRepresentation creatureRep, Vector2 point, List<Tracker.CreatureRepresentation> group) : base(wolf, creatureRep, point, Wolf.WolfAnimation.AnimationIndex.GeneralPoint) { this.group = group; this.groupStartNum = group.Count; } public override void Update() { base.Update(); if (this.group.Count < 1 || this.creatureRep == null || this.creatureRep.representedCreature.realizedCreature == null) { return; } int num = UnityEngine.Random.Range(0, this.group.Count); if (this.group[num].representedCreature.realizedCreature != null && this.group[num].representedCreature.realizedCreature.room == this.wolf.room && this.group[num].representedCreature.realizedCreature is Wolf) { if ((this.group[num].representedCreature.realizedCreature as Wolf).AI.tracker.RepresentationForObject(this.creatureRep.representedCreature.realizedCreature, false) != null) { this.group.RemoveAt(num); } } else { this.group.RemoveAt(num); } } public override bool Continue { get { return (float)this.age < Mathf.Lerp(80f + 300f * Mathf.Pow(Mathf.InverseLerp(0f, (float)this.groupStartNum, (float)this.group.Count), 1.5f - this.wolf.abstractCreature.personality.sympathy), 40f, Mathf.Lerp(this.wolf.AI.currentUtility, this.wolf.AI.agitation, 0.5f)); } } private List<Tracker.CreatureRepresentation> group; private int groupStartNum; } public abstract class CommunicationAnimation : Wolf.AttentiveAnimation { protected CommunicationAnimation(Wolf wolf, Tracker.CreatureRepresentation creatureRep, Vector2 point, Wolf.WolfAnimation.AnimationIndex idx) : base(wolf, creatureRep, point, true, idx) { this.gestureArm = ((UnityEngine.Random.value >= 0.5f) ? 1 : 0); } public int GestureArm { get { if (this.wolf.grasps[0] != null) { return (!(this.wolf.grasps[0].grabbed is Spear)) ? 1 : 0; } return this.gestureArm; } } public virtual Vector2 GestureArmPos() { return this.wolf.mainBodyChunk.pos + Custom.DirVec(this.wolf.mainBodyChunk.pos, base.LookPoint) * 60f; } protected int gestureArm; public bool pointWithSpears; } private enum ObjectGrabability { CantGrab, OneHand, BigOneHand, TwoHands, Drag } private Wolf.ObjectGrabability Grabability(PhysicalObject obj) { if (obj is Weapon) { return (!(obj is Spear)) ? Wolf.ObjectGrabability.OneHand : Wolf.ObjectGrabability.TwoHands; } if (obj is DataPearl) { return Wolf.ObjectGrabability.OneHand; } if (obj is Fly) { if (obj.grabbedBy.Count > 0 && obj.grabbedBy[0].grabber == this) { return Wolf.ObjectGrabability.BigOneHand; } return ((obj as Fly).shortcutDelay != 0) ? Wolf.ObjectGrabability.CantGrab : Wolf.ObjectGrabability.OneHand; } else { if (obj is DangleFruit) { return Wolf.ObjectGrabability.BigOneHand; } if (obj is EggBugEgg) { return Wolf.ObjectGrabability.BigOneHand; } if (obj is VultureGrub) { return Wolf.ObjectGrabability.BigOneHand; } if (obj is Hazer) { return (!(obj as Hazer).spraying) ? Wolf.ObjectGrabability.BigOneHand : Wolf.ObjectGrabability.CantGrab; } if (obj is JellyFish) { return Wolf.ObjectGrabability.BigOneHand; } if (obj is SwollenWaterNut) { return Wolf.ObjectGrabability.BigOneHand; } if (obj is OracleSwarmer) { return Wolf.ObjectGrabability.BigOneHand; } if (obj is KarmaFlower) { return Wolf.ObjectGrabability.BigOneHand; } if (obj is Mushroom) { return Wolf.ObjectGrabability.OneHand; } if (obj is Lantern) { return Wolf.ObjectGrabability.OneHand; } if (obj is Centipede && (obj as Centipede).Small) { return Wolf.ObjectGrabability.TwoHands; } if (obj is Creature && !(obj as Creature).Template.smallCreature && (obj as Creature).dead) { return Wolf.ObjectGrabability.Drag; } if (obj is VultureMask) { return Wolf.ObjectGrabability.TwoHands; } if (obj is SlimeMold) { return Wolf.ObjectGrabability.BigOneHand; } if (obj is FlyLure) { return Wolf.ObjectGrabability.OneHand; } if (obj is SmallNeedleWorm) { return Wolf.ObjectGrabability.TwoHands; } if (obj is NeedleEgg) { return Wolf.ObjectGrabability.TwoHands; } if (obj is BubbleGrass) { return Wolf.ObjectGrabability.OneHand; } if (obj is NSHSwarmer) { return Wolf.ObjectGrabability.OneHand; } if (obj is OverseerCarcass) { return Wolf.ObjectGrabability.OneHand; } //new if (obj is HornestFruit) { return Wolf.ObjectGrabability.TwoHands; } if (obj is SmallCentiwing) { return Wolf.ObjectGrabability.TwoHands; } return Wolf.ObjectGrabability.CantGrab; } } public bool HeavyCarry(PhysicalObject obj) { return this.Grabability(obj) == Wolf.ObjectGrabability.Drag || this.Grabability(obj) == Wolf.ObjectGrabability.TwoHands || obj.TotalMass > base.TotalMass * 0.6f; } public int FreeHand() { if (base.grasps[0] != null && this.HeavyCarry(base.grasps[0].grabbed)) { return -1; } for (int i = 0; i < base.grasps.Length; i++) { if (base.grasps[i] == null) { return i; } } return -1; } } }
using System.Collections.Generic; namespace Likja.Conthread { public interface IConthreadService<T> where T : Conthread { IEnumerable<T> GetAll(); T GetById(int id); int Save(T entity); T GetNext(int id); T GetPrevious(int id); } }
using UnityEngine; using System.Collections.Generic; /// <summary> /// メッシュ統合 /// </summary> static public class MeshCombine { /// <summary> /// 統合する /// </summary> /// <param name="combine">統合対象の親オブジェクト</param> /// <param name="parent">統合したものの親オブジェクト</param> static public void Combine(GameObject combine, GameObject parent) { //レンダラーの取得 Renderer[] meshRenderers = combine.GetComponentsInChildren<Renderer>(); //マテリアルごとに統合する Dictionary<Material, List<CombineInstance>> instances = new Dictionary<Material, List<CombineInstance>>(); //リストに追加していく foreach (var renderer in meshRenderers) { //レンダラーがdisableなら何もしない if (!renderer.enabled) continue; var mat = renderer.sharedMaterial; //キーがない場合 if (!instances.ContainsKey(mat)) { //キーの追加 instances.Add(mat, new List<CombineInstance>()); } var cmesh = new CombineInstance(); cmesh.transform = renderer.transform.localToWorldMatrix; cmesh.mesh = renderer.GetComponent<MeshFilter>().sharedMesh; instances[mat].Add(cmesh); } //統合する foreach (var instance in instances) { GameObject obj = new GameObject(instance.Key.name); MeshFilter meshFilter = obj.AddComponent<MeshFilter>(); MeshRenderer renderer = obj.AddComponent<MeshRenderer>(); renderer.sharedMaterial = instance.Key; meshFilter.mesh = new Mesh(); meshFilter.mesh.CombineMeshes(instance.Value.ToArray()); if (meshFilter.sharedMesh.vertexCount > ushort.MaxValue) { Debug.LogError("頂点数が多すぎます"); } obj.isStatic = true; obj.transform.parent = parent.transform; renderer.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off; } } }
namespace BoardGame.CardModelFromDatabase { public partial class PassiveCard { public override string ToString() { return SpecialPassiveAbility; } } }
using System.Collections.Generic; using UnityEngine; namespace DChild.Gameplay.Physics { [RequireComponent(typeof(Collider2D))] public class CollisionDetector : MonoBehaviour { [SerializeField] private LayerMask m_collisionMask; [SerializeField] [HideInInspector] private Collider2D m_collider; private List<Collision2D> m_collisions; public int Count => m_collisions.Count; public Collision2D GetCollision(int index) { if (Count == 0) { return null; } else { return m_collisions[index]; } } public void Enable() { m_collider.enabled = true; } public void Disable() { m_collider.enabled = false; m_collisions.Clear(); } public void Clear() => m_collisions.Clear(); private void Add(Collision2D collision) { if (m_collisionMask == (m_collisionMask | 1 << collision.gameObject.layer)) { m_collisions.Add(collision); } } private void Awake() => m_collisions = new List<Collision2D>(); private void OnCollisionEnter2D(Collision2D collision) => Add(collision); private void OnCollisionStay2D(Collision2D collision) { for (int i = 0; i < m_collisions.Count; i++) { if (m_collisions[i].gameObject == collision.gameObject) { m_collisions[i] = collision; return; } } //This is incase the collision is not Loaded // Add(collision); } private void OnCollisionExit2D(Collision2D collision) { for (int i = 0; i < m_collisions.Count; i++) { if (m_collisions[i].gameObject == collision.gameObject) { m_collisions.RemoveAt(i); return; } } } private void OnValidate() { m_collider = GetComponent<Collider2D>(); } } }
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 SCANINOUTBL; namespace ScanINOUTVer2 { public partial class frmPOLog : Form { public frmPOLog() { InitializeComponent(); } private void AddToPO_Load(object sender, EventArgs e) { dtpFrom.Value = DateTime.Now.AddMonths(-1); dtpTo.Value = DateTime.Now; dtpFrom.MinDate = dtpTo.MinDate = new DateTime(2015, 1, 1); dtpTo.MaxDate = dtpFrom.MaxDate = dtpTo.Value; dgvItems.AutoGenerateColumns = false; dgvItems.DataSource = Inventory.GetAllPerPerioud(dtpFrom.Value, dtpTo.Value); } private void btnCreatePO_Click(object sender, EventArgs e) { if (dtpFrom.Value>dtpTo.Value) { MessageBox.Show("Date from must be smaller tham Date to"); return; } dgvItems.AutoGenerateColumns = false; dgvItems.DataSource = Inventory.GetAllPerPerioud(dtpFrom.Value, dtpTo.Value); } } }
using Allyn.Domain.Models.Front; using Allyn.Infrastructure; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Allyn.Domain.Repositories.Front { /// <summary> /// 表示"产品类别"仓储类型. /// </summary> public interface ICategoryRepository { /// <summary> /// 获取一个产品类别. /// </summary> /// <param name="key">产品类别标识</param> /// <returns>产品类别</returns> Category GetCategoryByKey(Guid key); /// <summary> /// 获取所有产品类别 /// </summary> /// <returns>所有产品类别集合.</returns> IEnumerable<Category> GetCategorys(); /// <summary> /// 获取产品类别分页集合. /// </summary> /// <param name="pageNumber">页码</param> /// <param name="pageSize">分页大小</param> /// <returns>产品类别分页集合</returns> PagedResult<Category> GetCategorys(int pageNumber, int pageSize); /// <summary> /// 获取产品类别分页集合. /// </summary> /// <param name="strWhere">条件</param> /// <param name="pageNumber">页码</param> /// <param name="pageSize">分页大小</param> /// <returns>产品类别分页集合</returns> PagedResult<Category> GetCategorys(string strWhere, int pageNumber, int pageSize); /// <summary> /// 更新一个产品类别. /// </summary> /// <param name="model">产品类别聚合给类型</param> void UpdateCategory(Category model); /// <summary> /// 新增一个产品类别 /// </summary> /// <param name="model">产品类别聚合给类型</param> void AddCategory(Category model); /// <summary> /// 根据指定标识列表删除产品类别. /// </summary> /// <param name="keys">产品类别标识列表</param> void DeleteCategory(List<Guid> keys); } }
namespace gView.GraphicsEngine.GdiPlus.Extensions { static class FontStyleExtensions { static public System.Drawing.FontStyle ToGdiFontStyle(this FontStyle fontStyle) { var result = System.Drawing.FontStyle.Regular; if (fontStyle.HasFlag(FontStyle.Bold)) { result |= System.Drawing.FontStyle.Bold; } if (fontStyle.HasFlag(FontStyle.Italic)) { result |= System.Drawing.FontStyle.Italic; } if (fontStyle.HasFlag(FontStyle.Strikeout)) { result |= System.Drawing.FontStyle.Strikeout; } if (fontStyle.HasFlag(FontStyle.Underline)) { result |= System.Drawing.FontStyle.Underline; } return result; } } }
using System; using System.Collections.Generic; namespace Microsoft.UnifiedPlatform.Service.Common.DefaultHttpClient { public class RetryProtocol { public int MaxRetryCount { get; set; } public TimeSpan Timeout { get; set; } public TimeSpan MaxBackOffInterval { get; set; } public List<string> TransientFailureCodes { get; set; } public RetryProtocol() { //Set Default Retry values MaxRetryCount = 1; Timeout = TimeSpan.FromSeconds(30); MaxBackOffInterval = TimeSpan.FromMilliseconds(250); TransientFailureCodes = new List<string>(); } } }
using System; using HTTPServer.core; using System.Net.Sockets; using System.Collections.Generic; namespace HTTPServer.app { public class Driver { private static Server server = new Server(); private static int port = 0; private static string directoryPath = ""; private static string loggingFile = ""; private static int timeout = 0; public static void Main(string[] args) { HandleCommands(args); var pathContents = new ConcretePathContents(directoryPath); var requestHandler = AddFunctionality(pathContents); var info = new ServerInfo(port, pathContents,requestHandler,timeout); server.Start(info); server.HandleClients(); } private static IHttpHandler AddFunctionality(IPathContents pathContents) { var requestRouter = new RequestRouter(pathContents); requestRouter.AddAction(new ContentsCriteria(), new GetContents(pathContents)); requestRouter.AddAction(new PostCriteria(), new PostContents(pathContents)); requestRouter.AddAction(new PutCriteria(), new PutContents(pathContents)); requestRouter.AddAction(new DeleteCriteria(), new DeleteContents(pathContents)); IHttpHandler versionFilter = new VersionNotSupportedFilter(requestRouter); IHttpHandler malformedFilter = new BadRequestFilter(pathContents, versionFilter); return malformedFilter; } private static void HandleCommands(string[] args) { for (var i = 0; i < args.Length; i++) { switch (args[i]) { case "-p": port = Int32.Parse(args[i + 1]); break; case "-d": directoryPath = args[i + 1]; break; case "-t": timeout = Int32.Parse(args[i + 1]); break; case ">": loggingFile = args[i + 1]; break; } } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ShooterBehaviour : MonoBehaviour { Rigidbody2D m_Rigidbody; ShooterPatrol patrol; ShooterShooting shoot; GameObject player; //Controladores de comportamientos public bool patrolling; public bool shooting; void Start() { patrolling = true; shooting = false; player = GameObject.FindWithTag("Player1"); m_Rigidbody = GetComponent<Rigidbody2D>(); patrol = GetComponent<ShooterPatrol>(); shoot = GetComponent<ShooterShooting>(); shoot.enabled = false; } void Update() { if (patrolling == true) { patrol.enabled = true; } else { patrol.enabled = false; } if (shooting == true) { shoot.enabled = true; Vector3 direction = this.transform.position - player.transform.position; var distance = direction.magnitude; if(distance >= 10) { shooting = false; patrolling = true; } } else { shoot.enabled = false; } } private void OnCollisionEnter2D(Collision2D collision) { if (patrolling == true) { if (collision.gameObject.tag == "Player2") { patrolling = false; shooting = true; } } } }
using PyTK.CustomElementHandler; using Microsoft.Xna.Framework; using StardewValley; using StardewValley.TerrainFeatures; using System.Collections.Generic; using Microsoft.Xna.Framework.Graphics; using SObject = StardewValley.Object; namespace MoreGrassStarters { public class GrassStarterItem : SObject, ISaveElement { private static readonly Texture2D tex = Game1.content.Load<Texture2D>("TerrainFeatures\\grass"); public static Texture2D tex2; private int whichGrass = 1; public static int ExtraGrassTypes => tex2 == null ? 0 : tex2.Height / 20; public GrassStarterItem() { } public GrassStarterItem(int which) { whichGrass = which; name = $"Grass ({which})"; Price = 100; ParentSheetIndex = 297; } public override Item getOne() { return new GrassStarterItem(whichGrass); } public override bool canBePlacedHere(GameLocation l, Vector2 tile) { return !l.objects.ContainsKey(tile) && !l.terrainFeatures.ContainsKey(tile); } public override bool isPlaceable() { return true; } public override bool placementAction(GameLocation location, int x, int y, StardewValley.Farmer who = null) { Vector2 index1 = new Vector2((float)(x / Game1.tileSize), (float)(y / Game1.tileSize)); this.health = 10; this.owner.Value = who?.UniqueMultiplayerID ?? Game1.player.UniqueMultiplayerID; if (location.objects.ContainsKey(index1) || location.terrainFeatures.ContainsKey(index1)) return false; location.terrainFeatures.Add(index1, (TerrainFeature)new CustomGrass(whichGrass, 4)); Game1.playSound("dirtyHit"); return true; } public override void draw(SpriteBatch b, int x, int y, float alpha = 1) { Texture2D tex = GrassStarterItem.tex; int texOffset = 20 + whichGrass * 20; if (whichGrass >= 5) { tex = tex2; texOffset = 20 * (whichGrass - 5); } b.Draw(tex, new Rectangle(x, y, 16, 20), new Rectangle(0, texOffset, 16, 20), Color.White); } public override void drawWhenHeld(SpriteBatch b, Vector2 pos, StardewValley.Farmer f) { Texture2D tex = GrassStarterItem.tex; int texOffset = 20 + whichGrass * 20; if (whichGrass >= 5) { tex = tex2; texOffset = 20 * (whichGrass - 5); } b.Draw(tex, pos - new Vector2(-4, 24), new Rectangle(0, texOffset, 16, 20), Color.White, 0, Vector2.Zero, 4, SpriteEffects.None, (f.getStandingY() + 3) / 10000f); } public override void drawInMenu(SpriteBatch b, Vector2 pos, float scale, float transparency, float layerDepth, bool drawStackNumber, Color color, bool drawShadow) { Texture2D tex = GrassStarterItem.tex; int texOffset = 20 + whichGrass * 20; if (whichGrass >= 5) { tex = tex2; texOffset = 20 * (whichGrass - 5); } b.Draw(tex, pos + new Vector2( 4, 0 ), new Rectangle(0, texOffset, 16, 20), Color.White, 0, Vector2.Zero, 4 * scale, SpriteEffects.None, layerDepth); if (drawStackNumber && this.maximumStackSize() > 1 && ((double)scale > 0.3 && this.Stack != int.MaxValue) && this.Stack > 1) Utility.drawTinyDigits(this.Stack, b, pos + new Vector2((float)(Game1.tileSize - Utility.getWidthOfTinyDigitString(this.stack, 3f * scale)) + 3f * scale, (float)((double)Game1.tileSize - 18.0 * (double)scale + 2.0)), 3f * scale, 1f, Color.White); } // Custom Element Handler public object getReplacement() { return new SObject(297, stack); } public Dictionary<string, string> getAdditionalSaveData() { return new Dictionary<string, string> { ["whichGrass"] = whichGrass.ToString() }; } public void rebuild(Dictionary<string, string> additionalSaveData, object replacement) { whichGrass = int.Parse(additionalSaveData["whichGrass"]); name = $"Grass ({whichGrass})"; Price = 100; ParentSheetIndex = 297; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Different { class Program { static void Main(string[] args) { //Listing01.MainListing01(); //Listing02.MainListing02(); //Listing03.MainListing03(); //Listing04.MainListing04(); //Listing05.MainListing05(); //Listing0607.MainListing0607(); //Listing08.MainListing08(); //Listing09.MainListing09(); //Listing10.MainListing10(); //Listing11.MainListing11(); //Listing12.MainListing12(); //Exc01.MainExc01(); //??? граф интерфейс //Exc02.MainExc02(); //Exc03.MainExc03(); //считается, что 30 дней в месяце //Exc04.MainExc04(); //Exc05.MainExc05(); //Exc06.MainExc06(); //Exc07.MainExc07(); //Exc08.MainExc08(); //Exc09.MainExc09(); //Exc10.MainExc10(); } } }
using UnityEngine; using UnityAtoms.MonoHooks; namespace UnityAtoms.MonoHooks { /// <summary> /// Value List of type `CollisionGameObject`. Inherits from `AtomValueList&lt;CollisionGameObject, CollisionGameObjectEvent&gt;`. /// </summary> [EditorIcon("atom-icon-piglet")] [CreateAssetMenu(menuName = "Unity Atoms/Value Lists/CollisionGameObject", fileName = "CollisionGameObjectValueList")] public sealed class CollisionGameObjectValueList : AtomValueList<CollisionGameObject, CollisionGameObjectEvent> { } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Mojang.Minecraft.Protocol.Providers { internal sealed class PackageMaker { private FieldMaker _FieldMaker; private int _TypeCode; public PackageMaker(int typeCode, FieldMaker fieldMaker) { _TypeCode = typeCode; _FieldMaker = fieldMaker; } public byte[] MakePackage() { var packageList = new List<byte>(); var packageTypeCode = new VarInt((uint)_TypeCode); packageList.AddRange(PackageFieldToByteList(packageTypeCode)); packageList.AddRange(_FieldMaker.GetBytes()); var entityLength = new VarInt((uint)packageList.Count); packageList.InsertRange(0, PackageFieldToByteList(entityLength)); return packageList.ToArray(); } private static List<byte> PackageFieldToByteList(IPackageField bitConvertible) { var fieldMaker = new FieldMaker(); bitConvertible.AppendIntoField(fieldMaker); return new List<byte>(fieldMaker.GetBytes()); } public static int GetVariablePackageFieldLength(IPackageField bitConvertible) { return PackageFieldToByteList(bitConvertible).Count; } } }
using System; using Terraria; using Terraria.ID; using Terraria.ModLoader; namespace Caserraria.Items.InventoryItems { public class Roblox : ModItem { public override void SetStaticDefaults() { DisplayName.SetDefault("OOF.mp3"); Tooltip.SetDefault("Favorite to activate" + Environment.NewLine + "Makes you go OOF"); } public override void SetDefaults() { item.width = 26; item.height = 30; item.value = Item.sellPrice(gold: 10); item.rare = 11; } public override void UpdateInventory(Player player) { if (item.favorited) { MyPlayer p = player.GetModPlayer<MyPlayer>(); p.Oof = true; } } public override void AddRecipes() { ModRecipe recipe = new ModRecipe(mod); recipe.AddIngredient(ItemID.MusicBox); recipe.AddIngredient(ItemID.SoulofFright, 3); recipe.AddTile(TileID.MythrilAnvil); recipe.SetResult(this); recipe.AddRecipe(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DictionaryDataStruct { class Program { private static Dictionary<string, object> dict; private static void Add(string strKey, object dataType) { if (!dict.ContainsKey(strKey)) { dict.Add(strKey, dataType); } else { dict[strKey] = dataType; } } public static T GetAnyValue<T>(string strKey) { object obj; T retType; dict.TryGetValue(strKey, out obj); try { retType = (T)obj; } catch { retType = default(T); } return retType; } static void Main(string[] args) { dict = new Dictionary<string, object>(); Add("pie", 3.4123); Add("Apple Tart", "340 calories"); Add("Poltry", "Fried chickens"); Add("i", 7); Console.WriteLine("pi = " + GetAnyValue<double>("pi")); Console.WriteLine("Apple Tart = " + GetAnyValue<string>("Apple Tart")); Console.WriteLine("Poltry = " + GetAnyValue<string>("Poltry")); Console.WriteLine("i = " + GetAnyValue<int>("i")); Console.ReadLine(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AlgorithmProblems.Stack_and_Queue.Queue_Helper { public class CircularQueue<T> { // When the array is empty we will make the head -1 private int HeadIndex = -1; private int TailIndex = 0; private T[] array = null; public CircularQueue(int size) { array = new T[size]; } /// <summary> /// Add data in the array at the tail index and increment tail. /// Make sure that the array is not full /// </summary> /// <param name="data"></param> public void Enqueue(T data) { if(data == null) { return; } if(TailIndex == HeadIndex) { // This means the array is full throw new StackOverflowException(); } if(HeadIndex == -1) { // We will be adding our first element in the array // So we need to change the Head Index to the correct value HeadIndex = TailIndex; } array[TailIndex] = data; TailIndex = (TailIndex + 1) % array.Length; } /// <summary> /// Remove the data from the HeadIndex and increment HeadIndex /// Make sure that the array is not empty /// </summary> /// <returns></returns> public T Dequeue() { if(HeadIndex == -1) { // The array is empty throw new Exception("Stack is empty"); } T dataToReturn = array[HeadIndex]; if((HeadIndex+1)%array.Length == TailIndex) { HeadIndex = -1; } else { HeadIndex = (HeadIndex + 1) % array.Length; } return dataToReturn; } public int Count { get { if(HeadIndex == -1) { // The queue is empty return 0; } if(HeadIndex < TailIndex) { return TailIndex - HeadIndex; } else if(TailIndex < HeadIndex) { return array.Length - HeadIndex + TailIndex; } else { // The queue is full return array.Length; } } } public override string ToString() { if(HeadIndex == -1) { // Queue is empty return ""; } StringBuilder sb = new StringBuilder(); for (int i = 0; i < Count; i++) { int arrayindex = (HeadIndex + i) % array.Length; sb.Append(array[arrayindex] + " , "); } return sb.ToString(); } } public class TestCircularQueue { public static void TestCircularQueueWithDifferentCases() { CircularQueue<int> cq = new CircularQueue<int>(5); for (int i = 0; i < 5; i++) { cq.Enqueue(i); Console.WriteLine("The contents of the queue are : {0}", cq.ToString()); Console.WriteLine("The number of items in the queue is : {0}", cq.Count); } Console.WriteLine("The contents of the queue are: {0}", cq.ToString()); try { // Over flow should happen here. cq.Enqueue(3); } catch(Exception e) { Console.WriteLine(e.Message); } for (int i = 4; i >=0 ; i--) { Console.WriteLine("The item dequeued is : "+ cq.Dequeue()); Console.WriteLine("The contents of the queue are : {0}", cq.ToString()); Console.WriteLine("The number of items in the queue is : {0}", cq.Count); } try { // Empty queue should throw exception cq.Dequeue(); } catch (Exception e) { Console.WriteLine(e.Message); } } } }
using System.Threading; using System.Web.Mvc; using DevExpress.Web.Mvc; namespace DevExpress.Web.Demos { public partial class TreeListController : DemoController { [HttpGet] public ActionResult DataBinding() { Session["TreeListState"] = null; Session["ShowServiceColumns"] = false; return DemoView("DataBinding", DepartmentsProvider.GetDepartments()); } [HttpPost] public ActionResult DataBinding(bool showServiceColumns) { Session["ShowServiceColumns"] = showServiceColumns; return DemoView("DataBinding", DepartmentsProvider.GetDepartments()); } public ActionResult DataBindingPartial() { if(DevExpressHelper.IsCallback) // Intentionally pauses server-side processing, // to demonstrate the Loading Panel functionality. Thread.Sleep(500); return PartialView("DataBindingPartial", DepartmentsProvider.GetDepartments()); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using IconCreator.Core.Models; using System.Windows.Input; using System.Windows.Forms; using IconCreator.Core.Infrastructure; using System.ComponentModel; using System.Windows; using System.IO; using GalaSoft.MvvmLight.Command; using IconCreator.WPF.UI.Models; using IconCreator.Services; using IconCreator.Core.Models.Interfaces; namespace IconCreator.WPF.UI.ViewModel { public class AlfatouchPageViewModel : WizardPageViewModelBase { #region Fields RelayCommand _openDatabaseDialogCommand; RelayCommand _openWorkIconsDialogCommand; private readonly ISettingsService _settingsService; private readonly IDatabaseService _databaseService; private readonly IUnitOfWork _unitOfWork; private string _database; private string _workicons; #endregion // Fields public AlfatouchPageViewModel(IconCreatorSettings iconCreatorSettings, ISettingsService settingsService, IUnitOfWork unitOfWork, IDatabaseService databaseService) : base(iconCreatorSettings) { _settingsService = settingsService; _unitOfWork = unitOfWork; _databaseService = databaseService; } #region Commands #region OpenDatabaseDialogCommand public NotifyTaskCompletion<bool> IsValidDatabase { get; private set; } public ICommand OpenDatabaseDialogCommand { get { if (_openDatabaseDialogCommand == null) _openDatabaseDialogCommand = new RelayCommand(() => this.OpenDatabaseDialog()); return _openDatabaseDialogCommand; } } private void OpenDatabaseDialog() { OpenFileDialog dialog = new OpenFileDialog(); dialog.Filter = "Database files (*.mdb) | *.mdb"; if (dialog.ShowDialog() == DialogResult.OK) { Database = dialog.FileName; _unitOfWork.SetConnectionString(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + dialog.FileName); IsValidDatabase = new NotifyTaskCompletion<bool>( _databaseService.IsValid()); } RaisePropertyChanged("IsValidDatabase"); } #endregion // OpenDatabaseDialogCommand #region OpenWorkIconsDialogCommand public ICommand OpenWorkIconsDialogCommand { get { if (_openWorkIconsDialogCommand == null) _openWorkIconsDialogCommand = new RelayCommand(() => this.OpenWorkIconsDialog()); return _openWorkIconsDialogCommand; } } public string Database { get { return _database; } set { _database = value; RaisePropertyChanged("Database"); } } public string Workicons { get { return _workicons; } set { _workicons = value; RaisePropertyChanged("Workicons"); RaisePropertyChanged("IsValidWorkicons"); } } public bool IsValidWorkicons { get { return Directory.Exists(_workicons); } } private void OpenWorkIconsDialog() { FolderBrowserDialog dialog = new FolderBrowserDialog(); if (dialog.ShowDialog() == DialogResult.OK) { Workicons = dialog.SelectedPath; } } #endregion // OpenDatabaseDialogCommand #endregion // Commands public override string DisplayName { get { return "DATABASE"; } } internal override bool IsValid() { if (string.IsNullOrWhiteSpace(Database)) return false; if (_databaseService.IsValid().IsFaulted) return false; return _databaseService.IsValid().Result && IsValidWorkicons; } } }
using Boxofon.Web.Helpers; using NLog; using Nancy; namespace Boxofon.Web.Mailgun { public class RequestValidator { private static readonly Logger Logger = LogManager.GetCurrentClassLogger(); public bool IsValidRequest(NancyContext context, string apiKey) { var timestamp = (int)context.Request.Form.timestamp; var token = (string)context.Request.Form.token; var signature = (string)context.Request.Form.signature; var unencoded = string.Format("{0}{1}", timestamp, token); var encoded = unencoded.HmacSha256HexDigestEncode(apiKey); if (encoded != signature) { Logger.Info("Validation of Mailgun request failed. Timestamp: '{0}' Token: '{1}' Signature: '{2}' Computed: '{3}'", timestamp, token, signature, encoded); return false; } return true; } } }
using System; using System.Collections.Generic; using System.Windows.Forms; using AI.Functions; using AI.Neurons; using System.IO; namespace FinancialInstumentsAI.Dialogs { public sealed partial class AISettings : Form { private static AISettings instance; public static List<int> Layer { get; set; } public static INeuronInitilizer Init { get; set; } public static IActivationFunction Activ { get; set; } public static double LearnerRate { get; set; } public static double LearnerMomentum { get; set; } public static int IterationsCount { get; set; } public static List<KeyValuePair<Indi, int>> Indicator { get; set; } private AISettings() { InitializeComponent(); initFuncComboBox.DataSource = Enum.GetNames(typeof(Initialization)); activFuncComboBox.DataSource = Enum.GetNames(typeof(Activation)); constValueTextBox.Enabled = false; Indicator = new List<KeyValuePair<Indi, int>>(); } public static AISettings Instance { get { return instance ?? (instance = new AISettings()); } } private void btnOK_Click(object sender, EventArgs e) { AssignValue(); var a = this.Owner as MainForm; if (a != null) a.SetSettings(); this.Hide(); } private void apply_Click(object sender, EventArgs e) { AssignValue(); var a = this.Owner as MainForm; if (a != null) a.SetSettings(); } private void initFuncComboBox_SelectedIndexChanged(object sender, EventArgs e) { if (initFuncComboBox.SelectedIndex == 1) { activFuncComboBox.SelectedIndex = 1; activFuncComboBox.Enabled = false; } else { activFuncComboBox.Enabled = true; } if (initFuncComboBox.SelectedIndex == 2) { constValueTextBox.Enabled = true; } else { constValueTextBox.Enabled = false; } } private void AssignValue() { switch (initFuncComboBox.SelectedIndex) { case (0): Init = new RandomInitializer(); break; case (1): Init = new OptimalRangeRandomInitializer(Activ = new BipolarSigmoid((double)alphaNumeric.Value)); break; case (2): Init = new ConstInitializer(double.Parse(constValueTextBox.Text)); break; default: Init = null; break; } if (activFuncComboBox.SelectedIndex == 1) { Activ = new BipolarSigmoid((double)alphaNumeric.Value); } else { Activ = new Sigmoid((double)alphaNumeric.Value); } LearnerRate = (double)rateNumeric.Value; LearnerMomentum = (double)momentumNumeric.Value; int firstLayer = (int)windowSize.Value; firstLayer += AddIndicators(); Layer = new List<int> { firstLayer }; if (layerCountCheckBox.Checked) { for (int i = 0; i < (int)layersNumeric.Value - 2; i++) { Layer.Add((int)windowSize.Value * 2); } } else { for (int i = 0; i < (int)layersNumeric.Value - 2; i++) { var neuron = new NeuronCounts { Text = "Layer no. " + i + " count" }; DialogResult res = neuron.ShowDialog(this); if (res == DialogResult.OK) { Layer.Add(neuron.Value); } } } Layer.Add(1); int iterations; if (!int.TryParse(iterationsTextBox.Text, out iterations)) { iterations = 1000; } IterationsCount = iterations; } private int AddIndicators() { int toAddForFirstLayer = 0; Indicator.Clear(); if (sma.CheckState == CheckState.Checked) { Indicator.Add(new KeyValuePair<Indi, int>(Indicators.Indicators.SMA, (int)smaPeriod.Value)); toAddForFirstLayer++; } if (wma.CheckState == CheckState.Checked) { Indicator.Add(new KeyValuePair<Indi, int>(Indicators.Indicators.WMA, (int)wmaPeriod.Value)); toAddForFirstLayer++; } if (ema.CheckState == CheckState.Checked) { Indicator.Add(new KeyValuePair<Indi, int>(Indicators.Indicators.EMA, (int)emaPeriod.Value)); toAddForFirstLayer++; } if (roc.CheckState == CheckState.Checked) { Indicator.Add(new KeyValuePair<Indi, int>(Indicators.Indicators.ROC, (int)rocPeriod.Value)); toAddForFirstLayer++; } if (macd.CheckState == CheckState.Checked) { Indicator.Add(new KeyValuePair<Indi, int>(Indicators.Indicators.MACD, (int)macdPeriod.Value)); toAddForFirstLayer++; } if (oscill.CheckState == CheckState.Checked) { Indicator.Add(new KeyValuePair<Indi, int>(Indicators.Indicators.Oscillator, (int)oscillValue.Value)); toAddForFirstLayer++; } return toAddForFirstLayer; } private void btnCancel_Click(object sender, EventArgs e) { Hide(); } #region researchMethod private void tests() { //using (var writer = new StreamWriter("1hidelayer.txt")) //{ // Init = new RandomInitializer(); // Activ = new BipolarSigmoid((double)2.0); // LearnerRate = 0.3; // LearnerMomentum = 0.0; // string column = "window|hide layer 1|teach error|predic error 30%|10 values|5 |1|predic error 30%|10 values|5 |1"; // writer.WriteLine(column); // for (int j = 2; j < 10; j++) // { // for (int i = 1; i < 21; i++) // { // string toFile = j + "|" + i + "|"; // Layer = new List<int> { j }; // Layer.Add(i); // Layer.Add(1); // var a = this.Owner as MainForm; // if (a != null) // { // a.SetSettings(); // toFile += a.Teach(false).ToString("F6") + "|"; // toFile += a.Predict(false, true).ToString("F6") + "|"; // toFile += a.Predict(false, true, 10).ToString("F6") + "|"; // toFile += a.Predict(false, true, 5).ToString("F6") + "|"; // toFile += a.Predict(false, true, 1).ToString("F6") + "|"; // toFile += a.Predict(false, false).ToString("F6") + "|"; // toFile += a.Predict(false, false, 10).ToString("F6") + "|"; // toFile += a.Predict(false, false, 5).ToString("F6") + "|"; // toFile += a.Predict(false, false, 1).ToString("F6"); // } // writer.WriteLine(toFile); // } // } //} using (var writer = new StreamWriter("2hidelayer100.txt")) { Init = new OptimalRangeRandomInitializer(Activ = new BipolarSigmoid(2.0)); LearnerRate = 0.3; LearnerMomentum = 0.0; IterationsCount = 100; string column = "window|hide layer 1|hide layer 2|teach error|predic error 30%|10 values|5 |1|predic error 30%|10 values|5 |1"; writer.WriteLine(column); for (int j = 2; j < 10; j++) { for (int i = 1; i < 21; i++) { for (int k = 1; k < 21; k++) { string toFile = j + "|" + i + "|" + k + "|"; Layer = new List<int> { j }; Layer.Add(i); Layer.Add(k); Layer.Add(1); var a = this.Owner as MainForm; if (a != null) { a.SetSettings(); toFile += a.Teach(false).ToString("F6") + "|"; toFile += a.Predict(false, true).ToString("F6") + "|"; toFile += a.Predict(false, true, 10).ToString("F6") + "|"; toFile += a.Predict(false, true, 5).ToString("F6") + "|"; toFile += a.Predict(false, true, 1).ToString("F6") + "|"; toFile += a.Predict(false, false).ToString("F6") + "|"; toFile += a.Predict(false, false, 10).ToString("F6") + "|"; toFile += a.Predict(false, false, 5).ToString("F6") + "|"; toFile += a.Predict(false, false, 1).ToString("F6"); } writer.WriteLine(toFile); } } } } using (var writer = new StreamWriter("2hidelayer200.txt")) { Init = new OptimalRangeRandomInitializer(Activ = new BipolarSigmoid(2.0)); LearnerRate = 0.3; LearnerMomentum = 0.0; IterationsCount = 500; string column = "window|hide layer 1|hide layer 2|teach error|predic error 30%|10 values|5 |1|predic error 30%|10 values|5 |1"; writer.WriteLine(column); for (int j = 2; j < 10; j++) { for (int i = 1; i < 21; i++) { for (int k = 1; k < 21; k++) { string toFile = j + "|" + i + "|" + k + "|"; Layer = new List<int> { j }; Layer.Add(i); Layer.Add(k); Layer.Add(1); var a = this.Owner as MainForm; if (a != null) { a.SetSettings(); toFile += a.Teach(false).ToString("F6") + "|"; toFile += a.Predict(false, true).ToString("F6") + "|"; toFile += a.Predict(false, true, 10).ToString("F6") + "|"; toFile += a.Predict(false, true, 5).ToString("F6") + "|"; toFile += a.Predict(false, true, 1).ToString("F6") + "|"; toFile += a.Predict(false, false).ToString("F6") + "|"; toFile += a.Predict(false, false, 10).ToString("F6") + "|"; toFile += a.Predict(false, false, 5).ToString("F6") + "|"; toFile += a.Predict(false, false, 1).ToString("F6"); } writer.WriteLine(toFile); } } } } //using (var writer = new StreamWriter("1hidelayerRandomInit.txt")) //{ // Init = new RandomInitializer(); // Activ = new BipolarSigmoid((double)2.0); // LearnerRate = 0.3; // LearnerMomentum = 0.0; // IterationsCount = 500; // writer.WriteLine("func activ -BipolarSigmoid((double)2.0) , init - RandomInitializer() 500 iteracji"); // string column = "window|hide layer 1|teach error|predic error 30%|10 values|5 |1|predic error 30%|10 values|5 |1"; // writer.WriteLine(column); // for (int j = 2; j < 10; j++) // { // for (int i = 1; i < 21; i++) // { // string toFile = j + "|" + i + "|"; // Layer = new List<int> { j }; // Layer.Add(i); // Layer.Add(1); // var a = this.Owner as MainForm; // if (a != null) // { // a.SetSettings(); // toFile += a.Teach(false).ToString("F6") + "|"; // toFile += a.Predict(false, true).ToString("F6") + "|"; // toFile += a.Predict(false, true, 10).ToString("F6") + "|"; // toFile += a.Predict(false, true, 5).ToString("F6") + "|"; // toFile += a.Predict(false, true, 1).ToString("F6") + "|"; // toFile += a.Predict(false, false).ToString("F6") + "|"; // toFile += a.Predict(false, false, 10).ToString("F6") + "|"; // toFile += a.Predict(false, false, 5).ToString("F6") + "|"; // toFile += a.Predict(false, false, 1).ToString("F6"); // } // writer.WriteLine(toFile); // } // } //} //using (var writer = new StreamWriter("1hidelayerConstInit.txt")) //{ // Init = new ConstInitializer(5); // Activ = new BipolarSigmoid((double)2.0); // LearnerRate = 0.3; // LearnerMomentum = 0.0; // IterationsCount = 500; // string column = "window|hide layer 1|teach error|predic error 30%|10 values|5 |1|predic error 30%|10 values|5 |1"; // writer.WriteLine("func activ -BipolarSigmoid((double)2.0) , init - ConstInitializer(5) 500 iteracji"); // writer.WriteLine(column); // for (int j = 2; j < 10; j++) // { // for (int i = 1; i < 21; i++) // { // string toFile = j + "|" + i + "|"; // Layer = new List<int> { j }; // Layer.Add(i); // Layer.Add(1); // var a = this.Owner as MainForm; // if (a != null) // { // a.SetSettings(); // toFile += a.Teach(false).ToString("F6") + "|"; // toFile += a.Predict(false, true).ToString("F6") + "|"; // toFile += a.Predict(false, true, 10).ToString("F6") + "|"; // toFile += a.Predict(false, true, 5).ToString("F6") + "|"; // toFile += a.Predict(false, true, 1).ToString("F6") + "|"; // toFile += a.Predict(false, false).ToString("F6") + "|"; // toFile += a.Predict(false, false, 10).ToString("F6") + "|"; // toFile += a.Predict(false, false, 5).ToString("F6") + "|"; // toFile += a.Predict(false, false, 1).ToString("F6"); // } // writer.WriteLine(toFile); // } // } //} //using (var writer = new StreamWriter("1hidelayerSigmoid.txt")) //{ // Init = new RandomInitializer(); // Activ = new Sigmoid(2.0); // LearnerRate = 0.3; // LearnerMomentum = 0.0; // IterationsCount = 500; // string column = "window|hide layer 1|teach error|predic error 30%|10 values|5 |1|predic error 30%|10 values|5 |1"; // writer.WriteLine("func activ -Sigmoid(2.0) , init - RandomInitializer() 500 iteracji"); // writer.WriteLine(column); // for (int j = 2; j < 10; j++) // { // for (int i = 1; i < 21; i++) // { // string toFile = j + "|" + i + "|"; // Layer = new List<int> { j }; // Layer.Add(i); // Layer.Add(1); // var a = this.Owner as MainForm; // if (a != null) // { // a.SetSettings(); // toFile += a.Teach(false).ToString("F6") + "|"; // toFile += a.Predict(false, true).ToString("F6") + "|"; // toFile += a.Predict(false, true, 10).ToString("F6") + "|"; // toFile += a.Predict(false, true, 5).ToString("F6") + "|"; // toFile += a.Predict(false, true, 1).ToString("F6") + "|"; // toFile += a.Predict(false, false).ToString("F6") + "|"; // toFile += a.Predict(false, false, 10).ToString("F6") + "|"; // toFile += a.Predict(false, false, 5).ToString("F6") + "|"; // toFile += a.Predict(false, false, 1).ToString("F6"); // } // writer.WriteLine(toFile); // } // } //} // using (var writer = new StreamWriter("wskazniki.txt")) // { // Init = new OptimalRangeRandomInitializer(Activ = new BipolarSigmoid(2.0)); // ////Activ = new BipolarSigmoid((double)2.0); // LearnerRate = 0.3; // LearnerMomentum = 0.0; // IterationsCount = 100; // writer.WriteLine("indicators|argument|teach error|predic error 30%|10 values|5 |1|predic error 30%|10 values|5 |1"); // for (int j = 0; j < 6; j++) // { // for (int i = 0; i < 30; i++) // { // string toFile = ""; // switch (j) // { // case 0: // Indicator.Clear(); // Indicator.Add(new KeyValuePair<Indi, int>(Indicators.Indicators.SMA, i)); // toFile += "sma|"; // break; // case 1: // Indicator.Clear(); // Indicator.Add(new KeyValuePair<Indi, int>(Indicators.Indicators.WMA, i)); // toFile += "wma|"; // break; // case 2: // Indicator.Clear(); // Indicator.Add(new KeyValuePair<Indi, int>(Indicators.Indicators.EMA, i)); // toFile += "ema|"; // break; // case 3: // Indicator.Clear(); // Indicator.Add(new KeyValuePair<Indi, int>(Indicators.Indicators.ROC, i)); // toFile += "roc|"; // break; // case 4: // Indicator.Clear(); // Indicator.Add(new KeyValuePair<Indi, int>(Indicators.Indicators.MACD, i)); // toFile += "macd|"; // break; // case 5: // Indicator.Clear(); // Indicator.Add(new KeyValuePair<Indi, int>(Indicators.Indicators.Oscillator, 3 + i)); // toFile += "oscil|"; // break; // } // toFile += i + "|"; // Layer = new List<int> { 4 }; // Layer.Add(12); // Layer.Add(1); // var a = this.Owner as MainForm; // if (a != null) // { // a.SetSettings(); // toFile += a.Teach(false).ToString("F6") + "|"; // toFile += a.Predict(false, true).ToString("F6") + "|"; // toFile += a.Predict(false, true, 10).ToString("F6") + "|"; // toFile += a.Predict(false, true, 5).ToString("F6") + "|"; // toFile += a.Predict(false, true, 1).ToString("F6") + "|"; // toFile += a.Predict(false, false).ToString("F6") + "|"; // toFile += a.Predict(false, false, 10).ToString("F6") + "|"; // toFile += a.Predict(false, false, 5).ToString("F6") + "|"; // toFile += a.Predict(false, false, 1).ToString("F6"); // } // writer.WriteLine(toFile); // } // } // } // using (var writer = new StreamWriter("parametry.txt")) // { // writer.WriteLine("rate|momentum|alpha|teach error|predic error 30%|10 values|5 |1|predic error 30%|10 values|5 |1"); // double alpha = 0; // LearnerRate = 0.0; // LearnerMomentum = 0.0; // IterationsCount = 100; // for (int j = 0; j < 50; j++) // { // Init = new OptimalRangeRandomInitializer(Activ = new BipolarSigmoid(2.0)); // //Activ = new BipolarSigmoid((double)2.0); // string toFile = LearnerRate + "|" + LearnerMomentum + "|2.0|"; // Layer = new List<int> { 3 }; // Layer.Add(12); // Layer.Add(1); // var a = this.Owner as MainForm; // if (a != null) // { // a.SetSettings(); // toFile += a.Teach(false).ToString("F6") + "|"; // toFile += a.Predict(false, true).ToString("F6") + "|"; // toFile += a.Predict(false, true, 10).ToString("F6") + "|"; // toFile += a.Predict(false, true, 5).ToString("F6") + "|"; // toFile += a.Predict(false, true, 1).ToString("F6") + "|"; // toFile += a.Predict(false, false).ToString("F6") + "|"; // toFile += a.Predict(false, false, 10).ToString("F6") + "|"; // toFile += a.Predict(false, false, 5).ToString("F6") + "|"; // toFile += a.Predict(false, false, 1).ToString("F6"); // } // writer.WriteLine(toFile); // LearnerRate += 0.05; // } // for (int j = 0; j < 50; j++) // { // Init = new OptimalRangeRandomInitializer(Activ = new BipolarSigmoid(2.0)); // //Activ = new BipolarSigmoid((double)2.0); // LearnerRate = 0.3; // string toFile = LearnerRate + "|" + LearnerMomentum + "|2.0|"; // Layer = new List<int> { 3 }; // Layer.Add(12); // Layer.Add(1); // var a = this.Owner as MainForm; // if (a != null) // { // a.SetSettings(); // toFile += a.Teach(false).ToString("F6") + "|"; // toFile += a.Predict(false, true).ToString("F6") + "|"; // toFile += a.Predict(false, true, 10).ToString("F6") + "|"; // toFile += a.Predict(false, true, 5).ToString("F6") + "|"; // toFile += a.Predict(false, true, 1).ToString("F6") + "|"; // toFile += a.Predict(false, false).ToString("F6") + "|"; // toFile += a.Predict(false, false, 10).ToString("F6") + "|"; // toFile += a.Predict(false, false, 5).ToString("F6") + "|"; // toFile += a.Predict(false, false, 1).ToString("F6"); // } // writer.WriteLine(toFile); // LearnerMomentum += 0.05; // } // for (int j = 0; j < 50; j++) // { // Init = new OptimalRangeRandomInitializer(Activ = new BipolarSigmoid(alpha)); // //Activ = new BipolarSigmoid((double)2.0); // LearnerRate = 0.3; // LearnerMomentum = 0.0; // string toFile = LearnerRate + "|" + LearnerMomentum + "|" + alpha + "|"; // Layer = new List<int> { 3 }; // Layer.Add(12); // Layer.Add(1); // var a = this.Owner as MainForm; // if (a != null) // { // a.SetSettings(); // toFile += a.Teach(false).ToString("F6") + "|"; // toFile += a.Predict(false, true).ToString("F6") + "|"; // toFile += a.Predict(false, true, 10).ToString("F6") + "|"; // toFile += a.Predict(false, true, 5).ToString("F6") + "|"; // toFile += a.Predict(false, true, 1).ToString("F6") + "|"; // toFile += a.Predict(false, false).ToString("F6") + "|"; // toFile += a.Predict(false, false, 10).ToString("F6") + "|"; // toFile += a.Predict(false, false, 5).ToString("F6") + "|"; // toFile += a.Predict(false, false, 1).ToString("F6"); // } // writer.WriteLine(toFile); // alpha += 0.1; // } // } } private void runTests_Click(object sender, EventArgs e) { tests(); } #endregion } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class parseadorCSV : MonoBehaviour { private TextAsset datos; }
namespace PizzaMore.BindingModels { public class SignUpBindingModel : BindingUserModel { } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ChampionsOfForest.Player { public class CustomCrafting { public static CustomCrafting instance; public Rerolling rerolling; public Reforging reforging; public enum CraftMode { Rerolling, Reforging, Repurposing, Upgrading} public CraftMode craftMode = CraftMode.Rerolling; public static void Init() { instance = new CustomCrafting(); instance.rerolling = new Rerolling(instance); instance.reforging = new Reforging(instance); } public CustomCrafting() { ingredients = new CraftingIngredient[9]; for (int i = 0; i < 9; i++) { ingredients[i]=(new CraftingIngredient()); } changedItem = new CraftingIngredient(); } public CraftingIngredient changedItem; public CraftingIngredient[] ingredients; public void ClearedItem() { } public class Reforging { public CustomCrafting cc; public readonly int IngredientCount = 3; public Reforging(CustomCrafting cc) { this.cc = cc; } public bool validRecipe { get { if (cc.changedItem.i == null) return false; int itemCount = 0; int rarity = cc.changedItem.i.Rarity; for (int i = 0; i < cc.ingredients.Length; i++) { if (cc.ingredients[i].i != null) { if (cc.ingredients[i].i.Rarity >= rarity) { itemCount++; } else { return false; } } } return itemCount == IngredientCount; } } public void PerformReforge() { if (cc.changedItem.i != null) { if (validRecipe) { int lvl = cc.changedItem.i.level; var v = ItemDataBase.ItemBases.Where(x => x.Value.ID != cc.changedItem.i.ID && x.Value.Rarity == cc.changedItem.i.Rarity).Select(x => x.Value).ToArray(); ; var ib = v[UnityEngine.Random.Range(0, v.Length)]; var newItem = new Item(ib, 1, 0, false) { level = lvl, }; newItem.RollStats(); Inventory.Instance.ItemList[cc.changedItem.pos] = newItem; cc.changedItem.i = newItem; Effects.Sound_Effects.GlobalSFX.Play(3); for (int i = 0; i < cc.ingredients.Length; i++) { cc.ingredients[i].RemoveItem(); } } } } } public class Rerolling { public CustomCrafting cc; public readonly int IngredientCount =2; public Rerolling(CustomCrafting cc) { this.cc = cc; } public bool validRecipe { get { if (cc.changedItem.i == null) return false; int itemCount = 0; int rarity = cc.changedItem.i.Rarity; for (int i = 0; i < cc.ingredients.Length; i++) { if (cc.ingredients[i].i != null) { if (cc.ingredients[i].i.Rarity == rarity) { itemCount++; } else { return false; } } } return itemCount == IngredientCount; } } public void PerformReroll() { if(cc.changedItem.i != null) { if (validRecipe) { cc.changedItem.i.RollStats(); Effects.Sound_Effects.GlobalSFX.Play(3); for (int i = 0; i < cc.ingredients.Length; i++) { cc.ingredients[i].RemoveItem(); } } } } } public class CraftingIngredient { public Item i = null; public int pos = -1; public void Assign(int index, Item i) { this.i = i; pos = index; } public void RemoveItem() { if (Inventory.Instance.ItemList.ContainsKey(pos)) Inventory.Instance.ItemList[pos] = null; i = null; pos = -1; } public void Clear() { i = null; pos = -1; } } public static bool isIngredient(int index) { return instance.ingredients.Any(x => x.pos == index) ||instance.changedItem.pos == index; } public static bool UpdateIndex(int index,int newIndex) { for (int i = 0; i < instance.ingredients.Length; i++) { if (instance.ingredients[i].pos == index) { if (newIndex < -1) { instance.ingredients[i].Clear(); return true; } instance.ingredients[i].pos = newIndex; return true; } } if (instance.changedItem.pos == index) { if (newIndex < -1) { instance.changedItem.Clear(); return true; } instance.changedItem.pos = newIndex; return true; } return false; } public static bool ClearIndex(int index) { for (int i = 0; i < instance.ingredients.Length; i++) { if (instance.ingredients[i].pos == index) { instance.ingredients[i].Clear(); return true; } } if (instance.changedItem.pos == index) { instance.changedItem.Clear(); return true; } return false; } } }
using Owin; using System.Web.Http; namespace AngularTablesDataManager { public class Startup { public void Configuration(IAppBuilder app) { HttpConfiguration config = new HttpConfiguration(); GlobalConfiguration.Configure(c => WebApiConfig.Register(config)); app.UseWebApi(config); } } }
using System; namespace Treorisoft.InputReader.Native { [Flags] public enum ButtonFlag : ushort { LeftButtonDown = 0x0001, LeftButtonUp = 0x0002, MiddleButtonDown = 0x0010, MiddleButtonUp = 0x0020, RightButtonDown = 0x0004, RightButtonUp = 0x0008, Button1Down = LeftButtonDown, Button1Up = LeftButtonUp, Button2Down = RightButtonDown, Button2Up = RightButtonUp, Button3Down = MiddleButtonDown, Button3Up = MiddleButtonUp, Button4Down = 0x0040, Button4Up = 0x0080, Button5Down = 0x0100, Button5Up = 0x0200, Wheel = 0x0400 } }
using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Linq; using System.Net; using System.Web; using System.Web.Mvc; using SistemaFacturacionWeb.Models; namespace SistemaFacturacionWeb.Controllers { public class VentasDetallesController : Controller { private facturacionEntities db = new facturacionEntities(); // GET: VentasDetalles public ActionResult Index() { var ventasDetalles = db.VentasDetalles.Include(v => v.Ventas); return View(ventasDetalles.ToList()); } public ActionResult Buscar(String NombreArticulo) { var narticulo = from s in db.articulo select s; var articuloSl = narticulo.Where(j => j.NombreArticulo.Contains(NombreArticulo)); //articulox articulos = db.articulo.Find(NombreArticulo); if (NombreArticulo == null) { return View(narticulo); } else { return View(articuloSl); } } // GET: VentasDetalles/Details/5 public ActionResult Details(Guid? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } VentasDetalles ventasDetalles = db.VentasDetalles.Find(id); if (ventasDetalles == null) { return HttpNotFound(); } return View(ventasDetalles); } // GET: VentasDetalles/Create public ActionResult Create() { ViewBag.CustomerId = new SelectList(db.Ventas, "CustomerId", "Cliente"); return View(); } // POST: VentasDetalles/Create // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see https://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create([Bind(Include = "OrderId,Articulo,ArticuloCodigo,Cantidad,Precio,Total,CustomerId")] VentasDetalles ventasDetalles) { if (ModelState.IsValid) { ventasDetalles.OrderId = Guid.NewGuid(); db.VentasDetalles.Add(ventasDetalles); db.SaveChanges(); return RedirectToAction("Index"); } ViewBag.CustomerId = new SelectList(db.Ventas, "CustomerId", "Cliente", ventasDetalles.CustomerId); return View(ventasDetalles); } // GET: VentasDetalles/Edit/5 public ActionResult Edit(Guid? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } VentasDetalles ventasDetalles = db.VentasDetalles.Find(id); if (ventasDetalles == null) { return HttpNotFound(); } ViewBag.CustomerId = new SelectList(db.Ventas, "CustomerId", "Cliente", ventasDetalles.CustomerId); return View(ventasDetalles); } // POST: VentasDetalles/Edit/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see https://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit([Bind(Include = "OrderId,Articulo,ArticuloCodigo,Cantidad,Precio,Total,CustomerId")] VentasDetalles ventasDetalles) { if (ModelState.IsValid) { db.Entry(ventasDetalles).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } ViewBag.CustomerId = new SelectList(db.Ventas, "CustomerId", "Cliente", ventasDetalles.CustomerId); return View(ventasDetalles); } // GET: VentasDetalles/Delete/5 public ActionResult Delete(Guid? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } VentasDetalles ventasDetalles = db.VentasDetalles.Find(id); if (ventasDetalles == null) { return HttpNotFound(); } return View(ventasDetalles); } // POST: VentasDetalles/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public ActionResult DeleteConfirmed(Guid id) { VentasDetalles ventasDetalles = db.VentasDetalles.Find(id); db.VentasDetalles.Remove(ventasDetalles); db.SaveChanges(); return RedirectToAction("Index"); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } } }
using System; namespace CupcakePCL { public class IdeaCategory { public String Title { get; set; } public String Description { get; set; } public override string ToString() { return Title; } } }
using Alabo.Domains.Repositories; using Alabo.Tenants.Domain.Entities; using MongoDB.Bson; namespace Alabo.Tenants.Domain.Repositories { /// <summary> /// ITenantRepository /// </summary> public interface ITenantRepository : IRepository<Tenant, ObjectId> { } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using Flipcards.DataAccess; using FlipCards.Models; namespace Flipcards { public partial class CreateCardForm : MaterialSkin.Controls.MaterialForm { private CardModel newCardModel = new CardModel(); private DeckModel parentDeckModel; public CreateCardForm(DeckModel model) { InitializeComponent(); parentDeckModel = model; } private void CreateCard_Load(object sender, EventArgs e) { } private void okButton_Click(object sender, EventArgs e) { newCardModel.Prompt = cardPromptTextBox.Text; newCardModel.Answer = cardAnswerTextBox.Text; newCardModel.DeckId = parentDeckModel.Id; if (newCardModel.Prompt.Length > 0 || newCardModel.Answer.Length > 0) { DataAccess.GlobalConfig.Connection.CreateCard(newCardModel); Close(); } else { MessageBox.Show("Please complete all fields"); } } private void cancelButton_Click(object sender, EventArgs e) { Close(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace WebTest { public partial class pay : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void Button1_Click(object sender, EventArgs e) { var request = new CRL.Business.OnlinePay.Company.Bill99.GetDynNumContent.Request(); request.bankId = "ICBC"; request.customerId = "201105"; request.amount = "100.00";//必填 //以下第二次鉴权可以不需要 request.cardHolderName = "测试"; request.idType = "0"; request.cardHolderId = "340827198512011810"; request.pan = "4380880000000007";//卡号 request.expiredDate = "0911"; request.phoneNO = "15861806195"; request.cvv2 = "111"; var result = CRL.Business.OnlinePay.Company.Bill99.Bill99Util.PCIStore(request, true, out token); Response.Write(string.Format("{0},{1}",result,token)); } static string token; protected void Button2_Click(object sender, EventArgs e) { var request = new CRL.Business.OnlinePay.Company.Bill99.TxnMsgContent.Request(); request.amount = "100.00"; //与鉴权订单金额一致 request.customerId = "201105";//必须要 var ex = new CRL.Business.OnlinePay.Company.Bill99.TxnMsgContent.Request._extData(); //扩展字段信息 ex.validCode = "949378";//手机验证码 ex.savePciFlag = "1";//是否保存鉴权信息 1保存 0不保存 ex.token = token;//手机验证令牌 ex.payBatch = "2";//快捷支付批次 1首次支付 2再次支付 ex.phone = "15861806195"; request.extData = ex; //以下第二次支付可以不用填写 request.cardNo = "4380880000000007"; request.expiredDate = "0911"; request.cvv2 = "111"; request.cardHolderName = "测试"; request.cardHolderId = "340827198512011810"; request.idType = "0"; string error; var result = CRL.Business.OnlinePay.Company.Bill99.Bill99Util.Purchase(request, true, out error); Response.Write(string.Format("{0},{1}", result, error)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EntVenta { public class Producto { public int Id { get; set; } //2 public int IdCategoria { get; set; } //3 public int IdTipoPresentacion { get; set; } //4 public string codigo { get; set; } //5 public string Descripcion { get; set; } //6 public string Presentacion { get; set; } //7 public string seVendeA { get; set; } //8 public decimal precioMenudeo { get; set; } //9 public decimal precioMMayoreo { get; set; } //10 public decimal APartirDe { get; set; } //11 public decimal precioMayoreo { get; set; } //12 public string usaInventario { get; set; } //13 public string stock { get; set; } //14 public decimal stockMinimo { get; set; } //15 public string Caducidad { get; set; } //16 public bool Estado { get; set; } //17 public string Tipo_Presentacion { get; set; } public string Tipo_Catalogo { get; set; } public decimal? TotalUnidades { get; set; } public string PresentacionMenudeo { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.InputSystem; using UnityEngine.SceneManagement; using System.IO; using UnityEngine.UI; using UnityEngine.AI; public class GameManager : MonoBehaviour { //public static GameManager gameManager; PlayerLog eventlog; TeacherMono teachermono; Reputation rep; [Header("Player Level")] [SerializeField] private int maxExp; [SerializeField] private float updatedExp; public Text leveltext; public Image Expbar; [SerializeField] private GameObject confetti; [SerializeField] private GameObject lvlsplash; [SerializeField] private int expIncrease; [SerializeField] private int playerLevel; [Header("Player Publicity")] public Text publicity; public Text publicityStanding; [SerializeField] private int maxPub; [SerializeField] private int addpub; [SerializeField] private int playerpublicity; [Header("Player Reputation")] [SerializeField] private Text reputationtxt; [Header("Level SFX")] public AudioClip lvlSFX; private AudioSource lvlsfxSource { get { return GetComponent<AudioSource>(); } } public Transform[] LevelMarkers; [Header("Gold Coins")] [SerializeField] private float money; [SerializeField] Text moneyText; //"Money Text" [SerializeField] private float earnedM; [SerializeField] private float spentM; [Header("Gold SFX")] public AudioClip goldSFX; private AudioSource goldsfxSource { get { return GetComponent<AudioSource>(); } } [Header("Student Count")] Text StudentCountText;//"StudentCount" private int StudentCount; private int classRCount; [SerializeField] private Text classRCountText;//"classRCount" //ADMIN private int adminCount; [Header("Teacher Count")] private int teacherCount; [SerializeField] private Text TeacherCountTXT; [Header("Salary Needs to be paid")] [SerializeField] private float totalSalary; [SerializeField] private float totalSalaryPerDay; [SerializeField] private float GrandtotalSalary; public Text totalSalarytxt; public Text SalaryPaidtxt; public Text GrandtotalSalarytxt; public bool playerPaidSalary = false; // public Text incrementTxt; //tester public Vector3 LocationOfSpawn = new Vector3(-7.98f, 0f, -72f); public static GameManager instance = null; public List<GameObject> Clasesbogth = new List<GameObject>(); public List<GameObject> Chilingspot = new List<GameObject>(); public List<GameObject> Bathroomrooms = new List<GameObject>(); public List<GameObject> MagicClass = new List<GameObject>(); public List<GameObject> SurfingClass = new List<GameObject>(); public List<GameObject> HakingClass = new List<GameObject>(); public List<GameObject> AxeTrowingClass = new List<GameObject>(); public int NumberOfMagic = 0; public int NumberOfSurfing = 0; public int NumberOfHacking = 0; public int NumberOfAxeTrowing = 0; public string[] AvalableClases = new string[] { "Magic", "Surfing", "Hacking", "AxeTrowing" }; public List<GameObject> HiredTeachers; List<string> Clases = new List<string>(); [Header("Male & Female Student Prefab Toinstanciate")] [SerializeField] private GameObject[] Student; private int StudentSpawn; [SerializeField] private GameObject[] waypontsinmanagement; public int ClassRCount { get => classRCount; set => classRCount = value; } public float Money { get => money; set => money = value; } public int TeacherCount { get => teacherCount; set => teacherCount = value; } public float TotalSalary { get => totalSalary; set => totalSalary = value; } public float TotalSalaryPerDay { get => totalSalaryPerDay; set => totalSalaryPerDay = value; } public float GrandtotalSalary1 { get => GrandtotalSalary; set => GrandtotalSalary = value; } public int AdminCount { get => adminCount; set => adminCount = value; } public int MaxExp { get => maxExp; set => maxExp = value; } public float UpdatedExp { get => updatedExp; set => updatedExp = value; } public int ExpIncrease { get => expIncrease; set => expIncrease = value; } public int PlayerLevel { get => playerLevel; set => playerLevel = value; } public int StudentCount1 { get => StudentCount; set => StudentCount = value; } public int Playerpublicity { get => playerpublicity; set => playerpublicity = value; } public int MaxPub { get => maxPub; set => maxPub = value; } public int Addpub { get => addpub; set => addpub = value; } public float EarnedM { get => earnedM; set => earnedM = value; } public float SpentM { get => spentM; set => spentM = value; } private void Awake() { if (instance == null) { instance = this; } else if (instance != this) { Destroy(gameObject); } } ///SFX public void sfxStuff() { gameObject.AddComponent<AudioSource>(); goldsfxSource.clip = goldSFX; lvlsfxSource.clip = lvlSFX; //SFX volume Gold goldsfxSource.volume = 0.5f; goldsfxSource.playOnAwake = false; //SFX Volume Level lvlsfxSource.volume = 0.5f; lvlsfxSource.playOnAwake = false; } public void playGoldSFX() { goldsfxSource.PlayOneShot(goldSFX); } public void playLevelSFX() { lvlsfxSource.PlayOneShot(lvlSFX); } ///LEVEL SYSTEM public void playerBeginLvl() { PlayerLevel = 1; MaxExp = 100; UpdatedExp = 0; Expbar.fillAmount = 0; } public void addExp(int ExpIncrease) { //ExpIncrease = 50; for testing purposes lol UpdatedExp += ExpIncrease; Expbar.fillAmount = UpdatedExp / MaxExp; levelUp(); } public void levelUp() { confetti.SetActive(false); lvlsplash.SetActive(false); if (UpdatedExp >= MaxExp) { PlayerLevel++; confetti.SetActive(true); lvlsplash.SetActive(true); playLevelSFX(); UpdatedExp = 0; MaxExp += MaxExp/2; } } // Publicity SYSTEM public void playerBeginPublicity() { Playerpublicity = 50; } public void addPub(int Addpub) { Playerpublicity += Addpub; } public void removePub(int removepub) { Playerpublicity -= removepub; } public GameObject Reschudule(string clas) { GameObject tempo = null; if (clas == "Magic") { for(int i = 0; i < MagicClass.Count; i++) { if (MagicClass[i].GetComponent<ClasroomScip>().IsthereSpace()) { tempo=MagicClass[i].GetComponent<ClasroomScip>().AvalableSit(); } } return tempo; } else if (clas == "Hacking") { for (int i = 0; i < HakingClass.Count; i++) { if (HakingClass[i].GetComponent<ClasroomScip>().IsthereSpace()) { tempo = HakingClass[i].GetComponent<ClasroomScip>().AvalableSit(); } } return tempo; } else if (clas == "AxeTrowing") { for (int i = 0; i < AxeTrowingClass.Count; i++) { if (AxeTrowingClass[i].GetComponent<ClasroomScip>().IsthereSpace()) { tempo = AxeTrowingClass[i].GetComponent<ClasroomScip>().AvalableSit(); } } return tempo; } else if (clas == "Surfing") { for (int i = 0; i < SurfingClass.Count; i++) { if (SurfingClass[i].GetComponent<ClasroomScip>().IsthereSpace()) { tempo = SurfingClass[i].GetComponent<ClasroomScip>().AvalableSit(); } } return tempo; } else { return null; } } public void ClasesNumber(GameObject clasroom) { if (clasroom.tag == "Magic") { NumberOfMagic++; MagicClass.Add(clasroom); } else if (clasroom.tag == "Haking") { NumberOfHacking++; HakingClass.Add(clasroom); } else if (clasroom.tag == "AxeTrowing") { NumberOfAxeTrowing++; AxeTrowingClass.Add(clasroom); } else if (clasroom.tag == "Surfing") { NumberOfSurfing++; SurfingClass.Add(clasroom); } //public List<GameObject> MagicClass = new List<GameObject>(); //public List<GameObject> SurfingClass = new List<GameObject>(); //public List<GameObject> HakingClass = new List<GameObject>(); //public List<GameObject> AxeTrowingClass = new List<GameObject>(); } public bool SpaceOnClasroomBogth() { bool temp = false; if (Clasesbogth.Count > 0) { foreach (GameObject a in Clasesbogth) { if (a.GetComponent<ClasroomScip>().IsthereSpace()) temp = true; } return temp; } else { return false; } } void Start() { eventlog = PlayerLog.instance; rep = Reputation.instance; StudentCountText = GameObject.FindGameObjectWithTag("StudentCount").GetComponent<Text>(); classRCountText = GameObject.FindGameObjectWithTag("ClassCount").GetComponent<Text>(); TeacherCountTXT = GameObject.FindGameObjectWithTag("TeacherCount").GetComponent<Text>(); playerBeginLvl(); playerBeginPublicity(); } void Update() { UpdateMoneyUI(); RefreshTextOnUI(); classRTxtOnUI(); //ClasesNumber(); teacherTxtOnUI(); updateNewlyHiredTSalary(); updateCurrentTSalary(); updateRecentTSalary(); levelTxtOnUI(); publictyUI(); publictyStandingUI(); updateReputationUI(); //levelUp(); } /// money public void AddMoney(float amount) { money += amount; earnedMoney(amount); playGoldSFX(); UpdateMoneyUI(); } public void ReduceMoney(float amount) { money -= amount; spendMoney(amount); playGoldSFX(); UpdateMoneyUI(); } public void AddMoneyOvertime(float amount) { money += amount++; UpdateMoneyUI(); } public bool RequestMoney(float amount) { if (amount <= money) { return true; } return false; } public void getPaid() { float temp = 0; foreach (GameObject stud in Allregisteredstudents) { if (stud.GetComponent<StudentMono>().ClassSit.transform.parent.GetComponent<ClasroomScip>().Teacher != null) { AddMoney(25); } } } public void earnedMoney(float amount) { EarnedM += amount; } public void spendMoney(float amount) { SpentM += amount; } /// student public void AddStudent() { StudentCount1++; } public void AddClasses() { classRCount++; } public void ReduceClasses() { classRCount--; } //TEACHER public void AddTeacher(GameObject Teacher) { TeacherCount++; HiredTeachers.Add(Teacher); } /// ADMIN public void AddAdmin() { AdminCount++; } // SALARY public void SumofSalary(float teacherSalary) { TotalSalaryPerDay += teacherSalary; calcTotalSumofAllSalary(); } public void calcTotalSumofAllSalary() { //cal what needs to be paid in TOTAL GrandtotalSalary1 = TotalSalaryPerDay + totalSalary; } public void paySumofSalary() { if (playerPaidSalary == true) { eventlog.AddEvent("Already paid!"); Debug.Log("Already paid!"); } else { //remove it from the Money ReduceMoney(TotalSalaryPerDay); //GrandtotalSalary1 //resets the daily salary TotalSalary += TotalSalaryPerDay; TotalSalaryPerDay = 0; //paid salary indicator playerPaidSalary = true; } } // UI public void updateReputationUI() { reputationtxt.text = "Reputation: " + rep.REP1.ToString(); } public void updateCurrentTSalary() { SalaryPaidtxt.text = "Paid Salary: $" + TotalSalary.ToString(); } public void updateNewlyHiredTSalary() { totalSalarytxt.text = "Salary to Pay: $" + TotalSalaryPerDay.ToString(); } public void updateRecentTSalary() { GrandtotalSalarytxt.text = "Total Upkeep: $" + GrandtotalSalary1.ToString(); } public void UpdateMoneyUI() { moneyText.text = "$ " + money.ToString("N0"); } public void RefreshTextOnUI() { StudentCountText.text = "Students: "+StudentCount1; } public void classRTxtOnUI() { classRCountText.text = "Class Built: "+classRCount; } public void teacherTxtOnUI() { TeacherCountTXT.text = "Teachers: " + TeacherCount; } public void levelTxtOnUI() { leveltext.text = "Level " + playerLevel; } public void publictyUI() { Playerpublicity = Mathf.Clamp(Playerpublicity, 1, 100); publicity.text = "Publicity: " + Playerpublicity; } public void publictyStandingUI() { Playerpublicity = Mathf.Clamp(Playerpublicity, 1, 100); if(Playerpublicity > 0 && Playerpublicity < 45) { publicityStanding.text = "Current Publicity Standing is BAD because you are in the rage of 0 and 45."; } else if (Playerpublicity >= 45 && Playerpublicity < 65) { publicityStanding.text = "Current Publicity Standing is OKAY because you are in the range of 45 and 65."; } else if (Playerpublicity >= 65) { publicityStanding.text = "Current Publicity Standing is GOOD because you are above 65."; } } public void SpawnCode() { Instantiate(Student[Random.Range(0,1)], LocationOfSpawn, Quaternion.identity); //Instantiate(Student, LocationOfSpawn, Quaternion.identity); } public Administration[] managementlines; public List<GameObject> Allregisteredstudents; //public void Gopay() //{ // managementlines[0].studentstopay = new List<GameObject>(); // managementlines[1].studentstopay = new List<GameObject>(); // managementlines[2].studentstopay = new List<GameObject>(); // managementlines[3].studentstopay = new List<GameObject>(); // foreach (GameObject student in Allregisteredstudents) { // if (student.GetComponent<StudentMono>().Paid == false) // { // NavMeshAgent agent; // agent = student.GetComponent<NavMeshAgent>(); // int temp=0; // for (int i = 0; i < managementlines.Length; i++) // { // int f = 1; // if (managementlines[i].Isthereasecretary && managementlines[i].studentstopay.Count <= managementlines[f].studentstopay.Count) // { // temp = i; // } // } // managementlines[temp].studentstopay.Add(student); // } // } // StartCoroutine( managementlines[0].Payfees()); // managementlines[0].organiseline(); // StartCoroutine( managementlines[1].Payfees()); // managementlines[1].organiseline(); // StartCoroutine( managementlines[2].Payfees()); // managementlines[2].organiseline(); // StartCoroutine( managementlines[3].Payfees()); // managementlines[3].organiseline(); //} }
using System; using System.Collections.Generic; using System.Text; using Xunit; namespace TalkExamplesTest.SOLID.LSP.Example1 { public class CollectionArrayTest { [Fact] public void Test() { var array = new[] { 1, 2, 3 }; Assert.True(array is Array); ICollection<int> collection = array; Assert.True(array is ICollection<int>); collection.Add(4); } } }
using Newtonsoft.Json; using RestSharp; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; namespace trade.client.Marketdata { public class Level1Client { private static Dictionary<string, Exchange> Exchanges = new Dictionary<string, Exchange>() { {"sh", Exchange.Sh}, {"sz", Exchange.Sz} }; private static Dictionary<string, StockType> Types = new Dictionary<string, StockType>() { {"STOCK", StockType.Stock }, {"LOF", StockType.LOF }, { "ETF", StockType.ETF }, {"REPO", StockType.Repo } }; private RestClient Client; public Level1Client(string host) { Client = new RestClient(host); } public List<Stock> GetStocks() { string json = GetSecurities(); List<SecurityDto> list = JsonConvert.DeserializeObject<List<SecurityDto>>(json); List<Stock> result = new List<Stock>(); list.ForEach((stock) => { if (Types.ContainsKey(stock.Type)) result.Add(Transfer(stock)); }); return result; } private Stock Transfer(SecurityDto s) { Stock result = new Stock() { SecurityId = new SecurityId(s.Symbol, Exchanges[s.Exchange]), Name = s.Name, PinYin = s.Pinyin, Type = Types[s.Type] }; return result; } private string GetSecurities() { var request = new RestRequest("/securities", Method.GET); var response = Client.Execute(request); return response.Content; } } class SecurityDto { public string Symbol { set; get; } public string Exchange { set; get; } public string Type { set; get; } public string Name { set; get; } public string Pinyin { set; get; } public string Category { set; get; } } }
using System; using System.Collections.Generic; using System.Drawing; using System.Globalization; using System.Linq; using System.Web; using System.Web.Mvc; using AudioText.DAL; using AudioText.Models.ViewModels; namespace AudioText.Controllers { public class AdminOrdersController : Controller { private RepositoryManager _manager; public AdminOrdersController() { _manager = new RepositoryManager(); } [Route("admin/orders")] [HttpGet] public ActionResult Index() { return View(_manager.OrderRepository.Get().Select(nextOrder => new OrderListViewModel(nextOrder)) .OrderByDescending(entity => entity.Date) .ThenBy(entity => entity.Name).ToList()); } [Route("admin/orders/{orderId}/markAsShipped")] [HttpPost] public void MarkOrderAsShipped(int orderId) { var order = _manager.OrderRepository.GetByID(orderId); order.ShippedDate = DateTime.Now; _manager.save(); } [Route("admin/orders/search")] [HttpPost] public PartialViewResult UpdateOrderList(string filters) { var results = _manager.OrderRepository.Get(); filters = filters.ToLower(); if (filters.Contains('#')) { results = results.Where(entity => entity.ID.ToString().Contains(filters.Remove(filters.IndexOf('#'), 1).ToString())); } else { foreach (var nextFilter in filters.Split(' ')) { if (results.Any()) { results = results.Where(entity => entity.Address.ToLower().Contains(nextFilter) || (entity.Address2 != null && entity.Address2.ToLower().Contains(nextFilter)) || entity.City.ToLower().Contains(nextFilter) || entity.FirstName.ToLower().Contains(nextFilter) || entity.LastName.ToLower().Contains(nextFilter) || entity.OrderDate.ToString(CultureInfo.InvariantCulture).Contains(nextFilter)); } } } return PartialView("_datatable", results.Select(nextOrder => new OrderListViewModel(nextOrder)) .OrderByDescending(entity => entity.Date) .ThenBy(entity => entity.Name).ToList()); } [Route("admin/orders/OrderDetails/{orderId}")] [HttpPost] public ActionResult ViewOrderDetails(int orderId) { var order = _manager.OrderRepository.GetByID(orderId); return View("_orderDetailsModalContent", new OrderViewModel( order.OrderDetails, $"{order.Address} {order.Address2} {order.City}, {order.State} {order.Zip}", $"{order.LastName}, {order.FirstName}", order.ID, order.OrderDate, order.Total, order.OrderDate)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel.DataAnnotations; using com.Sconit.Entity.SYS; namespace com.Sconit.Entity.MRP.VIEW { public class MrpPlanTraceView { //物料号 物料描述 最大 最小 待收 待发 当前库存 public string Item { get; set; } public string ItemDescription { get; set; } public double MaxStock { get; set; } public double SafeStock { get; set; } public double StartQty { get; set; } public double StartTransQty { get; set; }//期初在途库存 public double InQty { get; set; } public double OutQty { get; set; } public double PlanInQty { get; set; } public double PlanOutQty { get; set; } public double EndQty { get; set; } public double EndTransQty { get; set; }//期末在途库存 public IList<MrpPlanTraceDetailView> MrpPlanTraceDetailViewList { get; set; } } public class MrpPlanTraceDetailView { //可能原因(质量,生产,客户) 订单号 时间 库位 单位 数量 //Item OrderNo Qty QualityType TransType IOType LocFrom LocTo CreateDate public string Item { get; set; } //public string Reason { get; set; } public string OrderNo { get; set; } public double Qty { get; set; } public CodeMaster.QualityType QualityType { get; set; } public CodeMaster.TransactionType TransType { get; set; } public CodeMaster.TransactionIOType IOType { get; set; } public string LocationFrom { get; set; } public string LocationTo { get; set; } public DateTime CreateDate { get; set; } //public string Location { get; set; } //public string LocationName { get; set; } public string Uom { get; set; } [CodeDetailDescriptionAttribute(CodeMaster = com.Sconit.CodeMaster.CodeMaster.TransactionType, ValueField = "TransType")] public string TransTypeDescription { get; set; } } }