Switching sprites of a object in different rooms - game-maker

I am creating a character selection which changes the sprites of the main character.
To do this I have an arrow object which the user clicks to change the sprite of the main character.
global.Mario = true;
global.PrincessPeach = false;
global.Luigi = false;
global.Bowser = false;
if (mouse_check_button_pressed(mb_left)) {
if (global.Mario = true) {
Mario = false;
PrincessPeach= true;
}
if (global.PrincessPeach= true) {
PrincessPeach = true;
Mario = false;
}
if (global.Luigi = true) {
Luigi = false;
Bowser = true;
}
if (global.Bowser = true) {
Bowser = false;
Mario = true;
}
}
Then, on my main character I have a created an event executing code similar to the following:
if (global.Mario = true) {
sprite_index = Mario_NotJumping;
}
if (global.Luigi = true) {
sprite_index = Luigispr;
}
However, when I run my game to test it out, I get the following error:
FATAL ERROR in
action number 1
of Create Event
for object Mario_selection:
Push :: Execution Error - Variable Get -5.Mario(100000, -1)
at gml_Object_Mario_selection_Create_0 (line 1) - if (global.Mario = true) {
The object Mario_selection has the exact create event and same code as the main character. To display changes to the user.
If anyone could help me out, I am fairly new to GameMaker so I have a feeling I'm just misunderstanding global variables.

It looks like the var global.Mario, has not been declared. In the arrow objects create event put,
global.Mario = true;
global.PrincessPeach = false;
global.Luigi = false;
global.Bowser = false;

If i were you, i would save the chosen "image" of the user in 1 simple variable.
Add a few constants;
PLAYER_MARIO = 0;
PLAYER_PEACH = 1;
PLAYER_LUIGI = 2;
PLAYER_BOWSER = 3;
Then you can use those constants and save them in a global variable;
global.player_image = PLAYER_LUIGI;
Then you can use those in your objects like so;
switch (global.player_image) {
case PLAYER_MARIO:
sprite_index = Mario_NotJumping;
break;
case PLAYER_PEACH:
sprite_index = Peach_NotJumping;
break;
case PLAYER_LUIGI:
sprite_index = Luigi_NotJumping;
break;
case PLAYER_BOWSER:
sprite_index = Bowser_NotJumping;
break;
}
The specific error you were getting was because the global variable was not defined at the time of use.
A better method by the way, would be something like this - saving all sprite handles into specific variables, then using those.
Define some constants for readability;
P_LEFT = 0;
P_RIGHT = 1;
P_JUMP = 2;
Then whenever a player switches its character;
//When the user switches to peach;
global.player_sprite[P_LEFT] = spr_Peach_Left;
global.player_sprite[P_RIGHT] = spr_Peach_Right;
global.player_sprite[P_JUMPING] = spr_Peach_Jumping;
And overwrite;
//When the user switches to Luigi;
global.player_sprite[P_LEFT] = spr_Luigi_Left;
global.player_sprite[P_RIGHT] = spr_Luigi_Right;
global.player_sprite[P_JUMPING] = spr_Luigi_Jumping;
Then you can code all code like this;
if (jumping) {
sprite_index = global.player_sprite[P_JUMPING];
} else {
sprite_index = global.player_sprite[P_LEFT];
}
Do you understand what i mean? This way you won't need the switch statements everywhere, and just store the chosen sprites in 1 single array at the beginning of the game.
You can then code the game without having to check what player image the player chose.
Also, always define global variables at the beginning of the game. Global variables will always exist in the game, in every room, at any given moment.

You should use var mario=true; instead.

Related

Xamarin.Forms How to display progress indicator while sound recording/playback takes place

I would like to display a progress indicator while recording sound in my app.
The amount of time allocated for the recording is predefined. I set that up in code, lets say 10 seconds maximum recording time, but the user can stop the recording in less time, and of course he progress indicator would stop and reset.
I have been trying to make it work right could you please offer some guidance.
Note: I am using the NateRickard AudioRecorder nuget package.
if (!recorder.IsRecording)
{
buttonRecord.IsEnabled = false;
buttonPlay.IsEnabled = false;
DependencyService.Get<IAudioService>().PrepareRecording();
// start recording
var recordTask = await recorder.StartRecording();
// set up progress bar
//progressBarRecordTime.Progress = 1.0;
//await progressBarRecordTime.ProgressTo(1.0, 10000, Easing.Linear);
buttonRecord.Text = "Stop Recording";
buttonRecord.IsEnabled = true;
// get the recorded file
var recordedAudioFile = await recordTask;
buttonRecord.Text = "Record";
buttonPlay.IsEnabled = true;
if (recordedAudioFile != null)
{
var recordingFileDestinationPath = Path.Combine(FileSystem.AppDataDirectory, AppConstants.CUSTOM_ALERT_FILENAME);
if (File.Exists(recordingFileDestinationPath))
{
File.Delete(recordingFileDestinationPath);
}
File.Copy(recordedAudioFile, recordingFileDestinationPath);
}
}
Place an ActivityIndicator (name it ind) in your xaml code (view)
At the top of your code above:
ind.IsRunning = true;
//
if (!recorder.IsRecording)
//
when you are done, add this below your code
//
}
File.Copy(recordedAudioFile, recordingFileDestinationPath);
}
}
ind.IsRunning = false;

