I'm new in here and at programming. I'm making a program that only shows one week at a time. I have some appointments spanning over several weeks, and my question is: Is there a way to only show the "appointments" of the week you are currently in?
So far i have this:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
var googleCal = new GoogleClass();
foreach (var googleEvent in googleCal.GoogleEvents)
{
if ((googleEvent.StartDate.Value.DayOfWeek - googleEvent.StartDate.Value.DayOfWeek)
{
listBox.Items.Add(googleEvent.Title + " " + googleEvent.StartDate);
}
}
}
}
public class GoogleEvents
{
public string Title { get; set; }
public DateTime? StartDate { get; set; }
}
class GoogleClass
{
public List<GoogleEvents> GoogleEvents = new List<GoogleEvents>();
static string[] Scopes = { CalendarService.Scope.CalendarReadonly };
static string ApplicationName = "Google Calendar API .NET Quickstart";
public GoogleClass()
{
UserCredential credential;
using (var stream = new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
{
string credPath = System.Environment.GetFolderPath(
System.Environment.SpecialFolder.Personal);
credPath = Path.Combine(credPath, ".credentials/calendar-dotnet-quickstart.json");
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scopes,
"user",
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
}
// Create Google Calendar API service.
var service = new CalendarService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
// Define parameters of request.
EventsResource.ListRequest request = service.Events.List("primary");
request.TimeMin = DateTime.Now;
request.ShowDeleted = false;
request.SingleEvents = true;
request.MaxResults = 10;
request.OrderBy = EventsResource.ListRequest.OrderByEnum.StartTime;
// List events.
Events events = request.Execute();
if (events.Items != null && events.Items.Count > 0)
{
foreach (var eventItem in events.Items)
{
string when = eventItem.Start.DateTime.ToString();
if (String.IsNullOrEmpty(when))
{
when = eventItem.Start.Date;
}
GoogleEvents.Add(new GoogleEvents {Title = eventItem.Summary, StartDate = eventItem.Start.DateTime});
}
}
}
}
I have figured it out
var googleCal = new GoogleClass();
var ugedag = DateTime.Now.DayOfWeek;
var getMondays = googleCal.GoogleEvents.Where(e => e.StartDate < DateTime.Now.AddDays(6));
var getTuesdays = googleCal.GoogleEvents.Where(e => e.StartDate < DateTime.Now.AddDays(5));
var getWednesday = googleCal.GoogleEvents.Where(e => e.StartDate < DateTime.Now.AddDays(4));
var getThursday = googleCal.GoogleEvents.Where(e => e.StartDate < DateTime.Now.AddDays(3));
var getFriday = googleCal.GoogleEvents.Where(e => e.StartDate < DateTime.Now.AddDays(2));
var getSaturday = googleCal.GoogleEvents.Where(e => e.StartDate < DateTime.Now.AddDays(1));
var getSunday = googleCal.GoogleEvents.Where(e => e.StartDate < DateTime.Now.AddDays(0));
foreach (var googleCalGoogleEvent in googleCal.GoogleEvents)
{
listBox.Items.Add(googleCalGoogleEvent.Title);
}
if (ugedag == DayOfWeek.Monday)
{
foreach (var events in getMondays)
{
NewMethod(events);
}
}
if (ugedag == DayOfWeek.Tuesday)
{
foreach (var events in getTuesdays)
{
NewMethod(events);
}
}
if (ugedag == DayOfWeek.Wednesday)
{
foreach (var events in getWednesday)
{
NewMethod(events);
}
}
if (ugedag == DayOfWeek.Thursday)
{
foreach (var events in getThursday)
{
NewMethod(events);
}
}
if (ugedag == DayOfWeek.Friday)
{
foreach (var events in getFriday)
{
NewMethod(events);
}
}
if (ugedag == DayOfWeek.Saturday)
{
foreach (var events in getSaturday)
{
NewMethod(events);
}
}
if (ugedag == DayOfWeek.Sunday)
{
foreach (var events in getSunday)
{
NewMethod(events);
}
}
}
private void NewMethod(GoogleEvents events)
{
if (events.StartDate.Value.DayOfWeek == DayOfWeek.Monday)
{
Monday.Items.Add($"{events.Title} \n{events.StartDate:dd-MM HH:MM}-{events.EndDate:HH:MM}");
}
if (events.StartDate.Value.DayOfWeek == DayOfWeek.Tuesday)
{
Tuesday.Items.Add($"{events.Title} \n{events.StartDate:dd-MM HH:MM}-{events.EndDate:HH:MM}");
}
if (events.StartDate.Value.DayOfWeek == DayOfWeek.Wednesday)
{
Wednsday.Items.Add($"{events.Title} \n{events.StartDate:dd-MM HH:MM}-{events.EndDate:HH:MM}");
}
if (events.StartDate.Value.DayOfWeek == DayOfWeek.Thursday)
{
Thuesday.Items.Add($"{events.Title} \n{events.StartDate:dd-MM HH:MM}-{events.EndDate:HH:MM}");
}
if (events.StartDate.Value.DayOfWeek == DayOfWeek.Friday)
{
Friday.Items.Add($"{events.Title} \n{events.StartDate:dd-MM HH:MM}-{events.EndDate:HH:MM}");
}
if (events.StartDate.Value.DayOfWeek == DayOfWeek.Saturday)
{
Saturday.Items.Add($"{events.Title} \n{events.StartDate:dd-MM HH:MM}-{events.EndDate:HH:MM}");
}
if (events.StartDate.Value.DayOfWeek == DayOfWeek.Sunday)
{
Sunday.Items.Add($"{events.Title} \n{events.StartDate:dd-MM HH:MM}-{events.EndDate:HH:MM}");
}
}
Related
I have identityServer4 as my oAuth server in my net core appilication. I was able to initialize my client database using the following code:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())
{
SeedData.EnsureSeedData(serviceScope);
}
}
}
The migration and client initialization is done using
public class SeedData
{
public static void EnsureSeedData(IServiceScope serviceScope)
{
Console.WriteLine("Seeding database...");
serviceScope.ServiceProvider.GetRequiredService<PersistedGrantDbContext>().Database.Migrate();
var context = serviceScope.ServiceProvider.GetRequiredService<ConfigurationDbContext>();
context.Database.Migrate();
EnsureSeedData(context);
Console.WriteLine("Done seeding database.");
Console.WriteLine();
}
private static void EnsureSeedData(ConfigurationDbContext context)
{
if (!context.Clients.Any())
{
Console.WriteLine("Clients being populated");
foreach (var client in Config.GetClients().ToList())
{
context.Clients.Add(client.ToEntity());
}
context.SaveChanges();
}
else
{
Console.WriteLine("Clients already populated, update clients");
foreach (var client in Config.GetClients().ToList())
{
var item = context.Clients.Where(c => c.ClientId == client.ClientId).FirstOrDefault();
if(item == null)
{
context.Clients.Add(client.ToEntity());
} else {
var model = client.ToEntity();
model.Id = item.Id;
context.Entry(item).CurrentValues.SetValues(model);
}
}
context.SaveChanges();
}
if (!context.IdentityResources.Any())
{
Console.WriteLine("IdentityResources being populated");
foreach (var resource in Config.GetIdentityResources().ToList())
{
context.IdentityResources.Add(resource.ToEntity());
}
context.SaveChanges();
}
else
{
Console.WriteLine("IdentityResources already populated");
foreach (var resource in Config.GetIdentityResources().ToList())
{
var item = context.IdentityResources.Where(c => c.Name == resource.Name).FirstOrDefault();
if (item == null)
{
context.IdentityResources.Add(resource.ToEntity());
}
else
{
var model = resource.ToEntity();
model.Id = item.Id;
context.Entry(item).CurrentValues.SetValues(model);
}
}
context.SaveChanges();
}
if (!context.ApiResources.Any())
{
Console.WriteLine("ApiResources being populated");
foreach (var resource in Config.GetApiResources().ToList())
{
context.ApiResources.Add(resource.ToEntity());
}
context.SaveChanges();
}
else
{
Console.WriteLine("ApiResources already populated");
foreach (var resource in Config.GetApiResources().ToList())
{
var item = context.ApiResources.Where(c => c.Name == resource.Name).FirstOrDefault();
if (item == null)
{
context.ApiResources.Add(resource.ToEntity());
}
else
{
var model = resource.ToEntity();
model.Id = item.Id;
context.Entry(item).CurrentValues.SetValues(model);
}
}
context.SaveChanges();
}
}
}
The initialization of the client database works well. However, there are problems to update the client database. Some of the records are not updated. Is there a better way to do this?
After some struggle, I found a solution that works for me. Basically, I created a table, ClientVersion, that track clients definition changes.
Here is my new version of SeedData.cs.
public class SeedData
{
public static void EnsureSeedData(IServiceScope serviceScope)
{
Console.WriteLine("Seeding database...");
serviceScope.ServiceProvider.GetRequiredService<PersistedGrantDbContext>().Database.Migrate();
var context = serviceScope.ServiceProvider.GetRequiredService<ConfigurationDbContext>();
context.Database.Migrate();
var versionContext = serviceScope.ServiceProvider.GetRequiredService<VersionContext>();
versionContext.Database.Migrate();
EnsureSeedData(context, versionContext);
Console.WriteLine("Done seeding database.");
Console.WriteLine();
}
private static void EnsureSeedData(ConfigurationDbContext context, VersionContext versionContext)
{
ClientVersion version = versionContext.ClientVersion.FirstOrDefault();
bool blUpdate = version == null ? true : (Config.CurrentVersion > version.Version ? true: false);
if(blUpdate)
{
if(version == null)
{
version = new ClientVersion()
{
Version = Config.CurrentVersion,
};
versionContext.ClientVersion.Add(version);
} else
{
version.Version = Config.CurrentVersion;
versionContext.ClientVersion.Update(version);
}
versionContext.SaveChanges();
}
if (!context.Clients.Any())
{
Console.WriteLine("Clients being populated");
foreach (var client in Config.GetClients().ToList())
{
context.Clients.Add(client.ToEntity());
}
context.SaveChanges();
}
else
{
Console.WriteLine("Clients already populated, update clients");
if (blUpdate)
{
foreach (var client in Config.GetClients().ToList())
{
var item = context.Clients
.Include(x => x.RedirectUris)
.Include(x => x.PostLogoutRedirectUris)
.Include(x => x.ClientSecrets)
.Include(x => x.Claims)
.Include(x => x.AllowedScopes)
.Include(x => x.AllowedCorsOrigins)
.Include(x => x.AllowedGrantTypes)
.Where(c => c.ClientId == client.ClientId).FirstOrDefault();
if (item != null)
{
context.Clients.Remove(item);
}
context.Clients.Add(client.ToEntity());
}
context.SaveChanges();
}
}
if (!context.IdentityResources.Any())
{
Console.WriteLine("IdentityResources being populated");
foreach (var resource in Config.GetIdentityResources().ToList())
{
context.IdentityResources.Add(resource.ToEntity());
}
context.SaveChanges();
}
else
{
Console.WriteLine("IdentityResources already populated");
if (blUpdate)
{
foreach (var resource in Config.GetIdentityResources().ToList())
{
var item = context.IdentityResources.Where(c => c.Name == resource.Name).FirstOrDefault();
if (item != null)
{
context.IdentityResources.Remove(item);
}
context.IdentityResources.Add(resource.ToEntity());
}
context.SaveChanges();
}
}
if (!context.ApiResources.Any())
{
Console.WriteLine("ApiResources being populated");
foreach (var resource in Config.GetApiResources().ToList())
{
context.ApiResources.Add(resource.ToEntity());
}
context.SaveChanges();
}
else
{
Console.WriteLine("ApiResources already populated");
if (blUpdate)
{
foreach (var resource in Config.GetApiResources().ToList())
{
var item = context.ApiResources.Where(c => c.Name == resource.Name).FirstOrDefault();
if (item != null)
{
context.ApiResources.Remove(item);
}
context.ApiResources.Add(resource.ToEntity());
}
context.SaveChanges();
}
}
}
}
A lot of apps have swipable intro screens - You know - those with the dots below which indicate the page one is currently viewing.
What would be the best way to create one in Codename One - a Container with snapToGrid?
I have my own implementation for this use case. There are two classes : TutoDialog which could be in your case the "intro screens" dialog and Caroussel with the dots indicator.
A tuto dialog has a title and some images in parameter. It automatically adjust the number of dots of the caroussel according to the number of images. For my use case, each image is a screenshot of my app with some advise. The tuto dialog contains 3 buttons to navigate between images (next/previous/finish).
public class Caroussel extends Container {
private final static Image CIRCLE = MainClass.getResources().getImage("circle-blue20.png");
private final static Image CIRCLE_EMPTY = MainClass.getResources().getImage("circle-empty-blue20.png");
private Label[] circles;
private int currentIndex = -1;
public Caroussel(int nbItems, boolean selectFirst) {
if (nbItems < 2 || nbItems > 50) {
throw new IllegalArgumentException("Can't create Caroussel component with nbItems<2 || nbItems>50 ! ");
}
this.circles = new Label[nbItems];
setLayout(new BoxLayout(BoxLayout.X_AXIS));
for (int i = 0; i < nbItems; i++) {
circles[i] = new Label("", CIRCLE_EMPTY);
add(circles[i]);
}
if (selectFirst) {
select(0);
}
}
public void select(int index) {
if (index >= 0 && index <= circles.length) {
if (currentIndex > -1) {
circles[currentIndex].setIcon(CIRCLE_EMPTY);
}
circles[index].setIcon(CIRCLE);
currentIndex = index;
repaint();
}
}
public void selectNext() {
if (currentIndex <= circles.length) {
select(currentIndex + 1);
}
}
public void selectPrevious() {
if (currentIndex >= 1) {
select(currentIndex - 1);
}
}}
And
public class TutoDialog extends Dialog {
private Caroussel caroussel = null;
public TutoDialog(String title, Image... images) {
if (images == null) {
return;
}
this.caroussel = new Caroussel(images.length, true);
setTitle(title);
setAutoAdjustDialogSize(true);
getTitleComponent().setUIID("DialogTitle2");
setBlurBackgroundRadius(8.5f);
Tabs tabs = new Tabs();
tabs.setSwipeActivated(false);
tabs.setAnimateTabSelection(false);
int px1 = DisplayUtil.getScaledPixel(800), px2 = DisplayUtil.getScaledPixel(600);
for (Image img : images) {
tabs.addTab("", new Label("", img.scaled(px1, px2)));
}
Container cButtons = new Container(new BorderLayout());
Button bSuivant = new Button("button.suivant");
Button bPrecedent = new Button("button.precedent");
Button bTerminer = new Button("button.terminer");
bPrecedent.setVisible(false);
bTerminer.setVisible(false);
bSuivant.addActionListener(new ActionListener<ActionEvent>() {
public void actionPerformed(ActionEvent evt) {
int currentInd = tabs.getSelectedIndex();
if (currentInd == 0) {
bPrecedent.setVisible(true);
}
if (currentInd + 1 <= tabs.getTabCount() - 1) {
if (caroussel != null)
caroussel.selectNext();
tabs.setSelectedIndex(currentInd + 1);
if (currentInd + 1 == tabs.getTabCount() - 1) {
bTerminer.setVisible(true);
bSuivant.setVisible(false);
cButtons.revalidate();
}
}
};
});
bPrecedent.addActionListener(new ActionListener<ActionEvent>() {
public void actionPerformed(ActionEvent evt) {
int currentInd = tabs.getSelectedIndex();
tabs.setSelectedIndex(currentInd - 1);
bSuivant.setVisible(true);
if (caroussel != null)
caroussel.selectPrevious();
if (currentInd - 1 == 0) {
bPrecedent.setVisible(false);
cButtons.revalidate();
}
};
});
bTerminer.addActionListener(new ActionListener<ActionEvent>() {
#Override
public void actionPerformed(ActionEvent evt) {
tabs.setSelectedIndex(0);
bPrecedent.setVisible(false);
bTerminer.setVisible(false);
bSuivant.setVisible(true);
if (caroussel != null)
caroussel.select(0);
TutoDialog.this.dispose();
}
});
cButtons.add(BorderLayout.WEST, bPrecedent).add(BorderLayout.CENTER, bSuivant).add(BorderLayout.EAST, bTerminer);
add(BoxLayout.encloseY(tabs, BoxLayout.encloseY(FlowLayout.encloseCenter(caroussel), cButtons)));
}
public static void showIfFirstTime(AbstractComponentController ctrl) {
if (ctrl == null) {
Log.p("Can't execute method showIfFirstTime(...) with null AbstractComponentController");
return;
}
String key = getKey(ctrl);
if (ctrl.getTutoDlg() != null && !Preferences.get(key, false)) {
Display.getInstance().callSerially(new Runnable() {
#Override
public void run() {
Preferences.set(key, true);
ctrl.getTutoDlg().show();
}
});
}
}
public static String getKey(AbstractComponentController ctrl) {
String key = "tuto" + ctrl.getClass().getSimpleName();
if (UserController.getCurrentUser() != null) {
key += "-" + UserController.getCurrentUser().getId();
}
return key;
}
public static boolean isAlreadyShown(AbstractComponentController ctrl) {
return Preferences.get(getKey(ctrl), false);
}
}
It's look like this :
OK - so that is my first attempt and I am pretty content with that:
private void showIntro() {
Display display = Display.getInstance();
int percentage = 60;
int snapWidth = display.getDisplayWidth() * percentage / 100;
int snapHeight = display.getDisplayHeight() * percentage / 100;
Dialog dialog = new Dialog(new LayeredLayout()) {
#Override
protected Dimension calcPreferredSize() {
return new Dimension(snapWidth, snapHeight);
}
};
Tabs tabs = new Tabs();
tabs.setTensileLength(0);
tabs.hideTabs();
int[] colors = {
0xc00000,
0x00c000,
0x0000c0,
0x909000,
0x009090,
};
for (int colorIndex = 0; colorIndex < colors.length; colorIndex++) {
Container containerElement = new Container() {
#Override
protected Dimension calcPreferredSize() {
return new Dimension(snapWidth, snapHeight);
}
};
Style style = containerElement.getAllStyles();
style.setBgTransparency(0xff);
style.setBgColor(colors[colorIndex]);
tabs.addTab("tab" + tabs.getTabCount(), containerElement);
}
int tabCount = tabs.getTabCount();
Button[] buttons = new Button[tabCount];
Style styleButton = UIManager.getInstance().getComponentStyle("Button");
styleButton.setFgColor(0xffffff);
Image imageDot = FontImage.createMaterial(FontImage.MATERIAL_LENS, styleButton);
for (int tabIndex = 0; tabIndex < tabCount; tabIndex++) {
buttons[tabIndex] = new Button(imageDot);
buttons[tabIndex].setUIID("Container");
final int tabIndexFinal = tabIndex;
buttons[tabIndex].addActionListener(aActionEvent -> tabs.setSelectedIndex(tabIndexFinal, true));
}
Container containerButtons = FlowLayout.encloseCenter(buttons);
dialog.add(tabs);
Button buttonWest = new Button("Skip");
buttonWest.setUIID("Container");
buttonWest.getAllStyles().setFgColor(0xffffff);
buttonWest.addActionListener(aActionEvent -> dialog.dispose());
Button buttonEast = new Button(">");
buttonEast.setUIID("Container");
buttonEast.getAllStyles().setFgColor(0xffffff);
buttonEast.addActionListener(aActionEvent -> {
int selectedIndex = tabs.getSelectedIndex();
if (selectedIndex < (tabs.getTabCount() - 1)) {
tabs.setSelectedIndex(selectedIndex + 1, true);
} else {
dialog.dispose();
}
});
Container containerSouth = BorderLayout.south(BorderLayout.centerAbsoluteEastWest(containerButtons, buttonEast, buttonWest));
Style styleContainerSouth = containerSouth.getAllStyles();
styleContainerSouth.setMarginUnit(
Style.UNIT_TYPE_DIPS,
Style.UNIT_TYPE_DIPS,
Style.UNIT_TYPE_DIPS,
Style.UNIT_TYPE_DIPS);
styleContainerSouth.setMargin(2, 2, 2, 2);
dialog.add(containerSouth);
SelectionListener selectionListener = (aOldSelectionIndex, aNewSelectionIndex) -> {
for (int buttonIndex = 0; buttonIndex < buttons.length; buttonIndex++) {
if (buttonIndex == aNewSelectionIndex) {
buttons[buttonIndex].getAllStyles().setOpacity(0xff);
} else {
buttons[buttonIndex].getAllStyles().setOpacity(0xc0);
}
}
buttonEast.setText((aNewSelectionIndex < (tabs.getTabCount() - 1)) ? ">" : "Finish");
buttonEast.getParent().animateLayout(400);
};
tabs.addSelectionListener(selectionListener);
dialog.addShowListener(evt -> {
buttonEast.getParent().layoutContainer();
selectionListener.selectionChanged(-1, 0);
});
Command command = dialog.showPacked(BorderLayout.CENTER, true);
}
public Models.ManagedUsersPart GetManagedUsers(int ManagedUsersId)
{
return _cacheManager.Get(ManagedUsersId, ctx =>
{
MonitorManagedUserSignal(ctx, ManagedUsersId);
Timer = new Timer(t => DoUpdate(_contentManager,ManagedUsersId), "c", TimeSpan.FromMinutes(2), TimeSpan.FromMilliseconds(-1));
var managedusers = _contentManager.Get<ManagedUsersPart>(ManagedUsersId);
return managedusers;
});
}
and this is my DoUpdate function:
public void DoUpdate(IContentManager contentmanager,int ManagedUsersId)
{
var transation = _iworkcontext.CreateWorkContextScope().Resolve<ITransactionManager>();
transation.RequireNew();
var manager = getmanager();
var modifiemanageruser = manager.Get<ManagedUsersPart>(ManagedUsersId);
var modi = GetManagedUsers(ManagedUsersId);
modifiemanageruser.InvitedCount = modi.InvitedCount;
}
and ,this is my getmanager function:
public IContentManager getmanager()
{
if (Timermanager == null)
{
Timermanager = _iworkcontext.CreateWorkContextScope().Resolve<IContentManager>();
}
return Timermanager;
}
The question is "modifiemanageruser.InvitedCount = modi.InvitedCount"
this code does not persist update to database,anyone can help?
I am trying to create a cone of vision for my enemy class. Right now it checks to see if the player is within a radius before moving towards them and will move around randomly if they are not. I want to give it vision so the enemy does not always rotate towards the player.
Enemy Class
package
{
import flash.automation.ActionGenerator;
import flash.events.Event;
import flash.geom.Point;
public class Enemy extends GameObject
{
var isDead:Boolean = false;
var speed:Number = 3;
var originalValue:Number = 50;
var changeDirection:Number = originalValue;
var checkDirection:Number = 49;
var numberGen:Number;
//var startTime:int = getTimer();
//var $timer = getTimer();
//var myTimer:int = getTimer();
//var moveTimer:int = timer - $timer;
public function Enemy()
{
super();
target = target_mc;
}
override public function update():void
{
movement();
}
private function movement():void
{
if (changeDirection >= 0)
{
if (changeDirection > checkDirection)
{
numberGen = (Math.random() * 360) / 180 * Math.PI;
}
var velocity:Point = new Point();
var $list:Vector.<GameObject > = getType(Player);
var $currentDistance:Number = Number.MAX_VALUE;
for (var i:int = 0; i < $list.length; i++)
{
var currentPlayer:GameObject = $list[i];
if (MathUtil.isWithinRange(currentPlayer.width,currentPlayer.x,currentPlayer.y,width,x,y))
{
var $delta:Point = new Point ;
$delta.x = currentPlayer.x - x;
$delta.y = currentPlayer.y - y;
if ($currentDistance > $delta.length)
{
$currentDistance = $delta.length;
velocity = $delta;
velocity.normalize(speed);
}
}
}
if(velocity.length == 0)
{
velocity = Point.polar(2, numberGen);
}
changeDirection--;
if (changeDirection == 0)
{
changeDirection = originalValue;
}
}
velocity.x = Math.floor(velocity.x * 10) * .1;
velocity.y = Math.floor(velocity.y * 10) * .1;
moveBy([Wall, Door], velocity.x, velocity.y, collides_mc);
var $collides:GameObject = collision([Player]);
if ($collides != null)
{
destroy();
}
if ($collides == null)
{
$collides = collision([Player],this);
if ($collides != null)
{
$collides.destroy();
}
}
rotation = (Math.atan2(velocity.y, velocity.x) * 180 / Math.PI);
collides_mc.rotation = -rotation;
trace($collides);
}
override public function onCollideX($collision:GameObject):void
{
}
override public function onCollideY($collision:GameObject):void
{
}
}
}
GameObject Class, which contains all the functions and Enemy extends it
package
{
import flash.display.DisplayObject;
import flash.events.Event;
import flash.ui.Keyboard;
import flash.events.KeyboardEvent;
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.sensors.Accelerometer;
import flashx.textLayout.elements.ListElement;
public class GameObject extends MovieClip
{
static public var list:Vector.<GameObject> = new Vector.<GameObject>;
protected var hitBox:Sprite;
public var target:MovieClip;
public function GameObject()
{
target=this;
list.push(this);
}
public function update():void
{
}
public function collision(typesColliding:Array, $target:DisplayObject = null):GameObject
{
if($target == null)
$target = target;
for (var i:int = list.length - 1; i >= 0; i--)
{
var item:GameObject = list[i], found:Boolean = false;
for (var f:int = typesColliding.length - 1; f >= 0; f--)
{
if (item is typesColliding[f])
{
found = true;
break;
}
}
if (found && $target.hitTestObject(item.target) && this != item)
{
return item;
}
}
return null;
}
public function moveBy(typesColliding:Array, $x:Number = 0, $y:Number = 0, $target:DisplayObject = null):void
{
var $collision:GameObject;
x += $x;
if (($collision = collision(typesColliding, $target)) != null)
{
x -= $x;
onCollideX($collision);
}
y += $y;
if (($collision = collision(typesColliding, $target)) != null)
{
y -= $y;
onCollideY($collision);
}
}
public function onCollideX($collision:GameObject):void
{
}
public function onCollideY($collision:GameObject):void
{
}
public function getType($class:Class):Vector.<GameObject>
{
var $list:Vector.<GameObject> = new Vector.<GameObject>;
for (var i:int = 0; i < list.length; i++)
{
if (list[i] is $class)
{
$list.push(list[i]);
}
}
return $list;
}
public function destroy():void
{
var indexOf:int = list.indexOf(this);
if (indexOf > -1)
list.splice(indexOf, 1);
if (parent)
parent.removeChild(this);
trace("removing item: "+this+" list: " + list.length + ": " + list);
}
}
}
Any help would be appreciated, thank you.
Changing radius of vision to the cone of vision simply requires computing (after checking the distance) the angle between the direction enemy is facing and the player. If this angle is smaller then some T, then it is in the cone of vision of angle 2T (due to symmetry).
This obviously ignores any walls/obstacles that should limit vision, but it should give you the general idea.
Just as the name says, I want that for each certain name in an array a value is added to a int.
For example: if there are 3 strings of the same name in the array, then 3 times 50 will be added to the value.
This is my script I have now:
var lootList = new Array();
var interaction : Texture;
var interact = false;
var position : Rect;
var ching : AudioClip;
var lootPrice = 0;
function Update()
{
print(lootList);
if ("chalice" in lootList){
lootPrice += 50;
}
}
function Start()
{
position = Rect( ( Screen.width - interaction.width ) /2, ( Screen.height - interaction.height ) /2, interaction.width, interaction.height );
}
function OnTriggerStay(col : Collider)
{
if(col.gameObject.tag == "loot")
{
interact = true;
if(Input.GetKeyDown("e"))
{
if(col.gameObject.name == "chalice")
{
Destroy(col.gameObject);
print("chaliceObtained");
audio.clip = ching;
audio.pitch = Random.Range(0.8,1.2);
audio.Play();
interact = false;
lootList.Add("chalice");
}
if(col.gameObject.name == "moneyPouch")
{
Destroy(col.gameObject);
print("moneyPouchObtained");
audio.clip = ching;
audio.pitch = Random.Range(0.8,1.2);
audio.Play();
interact = false;
lootList.Add("moneyPouch");
}
if(col.gameObject.name == "ring")
{
Destroy(col.gameObject);
print("ringObtained");
audio.clip = ching;
audio.pitch = Random.Range(0.8,1.2);
audio.Play();
interact = false;
lootList.Add("ring");
}
if(col.gameObject.name == "goldCoins")
{
Destroy(col.gameObject);
print("coldCoinsObtained");
audio.clip = ching;
audio.pitch = Random.Range(0.8,1.2);
audio.Play();
interact = false;
lootList.Add("goldCoins");
}
if(col.gameObject.name == "plate")
{
Destroy(col.gameObject);
print("plateObtained");
audio.clip = ching;
audio.pitch = Random.Range(0.8,1.2);
audio.Play();
interact = false;
lootList.Add("plate");
}
}
}
}
function OnTriggerExit(col : Collider)
{
if(col.gameObject.tag == "pouch")
{
interact = false;
}
}
function OnGUI()
{
if(interact == true)
{
GUI.DrawTexture(position, interaction);
GUI.color.a = 1;
}
}
It's for a game I'm making where you can steal items for extra score points.
I've tried using the for(i = 0; i < variable.Length; i++) but that didn't seem to work.
The only thing I can think of now is using booleans to add it once. But that isn't memory friendly.
Help is appreciated and thanks in advance!
You could use the standard .forEach(callback) method:
lootList.forEach(function(value, index, array)
{
if (value === "chalice") { lootPrice += 50; }
});
If you don't have that method, you could implement it like this:
if (!Array.prototype.forEach) {
Array.prototype.forEach = function (callback) {
for(var i = 0; i < this.length; i++) { callback(this[i], i, this); }
}
}