Presentation is loading. Please wait.

Presentation is loading. Please wait.

Main Index Contents 11 Main Index Contents NCurses (curses.h) Background Curses “Hello World” Initializing & Shutting down Moving cursor I/O (printw, scanw.

Similar presentations


Presentation on theme: "Main Index Contents 11 Main Index Contents NCurses (curses.h) Background Curses “Hello World” Initializing & Shutting down Moving cursor I/O (printw, scanw."— Presentation transcript:

1 Main Index Contents 11 Main Index Contents NCurses (curses.h) Background Curses “Hello World” Initializing & Shutting down Moving cursor I/O (printw, scanw & getch) Color Using Special keys (F1, …) Using the Mouse Exampleshi.cppmvbox.cppmvboxM.cpptttCM.cpp CSE 331 - Lecture 9 Chapter 6 Shifting blocks of elements… Model of a list object… Sample list The list ADT CLASS list Constructors CLASS list Operations CLASS list::iterator Operations Inserting an element into a list Removing an element from a list Ordered lists Splicing two lists Summary Slides

2 Main Index Contents 2 Curses Library Allows “text-based” GUI Curses or Ncurses for Unix/Linux/AIX PDCurses (Public Domain Curses) for Dos/Windows Supports mouse, keypads, color, buffered & non-buffered input, and some simple graphics (lines, boxes, etc)

3 Main Index Contents 3 Curses (Windows, etc) Curses works by creating a window / screen / console data structure within which the program moves the cursor and performs output A refresh() function updates the actual window / screen / console to reflect the logical one See class web site for URLs of Curses resources / tutotrials / examples/ etc.

4 Main Index Contents 4 Curses Basics #include int main() { // always do this first initscr(); // initialize curses // these are optional cbreak(); // input keys immediately available noecho(); // stop echoing inputs nonl(); // faster cursor movement // move cursor to location and output message // upper left screen corner is 0,0 move(12,5); // move cursor to row 12, column 5 printw(“Hello World\n”); // instead of cout <<... refresh(); // make it visible to us getch(); // wait for a key to be hit endwin(); // release window back to shell return 0; }

5 Main Index Contents 5 Curses Initialization & Shutdown Must use – initscr(); // called first to initialize curses – endwin(); // called last to return screen to normal Probably use – cbreak(); // enable direct keystroke access – noecho(); // prevent echoing of input – nonl(); // speeds cursor movement – getmaxyx(stdscr,h,w); // get screen limits Notes: – stdscr is the default screen/window

6 Main Index Contents 6 Curses Moving cursor & I/O Cursor & position – move(y,x); // move cursor to line y, char posit x Upper left of screen is at position 0,0 – getyx(y,x); // returns current cursor location I/O – printw(“%d %s”, num, str); // cout << Parameters are same as printf() Prints in window from current cursor location – scanw(“%f”,&realNum); // cin >> Parameters are same as scanf() Reads input stream as directed by format string – getch(); // reads single keystroke – wgetch(stdscr); // reads single keystroke From indicated window

7 Main Index Contents 7 Curses Moving cursor & I/O Combined movement and I/O – mvprintw(y,x,“%d %s”, num, str); Prints in window from cursor location y, x – mvscanw(y,x,“%f”,&realNum); Reads input stream as directed by format string Making it visible – refresh(); // updates console Makes it match logical window data structure

8 Main Index Contents 8 Curses Color Only supported on certain terminal types – xterm is good bet – set term=xterm at unix prompt before running program – start_color(); // initializes color – init_pair(num,fg_color,bg_color); – Creates a COLOR_PAIR of foreground and background colors – xterm has 8 colors and 64 color pairs, max – attron(COLOR_PAIR(num)); // makes color pair the output attribute until turned off – attroff(COLOR_PAIR(num));

9 Main Index Contents 9 Curses COLORS COLOR_BLACK COLOR_RED COLOR_GREEN COLOR_YELLOW COLOR_BLUE COLOR_MAGENTA COLOR_CYAN COLOR_WHITE

10 Main Index Contents 10 Curses Using Special Keys To use function keys, arrows, etc. Initialize with – keypad(stdscr,TRUE); – Must be used before both special key input – And before mouse event capture – prevents immediate translation to ASCII Get key with – int key = getch(); Test key with keycodes – KEY_DOWN, KEY_UP, KEY_LEFT, KEY_RIGHT – KEY_HOME, KEY_BACKSPACE – KEY_F(n) Function keys, for 0 = 63 – KEY_DC Delete character – KEY_IC Insert char or enter insert mode – KEY_ENTER Enter or send

11 Main Index Contents 11 Curses Mouse Support Only in Ncurses (Linux & AIX) Initialize for capture of events with – mousemask(ALL_MOUSE_EVENTS,NULL); Specific masks (BUTTON1_CLICKED,...) Read mouse click with – int key = getch(); or – int key = wgetch(stdscr);

12 Main Index Contents 12 Curses Mouse Events Processing event – Value read will equal KEY_MOUSE – Use getmouse(&event) to recover event from event queue – Use event.bstate to determine button state (which event) – Use event.x and event.y to determine where mouse was clicked in window MEVENT event; // data type for mouse event if (key == KEY_MOUSE) // if it was the mouse if (getmouse(&event) == OK) { // get the event if (event.bstate & BUTTON1_CLICKED) { // so do something with // event.y; and event.x;

13 Main Index Contents 13 Example Curses Programs Source Code is on Class Web Site Hi – Simple curses “Hello World” program Mvbox – Moving star shape – Uses keyboard (letter) inputs mvboxM – Moving star shape – Uses keyboard, special keys, and mouse input tttCM – TicTacToe – Uses Color, mouse and keyboard inputs

14 Main Index Contents 14 Shifting blocks of elements to insert or delete a vector item

15 Main Index Contents 15 Main Index Contents Model of a list object with links to next and previous element

16 Main Index Contents 16 Main Index Contents The List ADT The list API documents the member function prototype as well as pre- and postconditions. – provides three constructors to declare a list object.

17 Main Index Contents 17 Main Index Contents CLASS list Constructors list(); Create an empty list. This is the default constructor. list(int n, const T&value = T()); Create a list with n elements, each having a specified value. If the value argument is omitted, the elements are filled with the default value for type T. Type T must have a default constructor, and the default value of type T is specified by the notation T(). list(T *first, T *last); Initialize the list, using the address range [first, last).

18 Main Index Contents 18 Main Index Contents CLASS list Operations T& back(); Return the value of the item at the rear of the list. Precondition: The vector must contain at least one element. bool empty() const; Return true if the vector is empty, false otherwise. T& front(); Return the value of the item at the front of the list. Precondition: The vector must contain at least one element.

19 Main Index Contents 19 Main Index Contents CLASS list Operations void push_back(const T& value); Add a value at the rear of the list. Postcondition: The list has a new element at the rear, and its size increases by 1. void pop_back(); Remove the item at the rear of the list. Precondition:The list is not empty. Postcondition:The list has a new element at the rear or is empty.

20 Main Index Contents 20 Main Index Contents CLASS list Operations void push_front(const T& value); Add a value at the front of the list. Postcondition:The list has a new element at the front, and its size increases by 1. void pop_front(); Remove the item at the front of the list. Precondition:The list is not empty. Postcondition:The list has a new element at the front or is empty. int size() const; Return the number of elements in the vector.

21 Main Index Contents 21 Main Index Contents CLASS list Operations iterator begin(); Returns an iterator that references the first position (front) of the list. If the list is empty, the iterator value end() is returned. const_iterator begin(); Returns a const_iterator that points to the first position (front) of a constant list. If the list is empty, the const_iterator value end() is returned. iterator end(); Returns an iterator that signifies a location immediately out of the range of actual elements. A program must not dereference the value of end() with the * operator.

22 Main Index Contents 22 Main Index Contents CLASS list Operations iterator end(); Returns an iterator that signifies a location immediately out of the range of actual elements. A program must not dereference the value of end() with the * operator. const_iterator end(); Returns a const_iterator that signifies a location immediately out of the range of actual elements in a constant list. A program must not dereference the value of end() with the * operator.

23 Main Index Contents 23 Main Index Contents CLASS list Operations void erase(iterator pos); Erase the element pointed to by pos. Precondition:The list is not empty. Postcondition:The list has one fewer element. void erase(iterator first, iterator last); Erase all list elements within the iterator range [first, last]. Precondition:The list is not empty. Postcondition:The size of the list decreases by the number of elements in the range.

24 Main Index Contents 24 Main Index Contents CLASS list Operations iterator insert(iterator pos, const T& value); Insert value before pos, and return an iterator pointing to the position of the new value in the list. The operation does not affect any existing iterators. Postcondition:The list has a new element.

25 Main Index Contents 25 Main Index Contents CLASS list::iterator Operations * :Accesses the value of the item currently pointed to by the iterator.*iter; ++ :Moves the iterator to the next item in the list.iter++; -- :Moves the iterator to the previous item in the list.iter--; == :Takes two iterators as operands and returns true when they both point at the same item in the list. iter1 == iter2 != :Returns true when the two iterators do not point at the same item in the list. iter1 != iter2

26 Main Index Contents 26 Palindromes Strings that read the same forwards and backwards Spaces and punctuation are ignored Approaches (using lists) 1 – Pop matching pairs of 1 st & last chars 2 – Scan inward to middle, matching corresponding outermost pairs

27 Main Index Contents 27 Palindrome (pop matches) // Assume spaces & punctuation removed // by caller; all letters in lower case template bool isPal_1(const list & alist) { list copyList; copyList = alist; while (copyList.size() > 0) { if (copyList.front() != copyList.back()) return false; // mismatch, not a palindrome // pop matching pair copyList.pop_front(); copyList.pop_back(); } return true; // all pairs matched & popped }

28 Main Index Contents 28 Palindrome (scan inward) // Assume spaces & punctuation removed // by caller; all letters in lower case template bool isPal_2(const list & alist) { list ::iterator left, right; left = alist.begin(); right = alist.end(); right--; while (left != right) { if (*left != *right) return false; // mismatch, not a palindrome right--; // move right iter 1 posit left if (left == right) return true; // even length string, we’re done left++; // move left 1 posit right } return true; // all pairs matched & popped }

29 Main Index Contents 29 SeqSearch // search values [*first,*last)- sequentially template List ::iterator seqSearch ( list ::iterator& first, list ::iterator& last, const T& target) { list ::iterator iter = first; while((iter != last) && (*iter != target)) iter++; return iter; }

30 Main Index Contents 30 Main Index Contents Inserting an element into a list

31 Main Index Contents 31 Removing an element from a list

32 Main Index Contents 32 Main Index Contents Splicing two lists

33 Main Index Contents 33 Ordered Lists Values maintained in order by key – Numerical – Alphabetical – Lexicographical Insertion is two step process – Search for first list value (V) equal to or greater than new value – Insertion of new value in front of list value (V) Examples – Inserting – Removing duplicates – Merging lists

34 Main Index Contents 34 Inserting in Ordered List template void insertOrder (list & orderedList, const T& item) { list ::iterator curr = orderedList.begin(), stop = orderedList.end(); // find insertion spot, 1 st value >= item while((curr != stop) && (*curr < item)) curr++; // insert item ahead of *curr orderedList.insert(curr, item); }

35 Main Index Contents 35 Removing Duplicates // assume list is ordered. This way we can jump curr // ahead as soon as we find *p != *curr template void removeDups (list & orderedList) { list ::iterator curr, p; curr = orderedList.begin(); while (curr != orderedList.end()) { p = curr; p++; while ((p != orderedList.end() && (*p == *curr)) // pass p, move p forward, and call erase orderedList.erase(p++); curr = p; }

36 Main Index Contents 36 Main Index Contents Summary Slide 1 §- list -A Sequence of elements stored by position. -Index access is not available… §-to access the value of an element, must pass through its preceding elements. §- list iterator -A generalized pointer that moves through a list element by element… forward or backward -At any point, the * operator accesses the value of a list item.

37 Main Index Contents 37 Main Index Contents Summary Slide 2 §- The list class has two iterator types: 1)iterator 1)iterator: A generalized list traversal pointer. 2)const_iterator 2)const _ iterator: :: must be used with a constant list object. Each type is a nested class of list and must be accessed by using the scope operator ::

38 Main Index Contents 38 Main Index Contents Summary Slide 3 §- the list member function begin() -Gives an iterator an initial value that points to the first element. §- the list member function end() -Returns an iterator pointing just past the last element of the list.

39 Main Index Contents 39 Main Index Contents Summary Slide 4 §- The sequential search of a list object firstlast -implemented by using an iterator range [first, last). last -It returns an iterator that points at the target value or has value last if the target is not in the list.

40 Main Index Contents 40 Main Index Contents Summary Slide 5 §- list class member f ns insert() and erase() -Both use an iterator argument to modify a list. 1)insert(pos) pos 1)insert(pos): places value in the list before the data referenced by the iterator pos. 2)erase(pos) pos 2)erase(pos): removes the data item referenced by pos from the list.


Download ppt "Main Index Contents 11 Main Index Contents NCurses (curses.h) Background Curses “Hello World” Initializing & Shutting down Moving cursor I/O (printw, scanw."

Similar presentations


Ads by Google