My first ExtendScript... and it doesn't work

I am developing a script for Adobe Bridge CS6. For the moment, all I want to do is to access the size (width and height) of a thumbnail that the user has selected and show it, either on a popup or on the console. Here is my script:
function TestBridge() {
this.requiredContext = "\tAdobe Bridge must be running.\n\tExecute against Bridge as the Target.\n";
}
TestBridge.prototype.run = function() {
if(!this.canRun())
{
return false;
}
var selectedThumbnails = app.document.getSelection();
if (selectedThumbnails.length > 0) {
$.writeln("MEEEEEPT");
var thumb = selectedThumbnails[0];
var x = thumb.core.preview.preview.width;
var y = thumb.core.preview.preview.height;
//alert('MEEEEEPT: x = ' + x + ', y = ' + y);
$.writeln("MEEEEEPT: x = " + x + ", y = " + y);
return true;
}
$.writeln("MOOO");
return false;
}
TestBridge.prototype.canRun = function()
{
// Must be running in Bridge & have a selection
if( (BridgeTalk.appName == "bridge") && (app.document.selectionLength == 1)) {
return true;
}
// Fail if these preconditions are not met.
// Bridge must be running,
// There must be a selection.
$.writeln("ERROR:: Cannot run.");
$.writeln(this.requiredContext);
return false;
}
The only problem is that... well, it doesnt work. I open it on ExtendScript Toolkit, set the target to Bridge CS6, hit "Run"... and all that happens is that the console says "Result: canRun()".
Looking at other code samples from Adobe, I see that the structure of their scripts is pretty much the same as mine, so I don't really know what I'm doing wrong.
Edit: what I needed was to add in the end a line to call the function, like so:
new.TestBridge.run();
Silly, silly mistake.

Music player in Actionscript 3.0

I already added a stop button with autoplay but I need to make it so when you click the button again after you had stopped it, the music starts playing.
Source code:
var music:Sound = new Sound(new URLRequest("calmingsong.mp3"));
var sc:SoundChannel = music.play();
button1.addEventListener(MouseEvent.CLICK, stopMusic);
function stopMusic(e:Event):void
{
sc.stop();
}
If you just want to play the sound over from the beginning, just call the Sound object's play() method again (you get a new SoundChannel object when you do this).
If you'd like to resume playing the sound at the point where the user stopped it, you'll need to add additional variables to store the current "playback state"... Something like this:
var music:Sound = new Sound(new URLRequest("calmingsong.mp3"));
var sc:SoundChannel = music.play();
var startPosition:Number = 0;
var isPlaying = true; // default to true cause you auto play...
button1.addEventListener(MouseEvent.CLICK, togglePlayback);
function togglePlayback(e:Event):void
{
if (isPlaying)
{
startPosition = sc.position;
sc.stop();
isPlaying = false;
}
else
{
sc = music.play(startPosition);
isPlaying = true;
}
}

Most efficient way to check to see if there is any data in a SQL row

The code below works, but I know it can't be the most efficient. Is there another way to ask if there are any rows rather than using Any()?
I'd like to have the NoResults Div hidden by default and only turned on when no rows are present, likewise have the repeater show up by default and only hidden when no results are listed.
using (AgileEntities context = new AgileEntities())
{
int StoryID = Convert.ToInt32(Request["StoryID"]);
var tasks = from t in context.Tasks
where t.StoryId == StoryID
orderby t.Number
select t;
rptTasks.DataSource = tasks;
rptTasks.DataBind();
if (tasks.Any())
{
rptTasks.Visible = true;
NoResults.Visible = false;
}
else
{
rptTasks.Visible = false;
NoResults.Visible = true;
}
}
Caution - calling .Any() may re-execute your query
I would do this a bit 'safer' to ensure single execution.
//force execution once
var taskList = tasks.ToList();
rptTasks.Visible = taskList.Count>0;
NoResults.Visible = taskList.Count==0;
And
rptTasks.DataSource = tasksList;
rptTasks.DataBind();
The problem with Any() and Count() is they cause your code to execute over and over - a test case
static void Main(string[] args)
{
//Populate the test class
List list = new List(1000);
for (int i=0; i o.CreateDate.AddSeconds(5) > DateTime.Now);
while (newList.Any())
{
//Note - are actual count keeps decreasing.. showing our 'execute' is running every time we call count.
Console.WriteLine(newList.Any());
System.Threading.Thread.Sleep(500);
}
}
You can replace Any() with Count() above to show. Basically the code keeps evaluating the query when you call Any() - I'm not sure if this applies to Linq to Sql though if there is any different caching mechanism.
var tasks = from t in context.Tasks
where t.StoryId == StoryID
orderby t.Number
select t;
var tasksList = tasks.ToList();
rptTasks.DataSource = tasksList;
rptTasks.DataBind();
if (tasksList.Count > 0)
{
rptTasks.Visible = true;
NoResults.Visible = false;
}
else
{
rptTasks.Visible = false;
NoResults.Visible = true;
}
The ToList() call will execute the query and create a list of tasks objects
Your DataBind() call has already caused the query to be executed, so calling Any() on top of that shouldn't cost you anything further.
You can change this with :
rptTasks.Visible = tasks.Any();
NoResults.Visible = !rptTasks.Visible;

