Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I been working on a .vbs for a modified version of the Paper, Rock, and Scissors game but have had nothing but error after error. Please be gentle on the the amount of but hurt as i am still very new to the language of .vbs here is what i have so far.
Right now as it stands the code looks as follows:
`'***********************************************************************
'Script Name: RockPaperScissorsLizardSpock.vbs
'Author: Chuck.Norris
'Created: 03/03/15
'Description: This script prompts the user to Play a game.
'***********************************************************************
'Formally declare variables used by the script before trying to use them
Option Explicit
Dim objWshShell, strAnswer, strCardImage, strResults, GetRandomNumber, intGetRandomNumber, strCounter
strCounter = 1
Do while (strCounter <= 5)
strCounter = strCounter + 1
'Create an instance of the WScript object in order to later use the popup method
Set objWshShell = Wscript.CreateObject("Wscript.Shell")
strResults = "None"
'Display the rules of the game
strAnswer = InputBox("Please type Rock, Paper, Scissors, Lizard, Spock." & _
vbCrLf & vbCrLf & "Rules:" & vbCrLf & vbCrLf & _
"1. Guess the same thing as the computer to tie." & vbCrLf & _
"2. Paper covers rock and wins." & vbCrLf & _
"3. Rock crushes lizard and wins." & vbCrLf & _
"4. Lizard poisons Spock and wins." & vbCrLf & _
"5. Spock smashes Scissors and wins." & vbCrLf & _
"6. Scissors decapitates Lizard and wins." & vbCrLf & _
"7. Lizard eats paper and wins." & vbCrLf & _
"8. Paper disproves Spock and wins." & vbCrLf & _
"9. Spock vaporizes Rock and wins." & vbCrLf & _
"10. And as it always has...Rock crushes scissors and wins." & vbCrLf, "Let's Play a Game!")
'Time for the computer to randomly pick a choice
Randomize
GetRandomNumber = Round(FormatNumber(Int((5 * Rnd) + 1)))
intGetRandomNumber = GetRandomNumber
If GetRandomNumber = 5 Then strCardImage = "Lizard"
If GetRandomNumber = 4 Then strCardImage = "Spock"
If GetRandomNumber = 3 Then strCardImage = "Rock"
If GetRandomNumber = 2 Then strCardImage = "Scissors"
If GetRandomNumber = 1 Then strCardImage = "Paper"
'When you select rock
If strAnswer = "rock" Then
If intGetRandomNumber = 5 Then strResults = "You Win"
If intGetRandomNumber = 4 Then strResults = "You Lose"
If intGetRandomNumber = 3 Then strResults = "Tie"
If intGetRandomNumber = 2 Then strResults = "You Win"
If intGetRandomNumber = 1 Then strResults = "You Lose"
End If
'When you select scissors
If strAnswer = "scissors" Then
If intGetRandomNumber = 5 Then strResults = "You Win"
If intGetRandomNumber = 4 Then strResults = "You win"
If intGetRandomNumber = 3 Then strResults = "You Lose"
If intGetRandomNumber = 2 Then strResults = "Tie"
If intGetRandomNumber = 1 Then strResults = "You Lose"
End If
'When you select paper
If strAnswer = "paper" Then
If intGetRandomNumber = 5 Then strResults = "You Lose"
If intGetRandomNumber = 4 Then strResults = "You Lose"
If intGetRandomNumber = 3 Then strResults = "You Win"
If intGetRandomNumber = 2 Then strResults = "You Win"
If intGetRandomNumber = 1 Then strResults = "Tie"
End If
'When you select spock
If strAnswer = "spock" Then
If intGetRandomNumber = 5 Then strResults = "You Lose"
If intGetRandomNumber = 4 Then strResults = "Tie"
If intGetRandomNumber = 3 Then strResults = "You Win"
If intGetRandomNumber = 2 Then strResults = "You Win"
If intGetRandomNumber = 1 Then strResults = "You Lose"
End If
'When you select lizard
If strAnswer = "lizard" Then
If intGetRandomNumber = 5 Then strResults = "Tie"
If intGetRandomNumber = 4 Then strResults = "You Lose"
If intGetRandomNumber = 3 Then strResults = "You Lose"
If intGetRandomNumber = 2 Then strResults = "You Win"
If intGetRandomNumber = 1 Then strResults = "You Win"
End If
If strResults = "None" Then
objWshShell.Popup "Sorry. Your answer was not recognized. " & _
"Please type rock, paper, scissors, lizard, or spock in lower case letters."
WScript.Quit
End if
'Display the game's results so that the user can see if he or she won.
objWshShell.Popup "You picked: " & Space(12) & strAnswer & vbCrLf & _
vbCrLf & "Computer picked: " & space(12) & strCardImage & vbCrLf & _
vbCrLf & "=================" & vbCrLf & vbCrLf & "Results: " & _
strResults
Loop`
Script is working and i have learned in the process keep moving forward.
(1) Adding a double quote to
vbCrLf & =================" & vbCrLf & vbCrLf & "Results: " & _
to get
vbCrLf & "=================" & vbCrLf & vbCrLf & "Results: " & _
makes your script syntactically correct.
(2) Putting an Option Explicit at the top will force you to Dim the variables GetRandomNumber and intGetRandomNumber, and point out the (repeated) typo strRults for strResults.
(3) Your
intGetRandomNumber = GetRandomNumber = Round(FormatNumber(Int((5 * Rnd) + 1)))
does not assign the random number to GetRandomNumber and intGetRandomNumber but compares (empty) GetRandomNumber to that number and assigns the boolean result (False) to intGetRandomNumber. For just now use
GetRandomNumber = Round(FormatNumber(Int((5 * Rnd) + 1)))
intGetRandomNumber = GetRandomNumber
Evidence:
>> Dim a, b
>> b = a = 1
>> WScript.Echo TypeName(a)
>> WScript.Echo TypeName(b), CStr(b)
>>
Empty
Boolean False
That should give you a 'working' script.
P.S. What can be done to/with VBScript is determined by the Current Set of Knowledge and Skills (CSKS) of the programmer, not by the editor.
Update wrt comment/last edit:
Your last edit still contains
intGetRandomNumber = GetRandomNumber = Round(FormatNumber(Int((5 * Rnd) + 1)))
I told you why this can't possibly work and that you need to replace this by
GetRandomNumber = Round(FormatNumber(Int((5 * Rnd) + 1)))
intGetRandomNumber = GetRandomNumber
Related
In a text based game that I'm making with Ruby, I wanted to have multiple colors on a single line of text. The paint gem would only seem to work with two colors but I wanted more, so I looked up those terminal codes to manipulate the cursor position so I could move up a line and print a string in a new color.
Is there a more efficient way to do this? Here is the code for the buy function from the shop:
clr
draw_stats_main
shopbag = Game_DB.weapons_array
bagkeys = shopbag.keys
bagkeys.delete_if {|i| i == 0}
shopbag.each { |id, value|
if id != 0
if id >= 10
string1 = " (" + id.to_s + ")" + " " + value[0]
str1 = string1.size
else
string1 = " (" + id.to_s + ")" + " " + value[0]
str1 = string1.size
end
string2 = "ATTACK: #{value[1]}"; str2 = string2.size
string3 = "SPEED: #{value[2]}"; str3 = string3.size
string4 = "" if !value[3]
string4 = "TWO HANDED WEAPON" if value[3]
str3 = string3.size
pa "#{string1}"
pa "\033[1A \033[#{str1}C #{string2}", :red, :bright
pa "\033[1A \033[#{str1+str2+4}C #{string3}", :yellow, :bright if value[1] < 10
pa "\033[1A \033[#{str1+str2+str3+9}C #{string4}", :red if value[1] < 10
pa "\033[1A \033[#{str1+str2+3}C #{string3}", :yellow, :bright if value[1] > 10 && value[1] < 100
pa "\033[1A \033[#{str1+str2+str3+8}C #{string4}", :red if value[1] > 10 && value[1] < 100
pa "\033[1A \033[#{str1+str2+2}C #{string3}", :yellow, :bright if value[1] >= 100
pa "\033[1A \033[#{str1+str2+str3+7}C #{string4}", :red if value[1] >= 100
pa " >> Cost: #{value[4]}", :yellow
end
}
pa "#{Game_DB.tx(:other, 0)}"
pa "#{Game_DB.tx(:common, 22)}", :green, :bright
loop do
key = gets.chomp.to_i
if bagkeys.include?(key)
if #player.gold >= shopbag[key][4]
#player.remove_gold(shopbag[key][4])
#player.add_item(:weapon, key)
weap = shopbag[key][0]; weapstr = weap.delete " "
pa "#{Game_DB.tx(:other, 0)}"
pa " You purchased #{weapstr} for #{shopbag[key][4]} gold! Dont forget to equip it!", :green, :bright
key = gets
break
else
pa " You don't have enough gold!", :red
key = gets
break
end
elsif key == 0
#shopmenu[0] = false
break
end
end
Here is a screenshot of what the player sees with this block of code: Weapons Shop screenshot
I am writing a script where I have to create an Orange Tree and every time I run through the specified method the tree's height goes up, tree's age goes up, and number of oranges on the tree also increases. But after a certain time (it's up to me) the tree is supposed to die. So in my program I decided that if the tree is 15 feet or more it should be dead. Now every time I run through the method the height, age, and number of oranges go up and once the height goes past 15 feet I get a message saying "Tree is dead" but the height keeps increasing. I want it to stop once the tree is dead. Also how can I add something different every time the user runs the method to go into the next year? For example right now every year the height goes up by 3, number of oranges goes up by 4 and age goes up by 1 as it should. How do I make the height and number of oranges go up by a random number every year? (not too large) here is my code.
class OrangeTree
def initialize
#tree_height = 0
#no_oranges = 0
#tree_age = 0
end
def firstYear
if #tree_height >= 15 then
puts "Tree is dead"
end
#tree_height = #tree_height + 3
puts "Your orange tree is " + #tree_height.to_s + " feet tall!"
#tree_age = #tree_age + 1
puts "Your orange tree is " + #tree_age.to_s + " year old!"
#no_oranges = #no_oranges + 4
puts "Your orange tree has " + #no_oranges.to_s + " oranges!"
end
def pickOrange
if #no_oranges == 0 then
puts "You can't pick any oranges yet, you have to wait at least a year!" else
puts "How many oranges do you want to taste?" + " Remember you only have " + #no_oranges.to_s + " oranges on your tree!"
pick2 = gets.chomp.to_i
puts "The oranges taste delicious and very refreshing!"
#no_oranges = #no_oranges - pick2
end
end
def isDead
if #tree_height >= 15 then
return true else
return false
end
end
def countOranges
puts "Current number of oranges: " + #no_oranges.to_s
end
end
You have to modify your firstYear method in OrangeTree class to get the height and number of orange to be incremented as a parametre and return from the method when tree height reached a certain value.
class OrangeTree
def initialize
#tree_height = 0
#no_oranges = 0
#tree_age = 0
end
def firstYear(tree_height_increment, fruit_increment)
if #tree_height >= 15 then
puts "Tree is dead"
return
end
#tree_height = #tree_height + tree_height_increment
puts "Your orange tree is " + #tree_height.to_s + " feet tall!"
#tree_age = #tree_age + 1
puts "Your orange tree is " + #tree_age.to_s + " year old!"
#no_oranges = #no_oranges + fruit_increment
puts "Your orange tree has " + #no_oranges.to_s + " oranges!"
end
end
Now, Everytime you make a call to firstYear method, you can specify the value with which you want to increase tree's height and fruit's values.
How to add special character _ in the middle of string? For example:
Dim x
x = "Smith"
I need to get output as: S_m_i_t_h
Or:
Option Explicit
' string concatenation (bad idea in languages with non-mutable strings)
Function f1(s)
Dim l : l = Len(s)
If 2 > l Then
f1 = s
Else
Dim p
f1 = Left(s, 1)
For p = 2 To l
f1 = f1 & "_" & Mid(s, p, 1)
Next
End If
End Function
' Array via Mid(), Join
Function s2a(s)
Dim l : l = Len(s)
ReDim a(l - 1)
Dim p
For p = 1 To l
a(p - 1) = Mid(s, p, 1)
Next
s2a = a
End Function
Function f2(s)
f2 = Join(s2a(s), "_")
End Function
' RegExp.Replace, Mid(,2) to get rid of first _
Function f3(s)
Dim r : Set r = New RegExp
r.Global = True
r.Pattern = "(.)"
f3 = Mid(r.Replace(s, "_$1"), 2)
End Function
Function qq(s)
qq = """" & s & """"
End Function
Dim s, t
For Each s In Split(" a ab abc abcd Smith")
WScript.Echo "-----", qq(s)
t = f1(s)
WScript.Echo " ", qq(t)
t = f2(s)
WScript.Echo " ", qq(t)
t = f3(s)
WScript.Echo " ", qq(t)
Next
output:
cscript 39814484.vbs
----- ""
""
""
""
----- "a"
"a"
"a"
"a"
----- "ab"
"a_b"
"a_b"
"a_b"
----- "abc"
"a_b_c"
"a_b_c"
"a_b_c"
----- "abcd"
"a_b_c_d"
"a_b_c_d"
"a_b_c_d"
----- "Smith"
"S_m_i_t_h"
"S_m_i_t_h"
"S_m_i_t_h"
try it
strString = "Smith"
strleng=Len(strString)
result=""
if strleng<2 then
result=strString
else
For i=1 To strleng
result= result& Mid(strString,i,1)
if i<>strleng then
result= result& "_"
end if
Next
end if
I was trying to make a calculator in VBScript to test my skill, but came across an error. My program uses multiple else if statement to test what the user has input.
Here is my code below:
Dim head
Dim msg1, msgErr, msgAns
Dim input1, num1, num2
Dim ans
head = "Calculator"
msg1 = msgBox("Ruan's Vbscript calculator",0,head)
input1 = inputBox("How do you want to calculate? You can type (+ - * /)",head)
num1 = inputBox("Enter your first number",head)
num2 = inputBox("Enter your second number",head)
if (input1 = vbcancel) then
wscript.quit()
else if (input1 = "+") then
ans = num1 + num2
else if (input1 = "-") then
ans = num1 - num2
else if (input1 = "*") then
ans = num1 * num2
else if (input1 = "/") then
ans = num1 / num2
else
msgErr = msgBox("Make sure you type '+' or '-' or '*' or '/' with no extra letter or spaces","Error")
end if
msgAns = msgBox "Your answere is: " + head
When I run the program, the error says: "Expected end of statement". I don't see the problem here, as I have end if after all those else if statements.
Remove the space between else and if and make it elseif. Like this:
if (input1 = vbcancel) then
wscript.quit()
elseif (input1 = "+") then
ans = num1 + num2
elseif (input1 = "-") then
ans = num1 - num2
elseif (input1 = "*") then
ans = num1 * num2
elseif (input1 = "/") then
ans = num1 / num2
else
msgErr = msgBox("Make sure you type '+' or '-' or '*' or '/' with no extra letter or spaces","Error")
end if
With the additional space between else and if you start a new if statement nested in the else branch rather than continuing the first if statement. The nested if statements require end ifs of their own, which is why you're getting the error.
Minimal improvements to make it work:
Option Explicit
Dim head
Dim msg1, msgErr, msgAns
Dim input1, num1, num2
Dim ans
head = "Calculator"
msgBox "Ruan's Vbscript calculator", 0, head
input1 = inputBox("How do you want to calculate? You can type (+ - * /)",head)
If Not IsEmpty(input1) Then
num1 = CDbl(inputBox("Enter your first number",head))
num2 = CDbl(inputBox("Enter your second number",head))
if input1 = "+" then
ans = num1 + num2
elseif input1 = "-" then
ans = num1 - num2
elseif input1 = "*" then
ans = num1 * num2
elseif input1 = "/" then
ans = num1 / num2
elseif input1 = "\" then
ans = num1 \ num2
else
msgErr = msgBox("Make sure you type '+' or '-' or '*' or '/' with no extra letter or spaces","Error")
end if
msgBox "Your answere is: " & ans
else
msgBox "Aborted"
end if
Type and range checks for the operants left as execise.
A Select Case is usually a simpler/clearer construction for selecting operations based on a single variables value
Select Case input1
Case vbCancel
wscript.quit()
Case "+"
ans = num1 + num2
Case "-"
ans = num1 - num2
Case "*"
ans = num1 * num2
Case "/", "\" '//multiples
ans = num1 / num2
Case Else
msgBox "Make sure you type '+' or '-' or '*' or '/' with no extra letter or spaces", , "Error"
End Select
I'm playing around with the new yahoo API. I'd like to scrap some dummy data using the following address
http://query.yahooapis.com/v1/public/yql?q=desc%20social.updates.search&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=cbfunc
When I run this I get an authenticaion error (Need to be logged into Yahoo) This is fine obviously for me messing around on the internet. However I'd like to call this from a ruby script. Any ideas how I go about authenticating? I can only seem to find some web enabled version.
You might try the Mechanize gem for this. I've used it for other authenticated services
in the past.
I'd also recomment httparty -- It is ridiculously easy to map JSON services with this. Try this:
require 'rubygems'
require 'httparty'
class Yahoo
include HTTParty
# i don't think you need auth for this endpoint -- but if you do, uncomment below and fill it in
#basic_auth 'username', 'password'
format :json
def self.load
self.get 'http://query.yahooapis.com/v1/public/yql', :query => {:q => 'desc social.updates.search', :format => 'json', :diagnostics => true, :env => 'store://datatables.org/alltableswithkeys'}
end
end
puts Yahoo.load
You could try omniauth-yahoo for authorization, but it's seen didn't support get the new token after expired.
Public Function ScanColumns(SheetName As String, thisMany As Double, ShowWhat As String)
e = 0
For a = 1 To thisMany
aa = Application.WorksheetFunction.CountA(Sheets(SheetName).Cells(1, a).EntireColumn)
If aa > 0 Then
r = a
If e = 0 Then
e = a
End If
End If
Next a
If ShowWhat = "MIN" Then
ScanColumns = e
End If
If ShowWhat = "MAX" Then
ScanColumns = r
End If
End Function
Public Function ScanRows(SheetName As String, thisMany As Double, ShowWhat As String)
e = 0
For a = 1 To thisMany
aa = Application.WorksheetFunction.CountA(Sheets(SheetName).Cells(a, 1).EntireRow)
If aa > 0 Then
r = a
If e = 0 Then
e = a
End If
End If
Next a
If ShowWhat = "MIN" Then
ScanRows = e
End If
If ShowWhat = "MAX" Then
ScanRows = r
End If
End Function
Public Function FindInArea(SheetName As String, startRow As String, endRow As String, startCol As String, endCol As String, FindThis As String, ShowWhat As String)
CalendarMonthFormat1 = "Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec,"
CalendarMonthFormat2 = "January, Feburary,March,April,May,June,July,August,September,October,November,December,"
earliestDate = 999999999
latestDate = 0
If Left(FindThis, 7) = "[LENGTH" Then
LengthLook = Replace(FindThis, "[LENGTH", "")
LengthLook = Replace(LengthLook, "]", "")
End If
For a = startRow To endRow
For b = startCol To endCol
ThisCell = Sheets(SheetName).Cells(a, b)
thisCellAddr = Sheets(SheetName).Cells(a, b).Address
If ThisCell = FindThis Then
addrList = addrList & "[" & thisCellAddr & "]"
rc_list = rc_list & "[" & a & "," & b & "]"
c = c + 1
End If
If FindThis = "[MONTHS1]" Then
If ThisCell <> "" And InStr(LCase(CalendarMonthFormat1), LCase((ThisCell) & ",")) > 0 And Len(ThisCell) = 3 Then
addrList = addrList & "[" & thisCellAddr & "]"
rc_list = rc_list & "[" & a & "," & b & "]"
c = c + 1
End If
End If
If FindThis = "[MONTHS2]" Then
If ThisCell <> "" And InStr(LCase(CalendarMonthFormat2), LCase((ThisCell) & ",")) > 0 Then
addrList = addrList & "[" & thisCellAddr & "]"
rc_list = rc_list & "[" & a & "," & b & "]"
c = c + 1
End If
End If
If FindThis = "[DATEFORMAT]" Then
If InStr(ThisCell, "/") > 0 Then
slash_count = 0
For sc = 1 To Len(ThisCell)
If Mid(ThisCell, sc, 1) = "/" Then
slash_count = slash_count + 1
End If
Next sc
If slash_count = 2 Then
On Error Resume Next
D = Day(ThisCell)
M = Month(ThisCell)
Y = Year(ThisCell)
If D > 0 And M > 0 And Y > 0 Then
addrList = addrList & "[" & thisCellAddr & "]"
rc_list = rc_list & "[" & a & "," & b & "]"
c = c + 1
If earliestDate > DateValue(ThisCell) Then
earliestDate = DateValue(ThisCell)
If Len(D) = 1 Then
D = "0" & D
End If
If Len(M) = 1 Then
M = "0" & M
End If
eDateLocation = thisCellAddr
eDate_Format = D & "-" & M & "-" & Y
End If
If latestDate < DateValue(ThisCell) Then
latestDate = DateValue(ThisCell)
If Len(D) = 1 Then
D = "0" & D
End If
If Len(M) = 1 Then
M = "0" & M
End If
lDateLocation = thisCellAddr
lDate_Format = D & "-" & M & "-" & Y
End If
End If
End If
End If
End If
If Left(FindThis, 7) = "[LENGTH" Then
If Len(ThisCell) = Val(LengthLook) Then
addrList = addrList & "[" & thisCellAddr & "]"
rc_list = rc_list & "[" & a & "," & b & "]"
c = c + 1
End If
End If
If FindThis = "[DECIMAL]" Then
If InStr((ThisCell), ".") > 0 Then
addrList = addrList & "[" & thisCellAddr & "]"
rc_list = rc_list & "[" & a & "," & b & "]"
c = c + 1
End If
End If
If FindThis = "[PERC]" Then
If InStr((ThisCell), ".") > 0 And ThisCell <> "" And ThisCell <> 0 And Val(ThisCell) >= -1 And Val(ThisCell) <= 1 Then
addrList = addrList & "[" & thisCellAddr & "]"
rc_list = rc_list & "[" & a & "," & b & "]"
c = c + 1
End If
End If
Next b
Next a
If ShowWhat = "COUNT" Then
FindInArea = c
End If
If ShowWhat = "ADDR" Then
FindInArea = addrList
End If
If ShowWhat = "RC" Then
FindInArea = rc_list
End If
If ShowWhat = "EARLIESTDATE" Then
FindInArea = eDate_Format
End If
If ShowWhat = "EARLIESTDATEADDR" Then
FindInArea = eDateLocation
End If
If ShowWhat = "LATESTDATE" Then
FindInArea = lDate_Format
End If
If ShowWhat = "LATESTDATEADDR" Then
FindInArea = lDateLocation
End If
End Function