Показать сообщение отдельно
Старый 21.09.2013, 10:50   #1
Beholder
AnyKey`щик
 
Регистрация: 09.07.2013
Сообщений: 2
Написано одно полезное сообщение
(для 5 участников)
Работа с текстом

Здесь я выложу две функции (одна моя, другая не совсем) которые тем или иным способом облегчают работу с текстом. Может кому-нибудь пригодится

Первая функция это RandomText$(txtInput$), где txtInput$ это строка текста разделенная символами |, например "AAA|BBB|CCC|DDD". Функция возвращает AAA, BBB, CCC или DDD с одинаковым шансом
Также можно использовать для рандома чисел, например в ситуациях где нужно рандомить только 0 или 2, поэтому функция Rand(0,2) не подходит тк. может выдать 1. Выглядит это вот так: Int(RandomText$("0|2"))

Dim array$(31)

Function randomText$(textInput$)
	Local numberOfPossibleStrings=1
	
	If Right(textInput$,1)="|" Then numberOfPossibleStrings=0
	Local i,x,c=1
	Local strForReturn$
	
	For x=1 To Len(textInput$)
		If Mid(textInput$,x,1)="|"
			numberOfPossibleStrings=numberOfPossibleStrings+1
		EndIf
	Next
	
	For x=1 To numberOfPossibleStrings
		Repeat
			i=i+1
			If Mid(textInput$,i,1)<>"|"
				array$(x)=array$(x)+Mid(textInput$,i,1)
			EndIf
		Until i>Len(textInput$) Or Mid(textInput$,i,1)="|"
	Next
	
	Return array$(Rand(1,numberOfPossibleStrings))
End Function
Вторая функция с другой стороны была скопирована с какого-то сайта с двумя пользователями в год, и называется она WrapText%(x, y, txt$, mode=0, align=0, width=-1, justified=0, height=-1). По сути это форматировка текста, с автоматическим переходом на следующую строку, возможностью отцентрировать текст слева, справа или посередине и так далее.
Внизу простая программа показывающая возможности этой функции, её копировать не надо

; Environment Settings
Graphics 800, 600, 0, 2
SetBuffer BackBuffer()
SeedRnd MilliSecs()
AppTitle "Wrap Text"

; Main loop
t = MilliSecs() + 1000
While Not KeyDown(1)
	
    ; Frame rate
    If MilliSecs() >= t Then
        lastFPS = FPS
        FPS = 0
        t = MilliSecs() + 1000
    End If
    FPS = FPS + 1
    
    ; Select mode
    If KeyHit(57) Then
        mode = (mode + 1) Mod 3
    End If
    If KeyHit(28) Then
        amode = (amode + 1) Mod 3
    End If
    If KeyHit(15) Then
        jmode = (jmode + 1) Mod 2
    End If
    
    ; Render
    Cls
    Text 0, 0, "Wrap mode: " + mode + " (press space to change)"
    Select mode
        Case 0
            Text 10, 15, "None"
        Case 1
            Text 10, 15, "Wrapped"
        Case 2
            Text 10, 15, "Direct"
    End Select
    Text 0, 30, "Align mode: " + amode + " (press enter to change)"
    Select amode
        Case 0
            Text 10, 45, "Left"
        Case 1
            Text 10, 45, "Center"
        Case 2
            Text 10, 45, "Right"
    End Select
    Text 0, 60, "Justified mode: " + jmode + " (press tab to change)"
    Select jmode
        Case 0
            Text 10, 75, "OFF"
        Case 1
            Text 10, 75, "ON"
    End Select
    Text 0, 90, "Text Height: " + h
    Text 0, 115, "FPS: " + lastFPS
    h = WrapText(100, 150, "Word wrap" + Chr$(13) + "From Wikipedia, the free encyclopedia" + Chr$(13) + "Word wrap refers to a feature supported by most text editors that allows them to insert soft returns (or hard returns for some text editors) at the right margins of a document. As the full view of the text would show excessively long text strings, word wrapping confines text to the viewable window, allowing text to be edited or read from top to bottom without any left to right scrolling." + Chr$(13) + "In word processors, word wrapping usually does not cause actual soft returns to be inserted into the actual document, but while editing the viewed text will be displayed as if soft returns had been inserted. If the user changes the margins, the editor will either automatically reposition the soft returns to ensure that all the text will 'flow' within the margins and remain visible, or provide the typist some convenient way to reposition the soft returns.", mode, amode, 400, jmode)
    Flip False
	
Wend

;---------------------САМА ФУНКЦИЯ-----------------------

Const WRAP_MODE_NONE = 0
Const WRAP_MODE_WRAPPED = 1
Const WRAP_MODE_DIRECT = 2
Const ALIGN_MODE_LEFT = 0
Const ALIGN_MODE_CENTER = 1
Const ALIGN_MODE_RIGHT = 2
Const JUSTIFIED_OFF = 0
Const JUSTIFIED_ON = 1
Function WrapText%(x, y, txt$, mode = WRAP_MODE_NONE, align = ALIGN_MODE_LEFT, width = -1, justified = JUSTIFIED_OFF, height = -1)
    Local i, l, o, h
    Local w#, wx#
    Local c$
    l = Len(txt)
    If width < 0 And mode > WRAP_MODE_NONE Then
        RuntimeError "Cannot have no width with a wrap mode"
    End If
    If width < 0 And justified > JUSTIFIED_OFF Then
        RuntimeError "Cannot have no width and be justified"
    End If
    If height = -1 Then
        height = StringHeight(txt)
    End If
    Select mode
        Case WRAP_MODE_NONE
            For i = 1 To l
                If Mid(txt, i, 1) = Chr$(13) Or Mid(txt, i, 1) = Chr$(10) Then
                    h = WrapText(x, y, Left(txt, i - 1), WRAP_MODE_DIRECT, align, width, JUSTIFIED_OFF, height)
                    Return h+WrapText(x, y+height, Mid(txt, i + 1), mode, align, width, justified, height)
                End If
            Next
            Return WrapText(x, y, txt, WRAP_MODE_DIRECT, align, width, JUSTIFIED_OFF, height)
        Case WRAP_MODE_WRAPPED
            For i = 1 To l
                If Mid(txt, i, 1) = Chr$(13) Or Mid(txt, i, 1) = Chr$(10) Then
                    h = WrapText(x, y, Left(txt, i - 1), WRAP_MODE_DIRECT, align, width, JUSTIFIED_OFF, height)
                    Return h+WrapText(x, y+height, Mid(txt, i + 1), mode, align, width, justified, height)                
                End If
                If StringWidth(Left(txt, i - 1)) > width Then
                    i = i - 1
                    While i > 0 And Mid(txt, i, 1) <> " "
                        i = i - 1
                    Wend
                    If i = 0 Then
                        i = 1
                    End If
                    h = WrapText(x, y, Left(txt, i - 1), WRAP_MODE_DIRECT, align, width, justified, height)
                    Return h+WrapText(x, y+height, Mid(txt, i + 1), mode, align, width, justified, height)    
                End If
            Next
            Return WrapText(x, y, txt, WRAP_MODE_DIRECT, align, width, JUSTIFIED_OFF, height)
        Case WRAP_MODE_DIRECT
            Select justified
                Case JUSTIFIED_OFF
                    Select align
                        Case ALIGN_MODE_LEFT
                            Text x, y, txt
                        Case ALIGN_MODE_CENTER
                            Text x + width/2 - StringWidth(txt)/2, y, txt
                        Case ALIGN_MODE_RIGHT
                            Text x + width - StringWidth(txt), y, txt
                    End Select        
				Case JUSTIFIED_ON
                    w = (Float(width) - Float(StringWidth(txt))) / Float(l-1)
                    wx = x
                    For i = 1 To l
                        c$ = Mid(txt, i, 1)
                        Text wx, y, c
                        wx = wx + w + StringWidth(c)
                    Next
            End Select
            Return height
    End Select
End Function
Всем удачи :^)
(Offline)
 
Ответить с цитированием
Эти 5 пользователя(ей) сказали Спасибо Beholder за это полезное сообщение:
ant0N (04.10.2013), Arton (21.09.2013), Кирпи4 (21.09.2013), Snogg (22.09.2013), Susanin (22.09.2013)