ASP.NET Backgroundworkers for spreadsheet creation: multiple ones interfering with each other?

I am writing an ASP.NET application in which i need to create multiple excel reports. the report creation is pretty time-consuming (up to ten seconds for each) so i am using backgroundworkers to create them simultaneously.
My code looks a bit like this:
if (condition1)
{
excel_file_name = "TRANSFER";
BackgroundWorker worker_t = new BackgroundWorker();
worker_t.DoWork += new DoWorkEventHandler(DoWork);
worker_t.WorkerReportsProgress = false;
worker_t.WorkerSupportsCancellation = true;
worker_t.RunWorkerCompleted +=
new RunWorkerCompletedEventHandler(WorkerCompleted);
worker_t.RunWorkerAsync(excel_file_name);
}
if (Condition2)
{
excel_file_name = "NEFT";
BackgroundWorker worker_n = new BackgroundWorker();
worker_n.DoWork += new DoWorkEventHandler(DoWork);
worker_n.WorkerReportsProgress = false;
worker_n.WorkerSupportsCancellation = true;
worker_n.RunWorkerCompleted +=
new RunWorkerCompletedEventHandler(WorkerCompleted);
worker_n.RunWorkerAsync(excel_file_name);
}
there are more conditions but i haven't written them, since they are all similar. the only difference is the Excel_File_Name
the DoWork even then calls a class to create the excel files with the given name.
When condition1 and condition2 are both true, Here is the issue:
1. if i run this slowly using breakpoints during debugging, both files (TRANSFER and NEFT) are created.
2. if, however, i run it without breakpoints like a normal application, only the last file (NEFT in this example) is created.
What can be the issue?
Thanks
PS: For further information, here is the important code from the class that creates the excel file:
private static string placeDataInTemplate(string destFilePath, DataRow dr, bool isCoverLetter)
{
int loop = 0;
ExcelNamespace.Application excelApplication = new ExcelNamespace.Application();
ExcelNamespace.Workbook workbook = excelApplication.Workbooks.Open(destFilePath, 0, false, 5,
"", "", true, ExcelNamespace.XlPlatform.xlWindows, "\t", false, false, 0, true, true, false);
ExcelNamespace.Worksheet workSheet = (ExcelNamespace.Worksheet)workbook.Sheets[sheet_no];
try
{
string value;
string replicate;
string replicate_end;
// get data for Place Holders
sDataTable dtPlaceHolderData = getPlaceHolderData(dr);
//make Display Alerts False
excelApplication.DisplayAlerts = false;
if (dtPlaceHolderData != null && dtPlaceHolderData.Rows.Count > 0)
{
int rowCntDt = 0; //Which row will be used for data?
int i = 1;
Excel.Range Find = (ExcelNamespace.Range)workSheet.Cells.Find("#",
(ExcelNamespace.Range)workSheet.Cells[1, 1],
Excel.XlFindLookIn.xlValues,
Excel.XlLookAt.xlPart,
Excel.XlSearchOrder.xlByRows,
Excel.XlSearchDirection.xlNext,
false,
false,
Missing.Value);
while (Find != null && loop <= 200)
{
loop++;
value = Find.Value2.ToString();
if (condition)
//VERY long if...else if
}
string approveDirPath = destFilePath.Replace(Path.GetFileName(destFilePath), string.Empty);
workbook.Close(true, destFilePath, Type.Missing);
excelApplication.Quit();
string filepath = destFilePath.Split('-')[0];
string approval_id = dr[0].ToString();
return destFilePath;
}
return string.Empty;
}
catch (Exception ex)
{
//do something
}
finally
{
//release resources
}
NOTE: I have removed a lot of needless code. I can paste it if needed. Thank you
Most likely cause is some shared state between two threads - shared state may include excel application and workbooks. So you need to inspect your code for the same.
On the side note, instead of using Excel Automation to generate excel files, you may consider using some in-process library which would be perhaps more scalable and void of such issues. Have a look at one such free basic library at code project

Resources