Optimal Method of Checking Keypresses on TI-89 - optimization

for an experiment I decided to program a little game into my TI-89 using the built in program editor, however I cannot figure out an optimal method of getting keystrokes without significant delay. Currently I have:
Prgm
70→xpos
70→ypos
Loop
If getKey()=340 Then
xpos+3→xpos
PxlCrcl ypos,xpos,5,1
EndIf
If getKey()=337 Then
xpos-3→xpos
PxlCrcl ypos,xpos,5,1
EndIf
If getKey()=257 Then
Goto end
EndIf
EndLoop
Lbl end
EndPrgm
This creates an endless game loop that checks if the left, right, or delete buttons are being pressed and draw a circle left or right accordingly or end the program entirely. However, this method seems to run extremely slowly and I have seen much smoother movement in other demonstrations. Is there something wrong with my method and if so how can I improve it?

Sorry, I use a TI-84, but this method should still work.
The getKey() function is the function that is creating a delay. You only have to run the getKey() function once if you put the output into a variable. In TI-84, you can just do
getKey->K
You should be able to do exactly the same thing with TI-89.
Hope this helps!

What I usually do is use a While not() statement then check the answer afterwards.
For example
loop
0 -> X
while not(X)
do something every iteration
getKey()
if Ans: Ans -> X
Check values of X with If statements
End loop
In this way you are just executing some code (Maybe some basic addition and subtraction or a For loop to slow things down) and a single If statement on each loop of the While statement instead of checking a lot of If statements on each loop.
This serves you well and allows you to do something on each iteration of the While loop while still checking for a keypress.
Note that I usually program on TI-84s, but the idea should work much the same in the TI-89 with a bit of tweaking.

Related

VBA ShapeRange.Rotation Property randomly stops working

I am trying to rotate a shape. Below is the relevant snippet.
Sheets("Sheet1").Shapes.Range(Array("Down Arrow 8")).Select
Selection.ShapeRange.Rotation = 90 + Sheets("Sheet2").Range("H8")
My problem is that the last line randomly works and randomly doesn't! I used to have it as a number (instead of a to string) but this refuses to work! It worked fine, then I made some changes to the macro and then it helpfully returned Error 438 - Object doesn't support this property or method. I fiddled around, debugged, etc (without ever changing the code) and it started working! Then I made some more changes and it stopped working and it seems to have stopped working for good. I literally copied this code from a recorded macro.
What I have tried:
Using CStr() to convert the value to a string
Declaring a variable and using the variable
What I really don't understand is why it would work without me changing the code and them stop working without me changing the code (i.e. the relevant lines)
A few things. First, avoid select. It isn't necessary and will save you a lot of headache and time in the future. Second, you can reference the shape by its name right from the Shapes object, assuming you are only intending to rotate one shape with the code. Finally, are you certain the value in Sheets("Sheet2").Range("H8") is numeric? If not, this could cause an error. The code below handles the first two issues. Beyond that, we'll need to see more code to determine the error.
Sheets("Sheet1").Shapes("Down Arrow 8").Rotation = 90 + Sheets("Sheet2").Range("H8")

