My friend's GameElements.cs seems to have become corrupted in some way. We're both studying in the same class, and he sent me his project and I can't open the file either. I can't troubleshoot his solution, as he is using XNA and I'm using MonoGame.
Sadly, he does not have any back-ups (this way he'll learn the hard way though) and neither one of us are familiar with neither Visual Studio nor programming at all, as we're just a couple months into the course.
The file is still 12kb, even though I can only select/copy blank spaces. I have no idea if it's possible to restore the code from it, there is obviously data in the file.
This is a link to download the whole solution, though the corrupt file in question is "GameElements.cs". We both would appreciate it greatly if someone was able to recover the code! http://www.filedropper.com/xnabus
Please see below for the code from GameElements.cs. Hope this helps :). You could use any .Net Disassembler to do this. I used ILSpy and decompiled your code from XNA bus.exe file.
Note that, sometimes there could be minor issues with names of classes or methods. So, please go through the code once completely to ensure this.
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using System;
using System.Collections.Generic;
using System.Linq;
namespace XNA_bus
{
internal static class GameElements
{
public enum State
{
Menu,
Levels,
Level1,
Level2,
Level3,
Run,
Highscore,
Quit
}
private static Meny meny;
private static Levels levels;
private static Player player;
private static List<Fiender> Fiende;
private static List<GuldMynt> guldMynt;
private static List<Powerup> SuperSkepp;
private static List<Powerup> PenetratingBullets;
private static Texture2D guldMyntSprite;
private static Texture2D SuperskeppSprite;
private static Texture2D PenetratingbulletsSprite;
private static Utskrifter printText;
private static Bakgrund bakgrund;
private static Boss1 boss1;
private static int boss1Liv = 3;
private static int playerLiv = 1;
public static GameElements.State currentState;
public static void Initialize()
{
GameElements.guldMynt = new List<GuldMynt>();
GameElements.SuperSkepp = new List<Powerup>();
GameElements.PenetratingBullets = new List<Powerup>();
}
public static void LoadContent(ContentManager content, GameWindow window)
{
GameElements.player = new Player(content.Load<Texture2D>("Images/player/Player"), 0f, 200f, 2.5f, 4.5f, content.Load<Texture2D>("Images/player/bullet"));
GameElements.bakgrund = new Bakgrund(content.Load<Texture2D>("Images/bakgrund"), window);
GameElements.boss1 = new Boss1(content.Load<Texture2D>("Images/Enemies/Boss1"), 700f, 360f);
GameElements.meny = new Meny(0);
GameElements.meny.AddItem(content.Load<Texture2D>("Images/Meny/Start"), 1, window);
GameElements.meny.AddItem(content.Load<Texture2D>("Images/Meny/Highscore"), 6, window);
GameElements.meny.AddItem(content.Load<Texture2D>("Images/Meny/Avsluta"), 7, window);
GameElements.levels = new Levels(1);
GameElements.levels.AddItem(content.Load<Texture2D>("Images/Meny/Level 1"), 2, window);
GameElements.levels.AddItem(content.Load<Texture2D>("Images/Meny/Level 2"), 3, window);
GameElements.levels.AddItem(content.Load<Texture2D>("Images/Meny/Level 3"), 4, window);
GameElements.Fiende = new List<Fiender>();
Random random = new Random();
Texture2D tmpsprite = content.Load<Texture2D>("Images/Enemies/Predator");
for (int i = 0; i < 5; i++)
{
int rndX = random.Next(window.get_ClientBounds().Width / 2, window.get_ClientBounds().Width - tmpsprite.get_Width());
int rndY = random.Next(0, window.get_ClientBounds().Height - tmpsprite.get_Height());
Predator temp = new Predator(tmpsprite, (float)rndX, (float)rndY);
GameElements.Fiende.Add(temp);
}
tmpsprite = content.Load<Texture2D>("Images/Enemies/mina");
for (int i = 0; i < 5; i++)
{
int rndX = random.Next(window.get_ClientBounds().Width / 2, window.get_ClientBounds().Width - tmpsprite.get_Width());
int rndY = random.Next(0, window.get_ClientBounds().Height - tmpsprite.get_Height());
Mine temp2 = new Mine(tmpsprite, (float)rndX, (float)rndY);
GameElements.Fiende.Add(temp2);
}
GameElements.printText = new Utskrifter(content.Load<SpriteFont>("Font1"));
GameElements.guldMyntSprite = content.Load<Texture2D>("Images/Powerups/SpelMynt");
GameElements.SuperskeppSprite = content.Load<Texture2D>("Images/Powerups/PowerUp");
GameElements.PenetratingbulletsSprite = content.Load<Texture2D>("Images/Powerups/PowerUp2");
}
public static GameElements.State MenyUpdate(GameTime gameTime)
{
return (GameElements.State)GameElements.meny.Update(gameTime);
}
public static void MenyDraw(SpriteBatch spriteBatch)
{
GameElements.bakgrund.Draw(spriteBatch);
GameElements.meny.Draw(spriteBatch);
}
public static GameElements.State RunUpdate(ContentManager content, GameWindow window, GameTime gameTime)
{
GameElements.bakgrund.Update(window);
GameElements.player.Update(window, gameTime);
foreach (Fiender f in GameElements.Fiende.ToList<Fiender>())
{
foreach (Bullet b in GameElements.player.AntSkott.ToList<Bullet>())
{
if (f.CheckCollision(b))
{
f.Liv = false;
GameElements.player.poäng++;
if (!GameElements.player.PenetratingBullets)
{
GameElements.player.AntSkott.Remove(b);
}
else if (GameElements.player.PenetratingBullets)
{
if (gameTime.get_TotalGameTime().TotalSeconds > GameElements.player.PenetratingBulletsTime + 2.0)
{
GameElements.player.PenetratingBullets = false;
}
}
}
}
if (f.Liv)
{
if (f.CheckCollision(GameElements.player))
{
GameElements.playerLiv--;
GameElements.player.Liv = false;
}
f.Update(window);
}
else
{
GameElements.Fiende.Remove(f);
}
if (!f.FKoll)
{
GameElements.Fiende.Remove(f);
GameElements.playerLiv--;
}
}
if (GameElements.boss1.Liv)
{
foreach (Bullet b in GameElements.player.AntSkott.ToList<Bullet>())
{
if (GameElements.boss1.CheckCollision(b))
{
GameElements.player.AntSkott.Remove(b);
GameElements.boss1Liv--;
}
}
GameElements.boss1.Update(window);
}
if (GameElements.boss1Liv == 0)
{
GameElements.boss1.Liv = false;
}
GameElements.State result;
if (!GameElements.boss1.Liv)
{
GameElements.Reset(window, content);
result = GameElements.State.Menu;
}
else
{
Random random = new Random();
int newMynt = random.Next(1, 200);
if (newMynt == 1)
{
int rndX = random.Next(0, window.get_ClientBounds().Width - GameElements.guldMyntSprite.get_Width());
int rndY = random.Next(0, window.get_ClientBounds().Height - GameElements.guldMyntSprite.get_Height());
GameElements.guldMynt.Add(new GuldMynt(GameElements.guldMyntSprite, (float)rndX, (float)rndY));
}
foreach (GuldMynt gc in GameElements.guldMynt.ToList<GuldMynt>())
{
if (gc.Liv)
{
gc.Update(gameTime);
if (gc.CheckCollision(GameElements.player))
{
GameElements.guldMynt.Remove(gc);
GameElements.player.Poäng++;
}
}
else
{
GameElements.guldMynt.Remove(gc);
}
}
Random rnd = new Random();
int newPowerup = rnd.Next(1, 300);
if (newPowerup == 1)
{
int rndX = rnd.Next(0, window.get_ClientBounds().Width - GameElements.SuperskeppSprite.get_Width());
int rndY = rnd.Next(0, window.get_ClientBounds().Height - GameElements.SuperskeppSprite.get_Height());
GameElements.SuperSkepp.Add(new Powerup(GameElements.SuperskeppSprite, (float)rndX, (float)rndY));
}
foreach (Powerup Power in GameElements.SuperSkepp.ToList<Powerup>())
{
if (Power.Liv)
{
Power.Update(gameTime);
if (Power.CheckCollision(GameElements.player))
{
GameElements.SuperSkepp.Remove(Power);
GameElements.player.SuperSkepp = true;
GameElements.player.SuperSkeppTime = gameTime.get_TotalGameTime().TotalSeconds;
}
}
else
{
GameElements.SuperSkepp.Remove(Power);
}
}
Random rnd2 = new Random();
int NewPowerup = rnd2.Next(1, 300);
if (NewPowerup == 1)
{
int rndX = rnd2.Next(0, window.get_ClientBounds().Width - GameElements.PenetratingbulletsSprite.get_Width());
int rndY = rnd2.Next(0, window.get_ClientBounds().Height - GameElements.PenetratingbulletsSprite.get_Height());
GameElements.PenetratingBullets.Add(new Powerup(GameElements.PenetratingbulletsSprite, (float)rndX, (float)rndY));
}
foreach (Powerup P in GameElements.PenetratingBullets.ToList<Powerup>())
{
if (P.Liv)
{
P.Update(gameTime);
if (P.CheckCollision(GameElements.player))
{
GameElements.PenetratingBullets.Remove(P);
GameElements.player.PenetratingBullets = true;
GameElements.player.PenetratingBulletsTime = gameTime.get_TotalGameTime().TotalSeconds;
}
}
else
{
GameElements.PenetratingBullets.Remove(P);
}
}
if (!GameElements.player.Liv || GameElements.playerLiv == 0)
{
GameElements.Reset(window, content);
result = GameElements.State.Menu;
}
else
{
result = GameElements.State.Run;
}
}
return result;
}
public static void RunDraw(SpriteBatch spriteBatch)
{
GameElements.boss1.Draw(spriteBatch);
GameElements.bakgrund.Draw(spriteBatch);
GameElements.player.Draw(spriteBatch);
foreach (Fiender f in GameElements.Fiende)
{
f.Draw(spriteBatch);
}
foreach (GuldMynt gc in GameElements.guldMynt)
{
gc.Draw(spriteBatch);
}
foreach (Powerup Power in GameElements.SuperSkepp)
{
Power.Draw(spriteBatch);
}
foreach (Powerup p in GameElements.PenetratingBullets)
{
p.Draw(spriteBatch);
}
GameElements.printText.Print("Points:" + GameElements.player.poäng, spriteBatch, 0, 0);
GameElements.printText.Print("Boss Liv:" + GameElements.boss1Liv, spriteBatch, 680, 0);
GameElements.printText.Print("Liv:" + GameElements.playerLiv, spriteBatch, 0, 20);
}
public static GameElements.State HighScoreUpdate()
{
GameElements.State result;
if (Keyboard.GetState().IsKeyDown(27))
{
result = GameElements.State.Menu;
}
else
{
result = GameElements.State.Highscore;
}
return result;
}
public static void HighScoreDraw(SpriteBatch spriteBatch)
{
}
private static void Reset(GameWindow window, ContentManager content)
{
GameElements.boss1Liv = 3;
GameElements.playerLiv = 1;
GameElements.boss1.Liv = true;
GameElements.player.Reset(0f, 200f, 2.5f, 4.5f);
GameElements.Fiende.Clear();
Random random = new Random();
Texture2D tmpsprite = content.Load<Texture2D>("Images/Enemies/Predator");
for (int i = 0; i < 5; i++)
{
int rndX = random.Next(window.get_ClientBounds().Width / 2, window.get_ClientBounds().Width - tmpsprite.get_Width());
int rndY = random.Next(0, window.get_ClientBounds().Height - tmpsprite.get_Height());
Predator temp = new Predator(tmpsprite, (float)rndX, (float)rndY);
GameElements.Fiende.Add(temp);
}
tmpsprite = content.Load<Texture2D>("Images/Enemies/mina");
for (int i = 0; i < 5; i++)
{
int rndX = random.Next(window.get_ClientBounds().Width / 2, window.get_ClientBounds().Width - tmpsprite.get_Width());
int rndY = random.Next(0, window.get_ClientBounds().Height - tmpsprite.get_Height());
Mine temp2 = new Mine(tmpsprite, (float)rndX, (float)rndY);
GameElements.Fiende.Add(temp2);
}
}
public static GameElements.State LevelsUpdate(GameTime gameTime)
{
return (GameElements.State)GameElements.levels.Update(gameTime);
}
public static void LevelsDraw(SpriteBatch spritebatch)
{
GameElements.bakgrund.Draw(spritebatch);
GameElements.levels.Draw(spritebatch);
}
}
}
Related
I have a widget made up of 2 TextViews, 2 ImageViews, and 2 TextClocks. I am trying to update the widget using a ScreenListener (code below) and an alarm. I want all views to update when the screen is turned On. Also, a repeating alarm is set when the screen is turned On. The alarm is used to trigger the update of the battery level indicator (an ImageView). The image for the battery level indicator is generated using the ProgressRing (code below). The alarm is cancelled when the screen is turned Off. The TextClocks take care of themselves.
Everything works when debugging using the emulator or my phone. The various components update when I turn the screen On and Off. However, when I install the widget on my phone, the widget stops updating after a period of time. Initially, I can turn the screen On and Off and everything updates. And, I can plug (or unplug) the phone and the alarm will update the battery level indicator. But, after some period of time (I think with the screen Off), updating stops. Turning the screen On no longer updates anything and, I beleive, the alarm is no longer set. (Note: The TextClock continue to work and show the correct time.)
When debugging, I have seen the instances of the ScreenLister and ProgressRing become null. So, I've included checks for this and make new instances when it happens. This doesn't seem like the right solution. Should this be occurring?
Is the system killing my widget? Is there a way around this, if so? Is my AppWidgetProvider somehow losing it's connection to the RemoteViews?
Thanks for any help. And, let me know if you need more information.
P.S. I'm currently building for Android 9.0. And, I'm new to Android programming.
AppWidgetProvider
namespace ClockCalBattery
{
[BroadcastReceiver(Enabled = true)]
[IntentFilter(new string[] { "android.appwidget.action.APPWIDGET_UPDATE", Intent.ActionUserPresent})]
[MetaData("android.appwidget.provider", Resource = "#xml/appwidgetprovider")]
public class CCBWidget : AppWidgetProvider, ScreenStateListener
{
public static ProgressRing progressRing = new ProgressRing();
private static String ACTION_UPDATE_BATTERY = "com.lifetree.clockcalbattery.UPDATE-BATTERY";
public static ScreenListener mScreenListener;
public static int n_alarms = 0;
public override void OnReceive(Context context, Intent intent)
{
base.OnReceive(context, intent);
if (intent.Action == ACTION_UPDATE_BATTERY)
{
update_batteryLevel(context);
if (mScreenListener == null)
{
mScreenListener = new ScreenListener(context);
mScreenListener.begin(this);
}
if (progressRing == null)
{
progressRing = new ProgressRing();
}
}
}
public override void OnEnabled(Context context)
{
base.OnEnabled(context);
if (mScreenListener == null)
{
mScreenListener = new ScreenListener(context);
mScreenListener.begin(this);
}
if (progressRing == null)
{
progressRing = new ProgressRing();
}
update_batteryLevel(Application.Context);
update_nextAlarm(Application.Context);
}
public override void OnDisabled(Context context)
{
base.OnDisabled(context);
}
public override void OnUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds)
{
base.OnUpdate(context, appWidgetManager, appWidgetIds);
mScreenListener = new ScreenListener(context);
progressRing = new ProgressRing();
var me = new ComponentName(context, Java.Lang.Class.FromType(typeof(CCBWidget)).Name);
var widgetView = BuildRemoteViews(context, appWidgetIds);
appWidgetManager.UpdateAppWidget(me, widgetView);
}
private RemoteViews BuildRemoteViews(Context context, int[] appWidgetIds)
{
RemoteViews widgetView = new RemoteViews(context.PackageName, Resource.Layout.CCBWidget);
update_TodaysDate(widgetView);
update_nextAlarm(context, widgetView);
update_batteryLevel(widgetView);
return widgetView;
}
private void update_TodaysDate(RemoteViews widgetView)
{
string today = DateTime.Today.ToString("D");
widgetView.SetTextViewText(Resource.Id.longDate, today);
}
private void update_nextAlarm(Context context, RemoteViews widgetView)
{
AlarmManager am = (AlarmManager)context.GetSystemService(Context.AlarmService);
AlarmManager.AlarmClockInfo alarmInfo = am.NextAlarmClock;
if (alarmInfo != null)
{
long time = alarmInfo.TriggerTime;
DateTime alarmDateTime = new DateTime(1970, 1, 1).AddMilliseconds(time).ToLocalTime();
string alarmTime = alarmDateTime.ToString("ddd ");
alarmTime += alarmDateTime.ToString("t");
widgetView.SetTextViewText(Resource.Id.textView_alarmTime, alarmTime);
widgetView.SetImageViewResource(Resource.Id.imageView_alarmIcon, Resource.Drawable.whiteOnBlack_clock);
}
else
{
widgetView.SetTextViewText(Resource.Id.textView_alarmTime, "");
widgetView.SetImageViewResource(Resource.Id.imageView_alarmIcon, Resource.Drawable.navigation_empty_icon);
}
}
private void update_nextAlarm(Context mContext)
{
RemoteViews widgetView = new RemoteViews(mContext.PackageName, Resource.Layout.CCBWidget);
update_nextAlarm(mContext, widgetView);
var me = new ComponentName(mContext, Java.Lang.Class.FromType(typeof(CCBWidget)).Name);
var awm = AppWidgetManager.GetInstance(mContext);
awm.UpdateAppWidget(me, widgetView);
}
private void update_batteryLevel(RemoteViews widgetView)
{
progressRing.setProgress((int)(Battery.ChargeLevel * 100.0));
progressRing.drawProgressBitmap();
widgetView.SetImageViewBitmap(Resource.Id.progressRing, progressRing.ring);
}
private void update_batteryLevel(Context mContext)
{
RemoteViews widgetView = new RemoteViews(mContext.PackageName, Resource.Layout.CCBWidget);
update_batteryLevel(widgetView);
var me = new ComponentName(mContext, Java.Lang.Class.FromType(typeof(CCBWidget)).Name);
var awm = AppWidgetManager.GetInstance(mContext);
awm.UpdateAppWidget(me, widgetView);
}
public static void turnUpdateAlarmOnOff(Context context, bool turnOn, int time)
{
AlarmManager alarmManager = (AlarmManager)context.GetSystemService(Context.AlarmService);
Intent intent = new Intent(context, typeof(CCBWidget));
intent.SetAction(ACTION_UPDATE_BATTERY);
PendingIntent pendingIntent = PendingIntent.GetBroadcast(context, 0, intent, 0);
if (turnOn)
{
// Add extra 1 sec because sometimes ACTION_BATTERY_CHANGED is called after the first alarm
alarmManager.SetInexactRepeating(AlarmType.ElapsedRealtime, SystemClock.ElapsedRealtime() + 1000, time * 1000, pendingIntent);
n_alarms++;
}
else
{
alarmManager.Cancel(pendingIntent);
n_alarms--;
}
}
public void onScreenOn()
{
if (mScreenListener == null)
{
mScreenListener = new ScreenListener(Application.Context);
mScreenListener.begin(this);
}
if (progressRing == null)
{
progressRing = new ProgressRing();
}
update_batteryLevel(Application.Context);
update_nextAlarm(Application.Context);
turnUpdateAlarmOnOff(Application.Context, true, 60);
}
public void onScreenOff()
{
turnUpdateAlarmOnOff(Application.Context, false, 1);
}
public void onUserPresent()
{
//Console.WriteLine("onUserPresent");
}
}
}
ScreenListener
namespace ClockCalBattery
{
public class ScreenListener
{
private Context mContext;
private ScreenBroadcastReceiver mScreenReceiver;
private static ScreenStateListener mScreenStateListener;
public ScreenListener(Context context)
{
mContext = context;
mScreenReceiver = new ScreenBroadcastReceiver();
}
/**
* screen BroadcastReceiver
*/
private class ScreenBroadcastReceiver : BroadcastReceiver
{
private String action = null;
public override void OnReceive(Context context, Intent intent)
{
action = intent.Action;
if (Intent.ActionScreenOn == action)
{ // screen on
mScreenStateListener.onScreenOn();
}
else if (Intent.ActionScreenOff == action)
{ // screen off
mScreenStateListener.onScreenOff();
}
else if (Intent.ActionUserPresent == action)
{ // unlock
mScreenStateListener.onUserPresent();
}
}
}
/**
* begin to listen screen state
*
* #param listener
*/
public void begin(ScreenStateListener listener)
{
mScreenStateListener = listener;
registerListener();
getScreenState();
}
/**
* get screen state
*/
private void getScreenState()
{
PowerManager manager = (PowerManager)mContext
.GetSystemService(Context.PowerService);
if (manager.IsInteractive)
{
if (mScreenStateListener != null)
{
mScreenStateListener.onScreenOn();
}
}
else
{
if (mScreenStateListener != null)
{
mScreenStateListener.onScreenOff();
}
}
}
/**
* stop listen screen state
*/
public void unregisterListener()
{
mContext.UnregisterReceiver(mScreenReceiver);
}
/**
* regist screen state broadcast
*/
private void registerListener()
{
IntentFilter filter = new IntentFilter();
filter.AddAction(Intent.ActionScreenOn);
filter.AddAction(Intent.ActionScreenOff);
filter.AddAction(Intent.ActionUserPresent);
mContext.ApplicationContext.RegisterReceiver(mScreenReceiver, filter);
//mContext.RegisterReceiver(mScreenReceiver, filter);
}
public interface ScreenStateListener
{// Returns screen status information to the caller
void onScreenOn();
void onScreenOff();
void onUserPresent();
}
}
}
ProgressRing
namespace ClockCalBattery
{
public class ProgressRing
{
private int max = 100;
public int progress;
private Path path = new Path();
Color color = new Color(50, 50, 255, 255);
private Paint paint;
private Paint mPaintProgress;
private RectF mRectF;
private Paint batteryLevelTextPaint;
private Paint batteryStateTextPaint;
private String batteryLevelText = "0%";
private String batteryStateText = null;
private BatteryState bs;
private Rect textBounds = new Rect();
private int centerY;
private int centerX;
private float swipeAndgle = 0;
public Bitmap ring;
private int bitmapWidth = 70;
private int bitmapHeight = 70;
public ProgressRing()
{
progress = -1;
paint = new Paint();
paint.AntiAlias = true;
paint.StrokeWidth = 1;
paint.SetStyle(Paint.Style.Stroke);
paint.Color = color;
mPaintProgress = new Paint();
mPaintProgress.AntiAlias = true;
mPaintProgress.SetStyle(Paint.Style.Stroke);
mPaintProgress.StrokeWidth = 5;
mPaintProgress.Color = color;
batteryLevelTextPaint = new Paint();
batteryLevelTextPaint.AntiAlias = true;
batteryLevelTextPaint.SetStyle(Paint.Style.Fill);
batteryLevelTextPaint.Color = color;
batteryLevelTextPaint.StrokeWidth = 1;
batteryStateTextPaint = new Paint();
batteryStateTextPaint.AntiAlias = true;
batteryStateTextPaint.SetStyle(Paint.Style.Fill); ;
batteryStateTextPaint.Color = color;
batteryStateTextPaint.StrokeWidth = 1;
//batteryStateTextPaint.SetTypeface(Typeface.Create(Typeface.Default, TypefaceStyle.Bold));
Init_ring();
}
private void Init_ring()
{
int viewWidth = bitmapWidth;
int viewHeight = bitmapHeight;
float radius = (float)(bitmapHeight / 2.0);
path.Reset();
centerX = viewWidth / 2;
centerY = viewHeight / 2;
path.AddCircle(centerX, centerY, radius, Path.Direction.Cw);
float smallCirclRadius = radius - (float)(0.1 * radius);
path.AddCircle(centerX, centerY, smallCirclRadius, Path.Direction.Cw);
//mRectF = new RectF(0, 0, viewWidth, viewHeight);
mRectF = new RectF(centerX - smallCirclRadius, centerY - smallCirclRadius, centerX + smallCirclRadius, centerY + smallCirclRadius);
batteryLevelTextPaint.TextSize = radius * 0.5f;
batteryStateTextPaint.TextSize = radius * 0.30f;
}
internal void setProgress(int progress)
{
this.progress = progress;
int percentage = progress * 100 / max;
swipeAndgle = percentage * 360 / 100;
batteryLevelText = percentage + "%";
batteryStateText = null;
bs = Battery.State;
if (bs == BatteryState.Charging)
batteryStateText = "Charging";
else if (percentage > 99)
batteryStateText = "Full";
else if (percentage < 15)
batteryStateText = "Low";
}
internal void drawProgressBitmap()
{
ring = Bitmap.CreateBitmap(bitmapWidth, bitmapHeight, Bitmap.Config.Argb8888);
Canvas c = new Canvas(ring);
byte r = 0;
byte g = 0;
byte b = 0;
byte a = 255;
hls2rgb(swipeAndgle * (120.0 / 360.0), 1, 128, ref r, ref g, ref b);
paint.Color = new Color(r, g, b, a);
mPaintProgress.Color = new Color(r, g, b, a);
batteryLevelTextPaint.Color = new Color(r, g, b, a);
batteryStateTextPaint.Color = new Color(r, g, b, a);
c.DrawArc(mRectF, 270, swipeAndgle, false, mPaintProgress);
drawTextCentred(c);
}
private void drawTextCentred(Canvas c)
{
batteryLevelTextPaint.GetTextBounds(batteryLevelText, 0, batteryLevelText.Length, textBounds);
c.DrawText(batteryLevelText, centerX - textBounds.ExactCenterX(), centerY - textBounds.ExactCenterY(), batteryLevelTextPaint);
if (batteryStateText != null)
{
batteryStateTextPaint.GetTextBounds(batteryStateText, 0, batteryStateText.Length, textBounds);
c.DrawText(batteryStateText, centerX - textBounds.ExactCenterX(), centerY - textBounds.ExactCenterY() + 15, batteryStateTextPaint);
}
}
public void hls2rgb(double color_wheel_angle, double tlen, byte ilum,
ref byte color_r, ref byte color_g, ref byte color_b)
{
double rlum, rm1, rm2;
if (ilum > 255) ilum = 255;
if (ilum < 0) ilum = 0;
if (tlen > 1) tlen = 1;
if (tlen < 0) tlen = 0;
rlum = (double)ilum / 255;
if (rlum < 0.5)
rm2 = rlum * (1.0 + tlen);
else
rm2 = rlum + tlen - (rlum * tlen);
rm1 = (2.0 * rlum) - rm2;
if (tlen == 0)
{
color_r = ilum;
color_g = ilum;
color_b = ilum;
}
else
{
color_g = (byte)(value(rm1, rm2, color_wheel_angle + 120) * 255);
color_b = (byte)(value(rm1, rm2, color_wheel_angle) * 255);
color_r = (byte)(value(rm1, rm2, color_wheel_angle - 120) * 255);
}
return;
}
public double value(double r1, double r2, double angle)
{
double value;
angle = angle - 120;
if (angle > 360) angle = angle - 360;
if (angle < 0) angle = angle + 360;
if (angle < 60)
value = r1 + (r2 - r1) * angle / 60;
else if (angle < 180)
value = r2;
else if (angle < 240)
value = r1 + (r2 - r1) * (240 - angle) / 60;
else
value = r1;
return (value);
}
}
}
I am currently working on my thesis project, this is an application that writes tablature by ASIO drivers. In short, write what you play. I'm new in all regards Naudio and I'm having poblemas to transform sound into FFT. I am capturing the sound with a device called "GuitarLink" which runs through ASIO4ALL.
So I need to compare frequencies for the chord in real time.
Currently, the program gives me two values, X and Y.
(I am using "SampleAggregator" Class and AsioOut)
MAIN
private SampleAggregator sampleAggregator = new(fftLength);
public MainWindow()
{
InitializeComponent();
dispatcherTimer.Tick += new EventHandler(SoClose);
dispatcherTimer.Interval = new TimeSpan(0, 0, 0, 0, 500);
dispatcherTimer.Start();
}
void SoClose(object sender, EventArgs e)
{
try
{
if (PBass)
{
sampleAggregator.PerformFFT = true;
sampleAggregator.FftCalculated += new EventHandler<FftEventArgs>(FftCalculated);
AsioOut asioOut = new();
BufferedWaveProvider wavprov = new(new WaveFormat(48000, 1));
asioOut.AudioAvailable += new EventHandler<AsioAudioAvailableEventArgs>(asio_DataAvailable);
asioOut.InitRecordAndPlayback(wavprov, 1, 25);
asioOut.Play();
I1E.Text = frecuencia.ToString();
}
}
catch
{
MessageBox.Show("Error de bajo presupuesto", "Obviamente algo anda mal");
}
}
private void FftCalculated(object sender, FftEventArgs e)
{
for (int i = 0; i < e.Result.Length; ++i)
{
A = e.Result[i].X;
B = e.Result[i].Y;
frecuencia = B;
Debug.WriteLine($"FFT: X={e.Result[i].X} Y={e.Result[i].Y}");
}
}
void asio_DataAvailable(object sender, AsioAudioAvailableEventArgs e)
{
byte[] buf = new byte[e.SamplesPerBuffer * 4];
for (int i = 0; i < e.InputBuffers.Length; i++)
{
Marshal.Copy(e.InputBuffers[i], buf, 0, e.SamplesPerBuffer * 4);
Marshal.Copy(buf, 0, e.OutputBuffers[i], e.SamplesPerBuffer * 4);
}
for (int i = 0; i < buf.Length; i = i + 4)
{
float sample = Convert.ToSingle(buf[i] + buf[i + 1] + buf[i + 2] + buf[i + 3]);
sampleAggregator.Add(sample);
}
e.WrittenToOutputBuffers = true;
}
SampleAggregator class
public class SampleAggregator
{
// FFT
public event EventHandler<FftEventArgs> FftCalculated;
public bool PerformFFT { get; set; }
// This Complex is NAudio's own!
private Complex[] fftBuffer;
private FftEventArgs fftArgs;
private int fftPos;
private int fftLength;
private int m;
public SampleAggregator(int fftLength)
{
if (!IsPowerOfTwo(fftLength))
throw new ArgumentException("FFT Length must be a power of two");
this.m = (int)Math.Log(fftLength, 2.0);
this.fftLength = fftLength;
this.fftBuffer = new Complex[fftLength];
this.fftArgs = new FftEventArgs(fftBuffer);
}
public void Add(float value)
{
if (PerformFFT && FftCalculated != null)
{
fftBuffer[fftPos].X = (float)(value * FastFourierTransform.HammingWindow(fftPos, fftLength));
fftBuffer[fftPos].Y = 0; // This is always zero with audio.
fftPos++;
if (fftPos >= fftLength)
{
fftPos = 0;
FastFourierTransform.FFT(true, m, fftBuffer);
FftCalculated(this, fftArgs);
}
}
}
static bool IsPowerOfTwo(int x) => (x & (x - 1)) == 0;
}
public class FftEventArgs : EventArgs
{
public Complex[] Result { get; private set; }
public string resultado = "";
[DebuggerStepThrough]
public FftEventArgs(Complex[] result) => Result = result;
void FftCalculated(object sender, FftEventArgs e)
{
}
}
Well the problem is that when I play a note, the values that are delivered are not affected.
So Im making tetris and I dont know how to draw the blocks( L,I,Z etc) I have one block as Texture2D and every class for the blocks look like this:
namespace Tetris
{
public class ZBlock
{
Color Color;
const int x = 4;
const int y = 4;
bool[,] vorm;
public bool[,] zblock()
{
vorm = new bool[x, y];
for(int i=0; i< x; i++)
for (int j=0; j<y; j++)
{
vorm[i, j] = false;
vorm[0, 0] = true;
vorm[1, 0] = true;
vorm[1, 1] = true;
vorm[2, 1] = true;
}
Color = Color.Purple;
return vorm;
}
}
and this is the block class:
namespace Tetris
{
public class Block
{
Texture2D block;
Vector2 BlockPosition = new Vector2(30, 30);
float FallTimer;
Random Random = new Random();
ZBlock zBlock = new ZBlock();
TBlock tBlock = new TBlock();
SBlock sBlock = new SBlock();
OBlock oBlock = new OBlock();
JBlock jBlock = new JBlock();
LBlock lBlock = new LBlock();
IBlock iblock = new IBlock();
public bool[,] blockvorm()
{
bool[,] vorm;
vorm = new bool[4, 4];
vorm[3, 3] = false;
int r = Random.Next(7);
if (r == 0)
{
ZBlock.zblock();
}
else if (r == 1)
{
TBlock.tblock();
}
else if (r == 2)
{
SBlock.sblock();
}
else if (r == 3)
{
OBlock.oblock();
}
else if (r == 4)
{
JBlock.jblock();
}
else if (r == 5)
{
LBlock.lblock();
}
else if (r == 6)
{
IBlock.iblock();
}
return vorm;
}
public TBlock TBlock
{
get { return tBlock; }
}
public ZBlock ZBlock
{
get { return zBlock; }
}
public SBlock SBlock
{
get { return sBlock; }
}
public OBlock OBlock
{
get { return oBlock; }
}
public JBlock JBlock
{
get { return jBlock; }
}
public LBlock LBlock
{
get { return lBlock; }
}
public IBlock IBlock
{
get { return iblock; }
}
public void Draw(GameTime gameTime, SpriteBatch spriteBatch, ContentManager Content)
{
block = Content.Load<Texture2D>("Block");
int[,] Grid = Tetris.GameWorld.TetrisGrid;
spriteBatch.Begin();
spriteBatch.Draw(?????????????);
spriteBatch.End();
}
So the problem is: I dont know how to draw those blocks (I know how to draw one block but I want the complete ones). I thought maybe ZBlock.vorm or ZBLock.zblock but both give errors.
Does anyone know how to draw the blocks?
Ok so here is a partial answer. What you want to do is basically just draw each block with a certain offset from the next block equal to: blockWidth / 2 in pixels. This means that the blocks will be correctly orientated without overlap.
Here is what you should put in the draw statement:
public void Draw(int theXPosition, int theYPosition, Color theColor, SpriteBatch theSpriteBatch, Texture2D theBlockTexture)
{
int aTextureStartX = Color * Convert.ToInt32(mBlockSize);
for (int aBlock = 0; aBlock < mNumberOfBlocks; aBlock++)
{
int aXPosition = (int)(theXPosition + (CurrentShape[Rotation, aBlock, 0] * mBlockSize));
int aYPosition = (int)(theYPosition + (CurrentShape[Rotation, aBlock, 1] * mBlockSize));
theSpriteBatch.Draw(theBlockTexture, new Rectangle(aXPosition, aYPosition, mBlockSize, mBlockSize), new Rectangle(aTextureStartX, 0, mBlockSize, mBlockSize),
}
}
This is from a blog: http://www.xnadevelopment.com/tutorials/fallingblocksyoumovetomakelines/fallingblocksyoumovetomakelines.shtml
The source code is at the top of the page.
I am developing a game in C# .But it has some infinite loop that prevents form from being loaded. I have tried many solutions available on internet, But that doesn't seems to work.
My problem is :"How to load the form before execution of while loop."?
My Program.cs Source
namespace SumSwamp
{
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
var window = new Form1();
window.Show();
}
}
}
Form1.cs :
namespace SumSwamp
{
public partial class Form1 : Form
{
public static int DieLargeNum = 0;
public static int DieSmallNum = 0;
public static int DieOperator = 0;
public static int DieTotal = 0;
public static int TotalSpaces = 42;
public static int CompSum = 0;
public static int PlayerSum = 0;
public static Boolean PlayersRoll = true;
public static Boolean WaitForRoll = true;
public static int Turn = 0;
public Form1()
{
InitializeComponent();
this.Load += new EventHandler(this.Form1_Load);
while(Turn == 0) //INFINITE LOOP
{
if (WaitForRoll==false)
{
DieTotal=DieLargeNum;
Random rnd1 = new Random();
DieLargeNum = rnd1.Next(1, 7);
if (DieTotal>DieLargeNum)
{
Turn = 1;
labelStatus.Text = "Player 1's Turn";
WaitForRoll=true;
}
else
{
Turn = 2;
labelStatus.Text = "Player 2's Turn";
WaitForRoll = false;
}
}
}
while ((CompSum < TotalSpaces) & (PlayerSum < TotalSpaces))//INFINITE LOOP
{
while (Turn == 1)
{
if (WaitForRoll == false)
{
if (DieOperator == 1)
{
DieTotal = DieLargeNum + DieSmallNum;
}
else
{
if (DieLargeNum > DieSmallNum)
{
DieTotal = DieLargeNum - DieSmallNum;
}
else
{
DieTotal = DieSmallNum - DieLargeNum;
}
}
PlayerSum = PlayerSum + DieTotal;
Turn = 2;
PlayersRoll = false;
labelStatus.Text = "Player 2's Turn";
}
}
while (Turn == 2)
{
Random rnd1 = new Random();
DieLargeNum = rnd1.Next(1, 7);
Random rnd2 = new Random();
DieSmallNum = rnd2.Next(1, 7);
Random rnd3 = new Random();
DieOperator = rnd3.Next(1, 3);
labelDieLargeNum.Text = DieLargeNum.ToString();
labelDieSmallNum.Text = DieSmallNum.ToString();
if (DieOperator == 1)
{
labelDieOperator.Text = "+";
}
else
{
labelDieOperator.Text = "-";
}
if (DieOperator == 1)
{
DieTotal = DieLargeNum + DieSmallNum;
}
else
{
if (DieLargeNum > DieSmallNum)
{
DieTotal = DieLargeNum - DieSmallNum;
}
else
{
DieTotal = DieSmallNum - DieLargeNum;
}
}
CompSum = CompSum + DieTotal;
Turn = 1;
PlayersRoll = true;
labelStatus.Text = "Player 1's Turn";
}
}
if (CompSum>=TotalSpaces)
{
labelResult.Text = "CPU Player has won!";
}
else
{
labelResult.Text = "You win!";
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void buttonRoll_Click(object sender, EventArgs e)
{
if (PlayersRoll == true)
{
Random rnd1 = new Random();
DieLargeNum = rnd1.Next(1, 7);
Random rnd2 = new Random();
DieSmallNum = rnd2.Next(1, 7);
Random rnd3 = new Random();
DieOperator = rnd3.Next(1, 3);
WaitForRoll = false;
labelDieLargeNum.Text = DieLargeNum.ToString();
labelDieSmallNum.Text = DieSmallNum.ToString();
if(DieOperator == 1)
{
labelDieOperator.Text = "+";
}
else
{
labelDieOperator.Text = "-";
}
}
}
}
}
If you put your infinite loop in the Form.Enter() event, the form will be loaded first and then run your loop. But the UI will be unresponsive if you're really in an infinite loop.
Usually UI games are driven by user interaction with controls. So, instead of an infinite loop where you have "WaitForRoll", you just have a button that says "Roll", and when they click it you run your code for that particular event (of rolling the dice).
If you do have to run a loop while the user isn't interacting with controls, it should be done in a separate thread, like a BackgroundWorker or Task.
Greetings
I genereated a terrain with this equation:
H(x,y) = (abs(sin(x * y)) + abs(sin(0,2 * x) + sin(0,4 * y)) + abs(cos(0,12 * x) + cos(0,47 * y))) * e^(0.005*(x+y))
Now, this gives me a mix of featuresize, and a nice slope. This works fine, when I plot it using scilab.
I tried to import this in a c# application.
The terrain is created in this code:
using System;
using System.Drawing;
using System.Windows.Forms;
using Microsoft.DirectX.Direct3D;
using Microsoft.DirectX;
using System.Collections.Generic;
namespace Kamera_eins
{
public partial class Terrain : Form
{
public double[,] DTM;
string response ;
public Terrain()
{
InitializeComponent();
response = "";
DTM = new double[2048/4,2048/4];
}
public void BoxTheSky()
{
}
public void BoxTheLand()
{
mesh();
surf();
}
public void begin()
{
}
public void mesh()
{
response = "";
int i = new int();
int j = new int();
i = 0;
j = 0;
for (i=0;i<2048/4 ;i++ ) {
for (j=0;j<2048/4 ;j++ ) {
DTM[i,j] = Math.Abs (Math.Sin (j*i)) + Math.Abs(Math.Sin(0.2*i) * Math.Sin(0.4*j) ) + Math.Abs(Math.Cos(0.12* i) * Math.Cos(0.47*j));
DTM[i,j] = Math.Pow(Math.E, (0.012* (i + j)));
}
}
response = "DTM mesh ready";
}
public void surf()
{
}
}
}
This is kept in a file called terrain.cs, and i make this a winform, because i plan to add a simple textbox, where i can later make some sort of realtime log of the process.
Now, there is another file, and in that file, intend to display this terrain. this second file goes as follows:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using System.Data;
using System.IO;
using Microsoft.DirectX;
using Microsoft.DirectX.Direct3D;
using Microsoft.DirectX.DirectInput;
namespace Kamera_eins
{
public class viewport : Form
{
public Microsoft.DirectX.Direct3D.Device device = null;
public PresentParameters presentparameter = new PresentParameters();
public bool device_exists;
public bool show;
public int HEIGHT;
public int WIDTH;
public string paintDesc;
private float angle ;
private CustomVertex.PositionColored[] vertices;
public double[,] heightData;
private int[] indices;
private IndexBuffer ib;
private VertexBuffer vb;
private Microsoft.DirectX.DirectInput.Device keyb;
//public
public viewport()
{
this.ClientSize = new System.Drawing.Size(600, 600);
this.Text = "Terrain viewport";
WIDTH = 2048 / 4;
HEIGHT = 2048 / 4;
heightData = new double[HEIGHT,WIDTH];
keyb = new Microsoft.DirectX.DirectInput.Device(SystemGuid.Keyboard);
keyb.SetCooperativeLevel(this, CooperativeLevelFlags.Background | CooperativeLevelFlags.NonExclusive);
keyb.Acquire();
presentparameter.Windowed = true;
presentparameter.SwapEffect = SwapEffect.Discard;
presentparameter.AutoDepthStencilFormat = DepthFormat.D16;
presentparameter.EnableAutoDepthStencil = true;
this.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.Opaque, true);
try {
device = new Microsoft.DirectX.Direct3D.Device(0, Microsoft.DirectX.Direct3D.DeviceType.Hardware, this, CreateFlags.SoftwareVertexProcessing, presentparameter);
device.DeviceLost += new EventHandler(this.InvalidateDeviceObjects);
device.DeviceReset += new EventHandler(this.RestoreDeviceObjects);
device.Disposing += new EventHandler(this.DeleteDeviceObjects);
device.DeviceResizing += new CancelEventHandler(this.EnvironmentResizing);
device_exists = true;
} catch (Exception DirectException) {
device_exists = false;
}
}
private void setcamera()
{
device.Transform.Projection = Matrix.PerspectiveFovLH((float)Math.PI / 4, this.Width / this.Height, 1f, 50f);
device.Transform.View = Matrix.LookAtLH (new Vector3(0, 0, 100), new Vector3(0, 0, 0) , new Vector3(0,0,1) );
device.RenderState.Lighting = false;
device.RenderState.FillMode = FillMode.WireFrame;
device.RenderState.CullMode = Cull.None;
}
public void declareVertex()
{
vb = new VertexBuffer(typeof(CustomVertex.PositionColored), HEIGHT*WIDTH, device, Usage.Dynamic | Usage.WriteOnly, CustomVertex.PositionColored.Format, Pool.Default);
vertices = new CustomVertex.PositionColored[HEIGHT*WIDTH];
for (int x=0;x< WIDTH;x++) {
for (int y=0; y< HEIGHT;y++) {
vertices[x + y * WIDTH].Position = new Vector3(x, y, (float)heightData[x,y]);
int r = Convert.ToInt32(205 * heightData[x,y] / 200 );
if(r>254)
r = 254;
vertices[x + y * WIDTH].Color = Color.FromArgb( r , 120 , 120).ToArgb();
}
}
vb.SetData(vertices, 0, LockFlags.None);
}
public void declareIndex()
{
ib = new IndexBuffer(typeof(int), (WIDTH-1)*(HEIGHT-1)*6, device, Usage.WriteOnly, Pool.Default);
indices = new int[(WIDTH-1)*(HEIGHT-1)*6];
for (int x=0;x< WIDTH-1;x++) {
for (int y=0; y< HEIGHT-1;y++) {
indices[(x+y*(WIDTH-1))*6] = (x+1)+(y+1)*WIDTH;
indices[(x+y*(WIDTH-1))*6+1] = (x+1)+y*WIDTH;
indices[(x+y*(WIDTH-1))*6+2] = x+y*WIDTH;
indices[(x+y*(WIDTH-1))*6+3] = (x+1)+(y+1)*WIDTH;
indices[(x+y*(WIDTH-1))*6+4] = x+y*WIDTH;
indices[(x+y*(WIDTH-1))*6+5] = x+(y+1)*WIDTH;
}
}
ib.SetData(indices, 0, LockFlags.None);
}
protected override void Dispose (bool disposing)
{
base.Dispose(disposing);
MessageBox.Show("");
}
protected virtual void InvalidateDeviceObjects(object sender, EventArgs e)
{
}
protected virtual void RestoreDeviceObjects(object sender, EventArgs e)
{
}
protected virtual void DeleteDeviceObjects(object sender, EventArgs e)
{
}
protected virtual void EnvironmentResizing(object sender, CancelEventArgs e)
{
}
public void run()
{
while(this.Created)
{
render();
setcamera();
// optional: loading the height using functional call:
// loadheight();
Application.DoEvents();
}
}
public void render()
{
if (device != null)
{
device.Clear(ClearFlags.Target, Color.Black, 1.0f, 0);
device.BeginScene();
//display terrain
device.VertexFormat = CustomVertex.PositionColored.Format;
device.SetStreamSource(0, vb, 0);
device.Indices = ib;
device.Transform.World = Matrix.Translation(-HEIGHT/2, -WIDTH/2, 0)*Matrix.RotationZ(angle) ;
device.DrawIndexedPrimitives(PrimitiveType.TriangleFan, 0, 0, WIDTH*HEIGHT, 0, indices.Length/3);
//turn off lights now
device.EndScene();
device.Present();
this.Invalidate();
readkeyboard();
}
}
void readkeyboard()
{
KeyboardState keys = keyb.GetCurrentKeyboardState();
if (keys[Key.Delete])
{
angle+=0.03f;
}
if (keys[Key.Next])
{
angle-=0.03f;
}
}
public void openport()
{
}
protected override void OnPaint(PaintEventArgs e)
{
render();
setcamera();
}
}
}
Now, yet a third file calls the world creation and display:
void MainFormLoad(object sender, EventArgs e)
{
world = new World();
world.setterrain();
}
the surf and box-somthing functions do not yet do anything.
All what i get now, is just a black window (the device.clear(... ) part) - i tried to adjust the camera .. no success
please help, i want to show the terrain in the window ....