|
|
|
|
|
|
Author Rank:
|
|
Total page views :
5289
|
|
Total downloads :
49
|
|
|
|
|
Download
Files:
|
|
|
|
|
|
|
|
|
|
|
|
|
Similar ArticlesMost ReadTop RatedLatest
|
|
|
|
|
|
|
|
|
|
 Figure 1 - The Results of a Mad Libs Children's Tale.
Introduction.
When I was taking my much needed vacation with my girlfriend, I found a Brookstone game that brought back childhood camp memories of one my favorite belly-laughing pasttimes, MadLIBS. I still get a kick out of the game after all these years and decided to put together a version for the web. For those who are unfamiliar with the game, it goes something like this. You are prompted for a word by another person (or in this case a computer) in a grammar category. For example you may be asked for a noun or verb or name. You simply name anything in that particular category and it is recorded inside the story in a blanked out word space. You will continue to be prompted for a word fitting a particular grammar until all spots are filled. Then the resulting story is read. As you might imagine, the story takes on an almost mad construction as you have blindly seeded the story with substituted irrelevant words.
MadLibs.NET.
My version of mad libs utilizes a text file that is a template for the story. All information for the game is contained in this file. The file consists of two types of placeholders. One place holder is bracketed with < > . These brackets contain the grammar prompt for all the unfilled spots (e.g. <plural noun>). The other place holder is a set of square brackets [] containing a number (e.g. [0]) . This is a new feature I added to the game to allow the user to repeat a chosen bracketed <> word in another part of the story. The number in the square brackets refers to the order of the <> grammar word. Below is the MadLibs text file for the three little pigs:
Listing 1 - Mad Libs Template File.
Once upon a time there were three little <animal>s. They each lived in three houses. One made of <plural noun>, one made of <plural noun> and one made of <plural noun>. One day the <adjective> [0]s were sitting in their houses, when along came a big <adjective> <animal>. He huffed and he <verb - past tense> and he blew down the house made of [1]. The [0] was so <emotion> that he yelled <exclamation> and ran to the house made of [2]. The [6] <verb - past tense> to the house made of [2] and blew that house to <place>. Both [0]s <verb-past tense> and ran to the house made of [3]. The [6] followed the [0]s to the house made of [3]. He huffed and he puffed, but he could not seem to make the house <action verb>. So the [6] gave up and ran to <place>. The [0]s were very <adjective>.
The MadLib.NET game will continue to prompt the user with each grammar only in the <> brackets. When the programming engine reaches the end of the template, the story is displayed. Word needed for the [] square brackets are automatically substituted by the computer based on the sequence of the <> fields.
Design.
The design of the MadLibs game consists of a web page and a parser. The web page displays all the grammar prompts and the final story. The parser does all the parsing of the template file shown in Listing 1.