VB Code explanation? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 years ago.
Improve this question
Hey can someone explain this VB (Visual basic) code in a way thats simple for everyone to understand even minimal to no coding experience but still explains each section, also what dim and open do. Thanks!
Dim studentname As String
Dim intMsg As String
Private Sub Command1_Click()
‘To read the file
Text1.Text = ""
Dim variable1 As String
On Error GoTo file_error
Open "D:\Liew Folder\sample.txt" For Input As #1
Do
Input #1, variable1
Text1.Text = Text1.Text & variable1 & vbCrLf
Loop While Not EOF(1) Close #1
Declare a student name variable that we will call studentname as a string. Think of variables as you would do x and y in an algebraic equation. They are simply names for things of a particular type. In a maths equation x and y are numbers. A string is a basically a sequence of characters, such as words, numbers, or any other arbitrary data. "Moo-Juice" is a string, for example - delimited by the " characters.
Declare a message called intMsg as a string.
Subroutine "Command1_Click", called when the button (presumably) Command1 is clicked by the user. Subroutines are functions and are where you either put common code that you wish to re-use, or in the case of languages such as this, to respond to events that have occurred. Events in GUI applications come in various different flavours, this one is called when the user clicks a button. Others include MouseMove, KeyUp, KeyDown. Responding to these events allows your code to do stuff.
Set the Text1 control's Text property to an empty string (clear it). Controls on a form (both the text box and the button are examples of controls), have properties. The Text property is where a Textbox control stores what you can see in the textbox. Controls generally have a whole bunch of properties. Left denotes where it is on the form with regards to the horizontal position. Font specifies want font to use, etc, etc. There are many different GUI systems, and beyond VB6 and in the .NET environment there are Windows Forms, and WPF (Windows Presentation Foundation). In other languages there are as many GUI systems as you can care to think of.
Declare variable1 as a string.
Within this subroutine (Command1_Click), should an error occur go to the file_error label that appears not to be in your code snippet so we can assume it is farther down, beyond the loop. GoTo does exactly what it says on the tin - it jumps to the label specified and execution continues there. On Error tells visual basic what to do if an error occurs, and in this case it is saying "Go there if something goes awry".
Open the file specified, in read mode, assigning it file handle #1 for future reference. File handlers, like variables, are a way of identifying a file we want to do something with. Without file handlers (in VB6) if I open multiple files at the same time, how does the system know which one I want to write to? By saying "Open this file, and I'll refer to it as #1", we can tell the system which file we want to play with at any particular point in time.
Begin a loop. There are many loop constructs, and the verbosity of VB6 (and BASIC in general) allows you to see what kind of loop you're doing. This is a Do loop. It will execute at least once, with the condition at the end being checked each iteration. Should that check return true, the loop stops. Other loop types include For (for fine-grained control over steps, and how many iteration. Other languages allow more expressive boolean logic to determine the exact lifetime of a for-loop), and While which is similar to do, but the check is performed at the top, so it may run zero times if the condition fails immediately.
Read in a line from file handle #1 in to our string variable variable1. Remember we've told it which file handle to use and so the system knows where to read the data from.
Append this to the text box we emptied earlier, with a carriage-return & line-feed. Given that we are reading line-by-line, we're preserving the line-endings when putting the text in to the text box. Appending means we're keeping what was there and adding to it.
Keep doing this until we've reached the end of the file. The EOF() function takes a file handle and says whether we've reach the *E*nd *O*f the *F*ile. Remember that the end of our loop terminates if the expression is true. Well, EOF() returns true if we've reached the end of the file. A good time to stop reading it, don't you think? :)
Close the file handle. Enough said! :)
To Summarise
This code snippet reads in a file line-by-line and puts the contents in a textbox, preserving the line-endings.
Issues
intMsg is never used.
Neither is studentname
As mentioned earlier, you're missing the file_error label and the end of the sub-routine (End Sub).

How to prompt messagebox once inside a for loop in vb.net?

Is it possible to display a single messagebox inside a for loop codes?
I am trying to but cannot successfully make it.
Please help.
Thanks in advance.
Code inside a loop, by definition, is meant to execute multiple times, for each iteration of it, so if you don't want to have multiple messages, move that call outside of the loop so it executes only once. This would be the main way of doing so, because it makes it clear that there will be ever only one of them.
Otherwise, you can condition its display, by some particular condition that's warranted to happen only once, possibly caching the result from the user. The second snippet from phadaphunk does something like that.
From you question, I get that you don't understand how it works below.
The loop is a set of instructions that must be executed "x" number of time. So everything that is in the body of that loop will be executed that number of time. Which means that if there are 5 iterations to the loop, you will get 5 messagebox.
This is how you do it if you want a different box for each iterations :
For Each x As Integer In someList
MessageBox.Show(x.ToString());
Otherwise you can't do it unless there is a certain condition that explains to the compiler at which iteration you want the message box to appear. Something like
For Each x As Integer In someList
If (x == 5)
MessageBox.Show(x.ToString());

Purpose of using sub routines over functions

I've been working with Access for a while now, and although I understand the obvious benefit of a Function over a Sub, been that it can return values as a result, I'm not sure as to why I should use a Sub over a Function. After all unless I'm mistaken; Functions can do everything Subs can do?
Note: I'm fully aware of how to use both Sub's and Function's so not looking for an explanation of how they work.
In terms of performance, this would not be any significant issue here.
The main difference is that user defined function can be used in expression in your code, where as a sub cannot.
This is really a HUGE Mount Everest of a difference here.
This difference is not really limited to Access, but tends to applies to every programing language and system I can think of that supports the creating of user defined functions.
The key advantage of using defined function are MANY but the most basic issue is that such function can be used in EXPRESSIONS.
For example, in an on click setting for a button on a form, you can generally have a single VBA [Event Code] routine attached to that button.
However you can ALSO place an expression in the property sheet like this:
=MyUserFunction()
The above is a handy tip, since then you can highlight 10 controls on a form, and type in the above expression and you just assigned the above function to those 10 buttons. You cannot do the above with a sub.
Another significant difference is you can use a function as a data source (expression) for a text box on a form or report (again you cannot do this with a sub).
Another significant difference is you can utilize these functions in SQL. This is a truly fantastic ability as then you can have code "run" for each row of a query. And this means you can extend the ability and functionally of SQL.
And you can even use this idea to display a VBA variable in a sql query as you simply build a public function that returns the VBA variable and this can be used in a query – you cannot however use VBA variables in a query!
And this extending of SQL opens up endless ideas:
So I can build a public function called ToMorrow()
Public Function Tomorrow() as date
Tomorrow() = date() + 1
End Function.
Now in the query builder, I can go:
Select FirstName, lastName, Tomorrow() as NextDay from tblCustomers
And you can even make custom conversions such as:
Select FirstName, LastName, Celsius([DailyGreenHouseTemp]) from tblGreenHouse.
The above Daily temperature reading could in in Fahrenheit and you simply have to define a public function called Celsius like this:
Public Function Celsius(Temperature As Variant) As Variant
Celsius = (Temperature * 1.8) + 32
End Function
Now while the above function is simple, it could do complex record set processing a complex algorithm to determine the moisture above a flower pot based on temperature and humidity.
So once we define such a public function, then the key concept is such a function can be used not only in VBA code as an expression, but ALSO can be used amazing enough this ability includes SQL.
So even in code, you can go:
If MyCustomfucntion(SomeVar) = lngTestValue then
Again in the above, you cannot use a sub in VBA expressions.
And even more interesting is when using custom XML for ribbons in Access, then if you use a function() expression for the "on action" attribute then you can avoid the need for ribbon call backs. Even better is the ribbon will call those functions() in the current form, not a public code module like you MUST do with ribbon call backs.
I could probably type on for another 10+ pages as to the difference, but I think that would start to be redundant and I don't want to appear condensing in any way here.
So the basic difference between a sub and function in VBA or in fact in most programming languages is quite much the same.
And the benefits of using a function in Access or just about any programing language are also much the same. For example I can define a user defined function in t-sql (scalar) – and again you then are free to use that t-sql function in any of your t-sql code or even quires that you create and use for sql server.
So this is basic and simple difference between a sub and a function, and I dare say those who have written computer code will in just about any programing language will instantly realize the above significant and useful differences between a subroutine and a function.
The main difference is not only the return value, it seems that subs are faster than functions
(at least in .net) because the MSIL code of subs is much shorter when no value is returned. so overall subs are faster when no value is returned.
oh i've just found a great source for it (talks about .net), maybe you would like to read further about it- Functions vs. Subroutines
Yes, a Function is just a Sub that returns a value.
I'm not absolutely sure, however, I think subs are faster than functions because the variables of a subroutine are defined upon creation of the subroutine and are accessed by referencing the memory location. Functions must allocate memory space every time they are accessed.
Subroutines modify the variables in the calling code and functions leave them intact. So a subroutine can provide several modified pieces of information to the calling code (as many changes as there are variables, including arrays) but a function can only provide one answer at a time for the values that are passed to it. Because of this difference, if it is important that a variable in a subroutine does not change its value, one must assign the value to a temporary variable defined within the subroutine itself.
FWIW (my theory ;) -
Lets think of the real world to understand this.
Lets say you want to get something done. There are (at least) 2 ways of doing this.
First way, send out requests for information to helpers and they will return with the information for you. so you remain in control ie all info is flowing back to you and you are deciding what to do next if any. this is more of the centrally controlled environment. this is the essence of 'function' in vba
Second way, divide up work into separate tasks and assign responsibility to your helpers to finish the task for you ie actual work is performed here by helpers in contrast to just gathering info. This is the essence of 'sub' in vba.
So think of what to do if code breaks. with function calls, you concentrate on the central command to look for reason of failure. With sub calls, you have to run into each sub's work and find out what they did wrong.
Of course, you can screw up the purpose and have functions do work and subs just get info but that would just be really confusing when things break! Oh but you cant do that, read this link - http://www.cpearson.com/excel/differen.htm, which states that Excel forbids functions changing cell values and subs being called from cells.
You will note that events are always subs, never functions. However, in MS Access, it can be useful to create functions when you wish to use them as the property of an event:
On Close: = MyCloseFunction()
Subs can return a value ByRef.
I found one other difference, at least on Excel but likely other Office apps. If you want to customize the ribbon by adding a button to launch a VB program, when you choose Macros in the "Choose commands from" dropdown menu, it lists any Subs in your code but not Functions. Note that a Private Sub will also be hidden from the customize ribbon selection, as will a Public Function.
So to summarize, these will be available to add as buttons on the ribbon:
Sub, Public Sub
And these will not be available to add:
Function, Public Function, Private Function, Private Sub

Text box not showing total

In my program I want to add some values together with a running total, and then show that total in a text box. When I try to run it, though, it just shows zero.
Here's the code I'm using
TotalPrice = TotalPrice + Price
Next
TxtLuggage.Text = TotalPrice
this chunk was a part of a For next loop.
How do I fix this.
Please do not take this as an offense, but I think you should read some book or at least a decent article on .NET debugging. This one looks like an easy to spot with just a bit of basic debugging.
See this one for example, and pay special attention on stepping through code, setting breakpoints and watches
What you should do:
set a breakpoint in the code in the problematic code line
when debugger breaks code execution there, see which object are you changing the property for. Does this property change the text box text value? Are you using a correct form instance?
does the For..Next loop set it to zero on its final pass?