Figure 2 - MadLibs.NET Game Reverse Engineered with WithClass UML Tool.
Getting the template file.
Initially, the template file is read into the session and the first prompt is read in from the template and placed in the grammar prompt label. Also we keep a pointer in the session pointing to the last position of the <field> in the template that we read into the prompt.
Listing 2 - Initial reading of the template.
' open a new excel spreadsheet If Me.IsPostBack Then Else ' get the madlib template and store it in the session Dim libText As String = ReadMadLibFromFile("MadFile.txt") Session("Counter") = 0 ' get the first label and place it in the grammar prompt Dim parser As MadLibParser = New MadLibParser Dim nextIndex As Integer = 0 Dim grammar As String = parser.ParseNext(0, libText, nextIndex) Session("NextIndex") = nextIndex lblMadQuestion.Text = String.Format("{0}: Enter a {1}.", 1, grammar) End If
After each subsequent push of the button, we parse the next piece of grammar out of the template in the post back and assign the label text. If the end of the template is reached in the post back, we display the final story as shown in Listing 3.
Listing 3 - Reading in grammar after the post back.
If Me.IsPostBack Then Dim counter As Integer = CInt(Session("Counter")) ' get the current counter, that counts the template field counter += 1 ' get the next grammar field Dim parser As MadLibParser = New MadLibParser Dim index As Integer = CInt(Session("NextIndex")) Dim nextIndex As Integer = index Dim madText As String = CStr(Session("MadLibForm")) Dim grammar As String = parser.ParseNext(index, madText, nextIndex) If nextIndex = -1 Then ' we have reached the end of the template, display the story RecordNextWord() ' make sure we get the last entered word and put it into the session Dim story As String = parser.ConstructStory(madText, Session) txtStory.Text = story Button1.Enabled = False Else ' set the prompt for the next grammar field Session("NextIndex") = nextIndex lblMadQuestion.Text = String.Format("{0}: Enter a {1}.", counter + 1, grammar)End If Else ' see listing 2 End If
The button event handler saves the word that the player entered into the Session State. Here we increment a count on each grammar field, and use this to make a unique index into the session state table as shown in listing 4.
Listing 4 - Recording the player's entered word.
Private Sub RecordNextWord() Dim count As Integer = CInt(Session("Counter")) Session("Entry" & count.ToString()) = txtGrammarEntry.Text count += 1 Session("Counter") = count ' store it back in the session End Sub
Private Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) ' store the next entry into the session RecordNextWord() End Sub
After all words are entered, the story is constructed from the template. The program goes back through all the players words recorded in the session and places them consecutively inside the template in the appropriate places. All construction is performed in the ConstructStory method of the MadLibParser class. The ConstructStory method first goes through <> fields and replaces them one after another with the player's word entries. It then finds each square bracket field, looks at the number contained in them, and places the appropriate player entry corresponding to the sequence in which the player entered the word. For example, if the square brackets contain "[0]", the program will replace this field with the first entry the player entered in the game.
Listing 5 - Constructing the story from the player words and the madlib template.
Public Function ConstructStory(ByVal madlibFile As String, ByVal session As HttpSessionState) As String Dim story As String = "" Dim count As Integer = 0 Dim nextIndex As Integer = 0 Dim index As Integer = 0 ' loop through all player entries until there are no more entries Do While Not session("Entry" & count.ToString()) Is Nothing ' replace the template with the next player entry madlibFile = ReplaceNext(madlibFile, CStr(session("Entry" & count.ToString())), "<", ">") count += 1 Loop ' replace square brackets as well ' loop through all square brackets, and replace with the player word ' corresponding to the particular sequence number contained in the brackets Do While madlibFile.IndexOf("[") >= 0 ' parse out sequence number from square brackets Dim bracketNumber As String = GetNextNumber(madlibFile) replace template String bracket field with player entry corresponding to the sequence madlibFile = ReplaceNext(madlibFile, CStr(session("Entry" & bracketNumber)), "[", "]") Loop Return madlibFile End Function
Conclusion.
MadLIBS has given me hours of fun as a kid and still makes me chuckle when I read the wacky stories constructed from the game. It's my pleasure to pass on some of that wackiness to you as you stretch your creativity in this entertaining game of words now living on the Web courtesy of C# and .NET.
NOTE: THIS ARTICLE IS CONVERTED FROM C# TO VB.NET USING A CONVERSION TOOL. ORIGINAL ARTICLE CAN BE FOUND ON C# CORNER (WWW.C-SHARPCORNER.COM).
|
|
|
Login
to add your contents and source code to this article
|
|
|
|
|
|
|
|
Mike Gold
Michael Gold is President of Microgold Software Inc., makers of the WithClass UML Tool. His company is a Microsoft VBA Partner and Borland Partner. Mike is a Microsoft MVP and founding member of C# Corner. He has a BSEE and MEng EE from Cornell University and has consulted for Chase Manhattan Bank, JP Morgan, Merrill Lynch, and Charles Schwab. Currently he is a senior developer at Finisar Corp. He has been involved in several .NET book projects, and is currently working on a book for using .NET with embedded systems. He can be reached at mike@c-sharpcorner.com
|
|
|
|
|
|
|
|
|
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional
consulting company, our consultants are well-known experts in .NET and many of them
are MVPs, authors, and trainers. We specialize in Microsoft .NET development and
utilize Agile Development and Extreme Programming practices to provide fast pace
quick turnaround results. Our software development model is a mix of Agile Development,
traditional SDLC, and Waterfall models.
|
|
Click here to learn more about C# Consulting. |
|
|
|
|
|
|
|
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon.
Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees.
As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
|
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
|
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
|
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today. With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications. Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
|
60 FREE UI Controls from DevExpress
Register for your FREE copy on over 60 free presentation controls from
DevExpress - Absolutely Free-of-Charge without any royalties or distribution
costs. Visit Devexpress.com/60 today. Free controls include advanced lists box, dropdown calendar, rich text edit, spin
edit, tab control and so much more!
DevExpress engineers feature rich presentation controls and reporting tools for WinForms, ASP.NET, WPF, and Silverlight. Our technologies help you build your best, see complex software with greater clarity and deliver compelling business solutions for Windows and the web in the shortest possible time.
|
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or
application via a range of API's. Learn More about our API connections.
|
Microsoft Visual Studio 2010
Visualize your workspace with new multiple monitor support, powerful Web development, new SharePoint support with tons of templates and Web parts, and more accurate targeting of any version of the .NET Framework. Get set to unleash your creativity.
|
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
|
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
|
|
|
|
|
|
|
|
|
|
|
|
|