From 4342a5179e1c9be361bb4c98c92ae22974eea2bd Mon Sep 17 00:00:00 2001 From: Katie Dektar Date: Wed, 26 Aug 2020 08:57:24 -0700 Subject: [PATCH 01/40] Remove information from README that isn't helpful to students. Replaced with wiki. --- README.md | 80 +++---------------------------------------------------- 1 file changed, 3 insertions(+), 77 deletions(-) diff --git a/README.md b/README.md index ec927dc..faa754e 100644 --- a/README.md +++ b/README.md @@ -4,88 +4,14 @@ Libraries for student C++ code. ## Graphics -![C/C++ CI](https://github.com/ILXL/cpputils/workflows/C/C++%20CI/badge.svg) - graphics/image.h can be used to create, view, load and save images. Example: ![example fractal tree](graphics/test/example_fractal_tree.png) ### Usage -[image.h](graphics/image.h) provides a ``Color`` class and an ``Image`` class. Images can -be loaded from file or created. Users may access and set per-pixel color data. Image can be modified -by manipulating them at the pixel level, as well as by drawing lines, circles, rectangles and text. -Images can be displayed and saved as bitmaps (an uncompressed format). - -[image_event.h](graphics/image_event.h) provides a ``MouseEvent`` and a ``MouseEventListener`` interface. Extend the ``MouseEventListener`` interface and implement ``OnMouseEvent``. To begin receiving mouse events, use ``Image::AddMouseEventListener`` to register for mouse events, and enter the event loop with ``Image::ShowUntilClosed``. Note you will need to use ``Image::Flush`` (and ``cout::flush``) to ensure updates are noted after calling ``Image::ShowUntilClosed``. - -### Development - -image.cc is backed by [CImg](cimg.eu), an open-source C++ image processing library. To update CImg.h -to the latest, run ``make update_cimg`` in graphics/. - -It would be possible to back image.cc with some other implementation, for example Skia or OpenGL. -CImg was chosen because it is relatively light-weight, as all the implementation is contained within -the CImg.h header. - -## cpputils usage (for lab and project creators): - -To use this as a submodule in another lab or project, run: - -``` -git submodule add -b v1 https://github.com/ILXL/cpputils -``` - -This will create a .gitmodules file which you can add and commit, pointed at a particular -branch (in this case v1). - -Then make sure everyone who checks out the repo gets the submodule, for example adding this -command to your project Makefile to check if image.h is available: - -``` -cpputils/graphics/image.h: - @git submodule update --init --recursive -``` - -This checks out cpputils at a particular commit, and everyone cloning your git repository will -get that exact commit. This is useful for versioning: it ensures everyone using that git repository -will have the same version of cpputils until it is explicitly updated. - -So, if you want to update the commit which cpputils is pointed at in an existing repo, you can pull -from within the cpputils directory and then cd back out to add and commit the change. For example, -this snippet pulls the latest from the v1 branch: - -``` -cd cpputils -git checkout v1 && git pull -cd .. -git add cpputils/ && git commit -m "Updating cpputils" -``` - -## Release process (for cpputils library contributors): - -### Branches - -Users of cpputils will check out a particular branch as a submodule within their repository. We -have created branches for each version to make it easy for submodules to get a known stable -cpputils. -* Development of cpputils should be merged to the master branch. -* Significant changes, once ready for usage, should be forked to new version branches (v1, v2, etc). -* Changes should not be merged back to earlier version branches, except bugfixes. - -### Testing - -Utility classes in cpputils should be tested to ensure changes do not cause any surprising -breakages. You can set up github continuous integration testing using -[Github Actions](https://github.com/features/actions). - -You can add new tests by editing .github/workflows/c-cpp.yml. For example, the graphics class is -tested with graphcis/image_unittest.cc. c-cpp.yml has a workflow to ``make image_unittest`` -which ensures all dependencies are installed (like gtest) and then builds and runs -image_unittest.cc. +Learn more about how to C++ Utils graphics class on [ILXL-Guides](https://github.com/ILXL-guides/intro-to-graphics). -You can see the result of each test pass in the [actions](https://github.com/ILXL/cpputils/actions) -tab on GitHub. +## For developers and instructors -*Note: Github Actions is free for public repositories, but there are a limited number of minutes -for private repos! cpputils is public so it has unlimited actions minutes.* +Read more about developing and including C++ Utils in the [wiki](https://github.com/ILXL/cpputils/wiki). From 6525983dddf49150647aa1c599519c336408ecbb Mon Sep 17 00:00:00 2001 From: Katie Dektar Date: Wed, 9 Sep 2020 12:54:40 -0700 Subject: [PATCH 02/40] Make colors mutatable and add default constructor --- graphics/image.h | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/graphics/image.h b/graphics/image.h index 9b4b994..09fe00d 100644 --- a/graphics/image.h +++ b/graphics/image.h @@ -20,11 +20,11 @@ namespace graphics { /** * Represents an RGB pixel color, where |red|, |green| and |blue| - * may be between 0 and 255, inclusive. + * may be between 0 and 255, inclusive. Default color is black. */ class Color { public: - explicit Color(int red, int green, int blue); + explicit Color(int red = 0, int green = 0, int blue = 0); ~Color() = default; bool operator==(const Color& other) const { @@ -39,6 +39,10 @@ class Color { int Green() const { return green_; } int Blue() const { return blue_; } + void SetRed(int red) { red_ = red; } + void SetGreen(int green) { green_ = green; } + void SetBlue(int blue) { blue_ = blue; } + private: int red_; int green_; From 56e90f223f5724080a377e8ce89bc9325912d5a9 Mon Sep 17 00:00:00 2001 From: Katie Dektar Date: Tue, 15 Sep 2020 08:54:24 -0700 Subject: [PATCH 03/40] Animation support --- .github/workflows/c-cpp.yml | 2 +- graphics/image.cc | 41 +++++++++++++++++++++++++-------- graphics/image.h | 36 ++++++++++++++++++++++++++--- graphics/image_event.h | 16 +++++++++++++ graphics/test/image_unittest.cc | 8 +++---- 5 files changed, 86 insertions(+), 17 deletions(-) diff --git a/.github/workflows/c-cpp.yml b/.github/workflows/c-cpp.yml index b5bd8a3..cdfa76f 100644 --- a/.github/workflows/c-cpp.yml +++ b/.github/workflows/c-cpp.yml @@ -2,7 +2,7 @@ name: C/C++ CI on: push: - branches: [ master, v1 ] + branches: [ master, v1, v2, animation ] pull_request: branches: [ master ] diff --git a/graphics/image.cc b/graphics/image.cc index e58f7ac..d400d9b 100644 --- a/graphics/image.cc +++ b/graphics/image.cc @@ -97,14 +97,25 @@ bool Image::Show(const string& title) { return true; } -bool Image::ShowUntilClosed(const string& title) { +bool Image::ShowUntilClosed(const string& title, int animation_ms) { if (!Show(title)) { return false; } while (!display_->is_closed()) { ProcessEvent(); - display_->wait(); + if (timer_ > animation_ms) { + for (auto listener : animation_listeners_) { + listener->OnAnimationStep(); + } + // Reset the timer. + timer_ = timer_ % animation_ms; + } + // May need to tweak this for performance. + const int kEventCheckMs = 5; + display_->wait(kEventCheckMs); + timer_ += kEventCheckMs; } + timer_ = 0; return true; } @@ -221,7 +232,8 @@ void Image::ProcessEvent() { if (display_->button() & 1 && mouse_x >= 0 && mouse_y >= 0) { // Left button has been pressed or moved. MouseAction action; - if (latest_event_.GetMouseAction() == MouseAction::kReleased) { + if (latest_event_.GetMouseAction() == MouseAction::kReleased || + latest_event_.GetMouseAction() == MouseAction::kMoved) { action = MouseAction::kPressed; } else { if (mouse_x == latest_event_.GetX() && mouse_y == latest_event_.GetY()) { @@ -234,13 +246,24 @@ void Image::ProcessEvent() { for (auto listener : mouse_listeners_) { listener->OnMouseEvent(latest_event_); } - } else if (!(display_->button() & 1) && - latest_event_.GetMouseAction() != MouseAction::kReleased) { + } else if (!(display_->button() & 1)) { // Left button is not clicked. - latest_event_ = MouseEvent(latest_event_.GetX(), latest_event_.GetY(), - MouseAction::kReleased); - for (auto listener : mouse_listeners_) { - listener->OnMouseEvent(latest_event_); + if (latest_event_.GetMouseAction() == MouseAction::kDragged || + latest_event_.GetMouseAction() == MouseAction::kPressed) { + // We were dragging or pressing, send a release. + latest_event_ = MouseEvent(latest_event_.GetX(), latest_event_.GetY(), + MouseAction::kReleased); + for (auto listener : mouse_listeners_) { + listener->OnMouseEvent(latest_event_); + } + } else if (mouse_x != latest_event_.GetX() && + mouse_y != latest_event_.GetY() && + mouse_x >= 0 && mouse_y >= 0) { + // Mouse position has changed, send a move. + latest_event_ = MouseEvent(mouse_x, mouse_y, MouseAction::kMoved); + for (auto listener : mouse_listeners_) { + listener->OnMouseEvent(latest_event_); + } } } } diff --git a/graphics/image.h b/graphics/image.h index 09fe00d..bb70979 100644 --- a/graphics/image.h +++ b/graphics/image.h @@ -110,7 +110,11 @@ class Image { * Optional |title| for the window. Returns false if the image * could not be shown. */ - bool ShowUntilClosed(const std::string& title); + bool ShowUntilClosed(const std::string& title) { + return ShowUntilClosed(title, 30); + } + + bool ShowUntilClosed(const std::string& title, int animation_ms); /** * Refreshes the display with any update to the image. Does nothing if the @@ -252,7 +256,7 @@ class Image { int green, int blue); /** - * Adds a MouseEventListener to this image. This EventListener's OnMouseEvent + * Adds a MouseEventListener to this image. This MouseEventListener's OnMouseEvent * function will be called whenever the display receives left-button mouse * events. */ @@ -263,7 +267,7 @@ class Image { } /** - * Removes a MouseEventListener if it was added. This EventListener's + * Removes a MouseEventListener if it was added. This MouseEventListener's * OnMouseEvent function will no longer be called when the display receives * mouse events. */ @@ -273,6 +277,28 @@ class Image { } } + /** + * Adds a AnimationEventListener to this image. This AnimationEventListener's + * OnAnimationStep function will be called whenever the time has ellapsed + * for the next animation step. + */ + void AddAnimationEventListener(AnimationEventListener& listener) { + if (animation_listeners_.find(&listener) == animation_listeners_.end()) { + animation_listeners_.insert(&listener); + } + } + + /** + * Removes a AnimationEventListener if it was added. This + * AnimationEventListener's OnAnimationStep function will no longer be called + * every animation step. + */ + void RemoveAnimationEventListener(AnimationEventListener& listener) { + if (animation_listeners_.find(&listener) != animation_listeners_.end()) { + animation_listeners_.erase(&listener); + } + } + private: friend class TestEventGenerator; @@ -299,10 +325,14 @@ class Image { int height_ = 0; std::unique_ptr> cimage_; std::unique_ptr display_; + int timer_ = 0; // Mouse listeners. Unowned. std::set mouse_listeners_; + // Animation listeners. Unowned. + std::set animation_listeners_; + MouseEvent latest_event_ = MouseEvent(0, 0, MouseAction::kReleased); }; diff --git a/graphics/image_event.h b/graphics/image_event.h index f485b39..ad43629 100644 --- a/graphics/image_event.h +++ b/graphics/image_event.h @@ -7,9 +7,14 @@ namespace graphics { * Enum representing whether a button was pressed or released. */ enum class MouseAction { + // Left button down. kPressed = 0, + // Moved while left button was down. kDragged, + // Left button up. kReleased, + // Moved but the left button was not down. + kMoved, }; /** @@ -45,6 +50,17 @@ class MouseEventListener { virtual void OnMouseEvent(const MouseEvent& event) = 0; }; +/** + * Abstract interface for listening to AnimationEvents on images. Add and + * remove with Image::Add/RemoveAnimationEventListener + * Use Image::ShowUntilClosed with a ms for custom animation duration, and the + * AnimationListener::OnAnimationStep() will be called at that duration. + */ +class AnimationEventListener { + public: + virtual void OnAnimationStep() = 0; +}; + } // namespace graphics #endif // GRAPHICS_IMAGE_EVENT_H diff --git a/graphics/test/image_unittest.cc b/graphics/test/image_unittest.cc index 0f2c0e9..d845c12 100644 --- a/graphics/test/image_unittest.cc +++ b/graphics/test/image_unittest.cc @@ -232,10 +232,10 @@ TEST(ImageEventTest, HandlesEvents) { EXPECT_EQ(listener.GetLatestEvent().GetMouseAction(), graphics::MouseAction::kReleased); generator.MoveMouseTo(30, 30); - // Nothing happens, mosue is up. - EXPECT_EQ(listener.GetLatestEvent().GetX(), 90); - EXPECT_EQ(listener.GetLatestEvent().GetY(), 80); - EXPECT_EQ(listener.GetLatestEvent().GetMouseAction(), graphics::MouseAction::kReleased); + // Mouse moved event. + EXPECT_EQ(listener.GetLatestEvent().GetX(), 30); + EXPECT_EQ(listener.GetLatestEvent().GetY(), 30); + EXPECT_EQ(listener.GetLatestEvent().GetMouseAction(), graphics::MouseAction::kMoved); // Ensure other mouse buttons don't interfere. generator.MouseDown(10, 20); From 2cc7d27e499d0c19cc0f1da0783188a27606095d Mon Sep 17 00:00:00 2001 From: Katie Dektar Date: Tue, 15 Sep 2020 20:14:51 -0700 Subject: [PATCH 04/40] Fix off by one bug in rectangle --- graphics/image.cc | 5 ++++- graphics/test/image_unittest.cc | 6 +++--- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/graphics/image.cc b/graphics/image.cc index d400d9b..2da194d 100644 --- a/graphics/image.cc +++ b/graphics/image.cc @@ -212,7 +212,10 @@ bool Image::DrawRectangle(int x, int y, int width, int height, int red, if (!CheckPixelInBounds(x, y) || !CheckColorInBounds(color)) { return false; } - cimage_->draw_rectangle(x, y, x + width, y + height, color); + if (width < 0 || height < 0) { + return false; + } + cimage_->draw_rectangle(x, y, x + width - 1, y + height - 1, color); return true; } diff --git a/graphics/test/image_unittest.cc b/graphics/test/image_unittest.cc index d845c12..7baec34 100644 --- a/graphics/test/image_unittest.cc +++ b/graphics/test/image_unittest.cc @@ -154,7 +154,7 @@ TEST(ImageTest, DrawsLinesWithThickness) { remove("DrawsLinesWithThicknessHorizontal.bmp"); remove("DrawsLinesWithThicknessVertical.bmp"); - int thickness = 20; + int thickness = 21; int size = 100; graphics::Color blue(0, 0, 255); @@ -162,13 +162,13 @@ TEST(ImageTest, DrawsLinesWithThickness) { graphics::Image actual(size, size); // Horizontal rectangle is the same as a thick line. - expected.DrawRectangle(10, 40, 80, thickness, blue); + expected.DrawRectangle(10, 40, 81, thickness, blue); actual.DrawLine(10, 50, 90, 50, blue, thickness); EXPECT_TRUE(ImagesMatch(&expected, &actual, "DrawsLinesWithThicknessHorizontal.bmp", DiffType::kTypeHighlight)); // Vertical rectangle is the same as a thick line. - expected.DrawRectangle(40, 5, thickness, 90, blue); + expected.DrawRectangle(40, 5, thickness, 91, blue); actual.DrawLine(50, 5, 50, 95, blue, thickness); EXPECT_TRUE(ImagesMatch(&expected, &actual, "DrawsLinesWithThicknessVertical.bmp", DiffType::kTypeHighlight)); From e207382fe24a10cacd02b2c680207f10b8f91cf2 Mon Sep 17 00:00:00 2001 From: Katie Dektar Date: Tue, 15 Sep 2020 20:36:41 -0700 Subject: [PATCH 05/40] Use const --- graphics/image.h | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/graphics/image.h b/graphics/image.h index bb70979..1876dae 100644 --- a/graphics/image.h +++ b/graphics/image.h @@ -18,6 +18,8 @@ using namespace cimg_library; namespace graphics { +const int kDefaultAnimationMs = 30; + /** * Represents an RGB pixel color, where |red|, |green| and |blue| * may be between 0 and 255, inclusive. Default color is black. @@ -111,7 +113,7 @@ class Image { * could not be shown. */ bool ShowUntilClosed(const std::string& title) { - return ShowUntilClosed(title, 30); + return ShowUntilClosed(title, kDefaultAnimationMs); } bool ShowUntilClosed(const std::string& title, int animation_ms); From 0664317eae11552fb411c146983f1f0e5d54f4a6 Mon Sep 17 00:00:00 2001 From: Katie Dektar Date: Fri, 2 Oct 2020 15:28:07 -0700 Subject: [PATCH 06/40] Adds copy and assign operators for graphics::Color --- graphics/image.h | 20 ++++++++++++++++++++ graphics/test/image_unittest.cc | 14 ++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/graphics/image.h b/graphics/image.h index 1876dae..c061600 100644 --- a/graphics/image.h +++ b/graphics/image.h @@ -27,20 +27,40 @@ const int kDefaultAnimationMs = 30; class Color { public: explicit Color(int red = 0, int green = 0, int blue = 0); + + // Copy constructor. + Color(const Color& other) { + red_ = other.Red(); + green_ = other.Green(); + blue_ = other.Blue(); + } + + // Assignment operator. + Color& operator=(const Color& other) { + red_ = other.Red(); + green_ = other.Green(); + blue_ = other.Blue(); + return *this; + } + ~Color() = default; + // Equality operator. bool operator==(const Color& other) const { return red_ == other.Red() && green_ == other.Green() && blue_ == other.Blue(); } + // Inequality operator. bool operator!=(const Color& other) const { return red_ != other.Red() || green_ != other.Green() || blue_ != other.Blue(); } + // Getters int Red() const { return red_; } int Green() const { return green_; } int Blue() const { return blue_; } + // Setters void SetRed(int red) { red_ = red; } void SetGreen(int green) { green_ = green; } void SetBlue(int blue) { blue_ = blue; } diff --git a/graphics/test/image_unittest.cc b/graphics/test/image_unittest.cc index 7baec34..d65f130 100644 --- a/graphics/test/image_unittest.cc +++ b/graphics/test/image_unittest.cc @@ -48,6 +48,20 @@ TEST(ImageDeathTest, InvalidSizeConstructorNegative) { ASSERT_DEATH(graphics::Image image(10, -1), ""); } +TEST(ColorTest, ColorOperators) { + graphics::Color black(0, 0, 0); + graphics::Color red(255, 0, 0); + ASSERT_NE(black, red); + ASSERT_EQ(red, graphics::Color(255, 0, 0)); + + graphics::Color red_copy = red; + ASSERT_EQ(red, red_copy); + + graphics::Color& red_ref = red; + red_ref.SetBlue(255); + ASSERT_EQ(red.Blue(), 255); +} + TEST(ImageTest, BlankImageCreation) { // Check size is correct. graphics::Image image(10, 10); From cb437714a9a96a76f612ac6b4c2d05e6596a3b93 Mon Sep 17 00:00:00 2001 From: Katie Dektar Date: Mon, 19 Oct 2020 14:37:15 -0700 Subject: [PATCH 07/40] Add simple animation capability with ShowForMs function --- graphics/image.cc | 3 ++- graphics/image.h | 15 ++++++++++++++- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/graphics/image.cc b/graphics/image.cc index 2da194d..863c6b1 100644 --- a/graphics/image.cc +++ b/graphics/image.cc @@ -79,7 +79,7 @@ bool Image::SaveImageBmp(const string& filename) const { return true; } -bool Image::Show(const string& title) { +bool Image::ShowForMs(int milliseconds, const std::string& title) { if (!IsValid()) return false; if (!display_) { try { @@ -93,6 +93,7 @@ bool Image::Show(const string& title) { display_->set_title("%s", title.c_str()); display_->show(); display_->display(*cimage_); + if (milliseconds > 0) display_->wait(milliseconds); } return true; } diff --git a/graphics/image.h b/graphics/image.h index c061600..98bb3c7 100644 --- a/graphics/image.h +++ b/graphics/image.h @@ -119,7 +119,20 @@ class Image { * Shows the image in a window with the title |title|. Returns false if * the image could not be shown. */ - bool Show(const std::string& title); + bool Show(const std::string& title) { return ShowForMs(0, "Image"); } + + /** + * Shows the image in a window for |milliseconds| duration. Returns false if + * the image could not be shown, or true after |milliseconds| are ellapsed. + */ + bool ShowForMs(int milliseconds) { return ShowForMs(milliseconds, "Image"); } + + /** + * Shows the image in a window with the title |title| for |milliseconds| + * duration. Returns false if the image could not be shown, or true after + * |milliseconds| are ellapsed. + */ + bool ShowForMs(int milliseconds, const std::string& title); /** * Shows the current image until the window is closed. Returns false if From 83d0337f5116467e3ed9149bc79e5b4cf259544f Mon Sep 17 00:00:00 2001 From: Katie Dektar Date: Tue, 20 Oct 2020 14:41:12 -0700 Subject: [PATCH 08/40] Add SendAnimationEvent to TestEventGenerator --- graphics/image.cc | 10 +++++--- graphics/image.h | 2 ++ graphics/test/image_unittest.cc | 35 ++++++++++++++++++++++++++++ graphics/test/test_event_generator.h | 5 ++++ 4 files changed, 49 insertions(+), 3 deletions(-) diff --git a/graphics/image.cc b/graphics/image.cc index 863c6b1..7b3d544 100644 --- a/graphics/image.cc +++ b/graphics/image.cc @@ -105,9 +105,7 @@ bool Image::ShowUntilClosed(const string& title, int animation_ms) { while (!display_->is_closed()) { ProcessEvent(); if (timer_ > animation_ms) { - for (auto listener : animation_listeners_) { - listener->OnAnimationStep(); - } + ProcessAnimation(); // Reset the timer. timer_ = timer_ % animation_ms; } @@ -272,6 +270,12 @@ void Image::ProcessEvent() { } } +void Image::ProcessAnimation() { + for (auto listener : animation_listeners_) { + listener->OnAnimationStep(); + } +} + bool Image::CheckPixelInBounds(int x, int y) const { if (x < 0 || y < 0 || x >= GetWidth() || y >= GetHeight()) { cout << "(" << x << ", " << y << ") is out of bounds." << endl; diff --git a/graphics/image.h b/graphics/image.h index 98bb3c7..03da895 100644 --- a/graphics/image.h +++ b/graphics/image.h @@ -344,6 +344,8 @@ class Image { void ProcessEvent(); + void ProcessAnimation(); + bool IsValid() const { return height_ > 0 && width_ > 0; } bool CheckPixelInBounds(int x, int y) const; diff --git a/graphics/test/image_unittest.cc b/graphics/test/image_unittest.cc index d65f130..a3bc41b 100644 --- a/graphics/test/image_unittest.cc +++ b/graphics/test/image_unittest.cc @@ -266,6 +266,41 @@ TEST(ImageEventTest, HandlesEvents) { image.Hide(); } +class TestAnimationEventListener : public graphics::AnimationEventListener { + public: + TestAnimationEventListener() = default; + ~TestAnimationEventListener() = default; + void OnAnimationStep() override { + num_events_++; + } + + int GetNumEvents() { + return num_events_; + } + private: + int num_events_ = 0; +}; + +TEST(AnimationEventTest, CallsAnimationListeners) { + TestAnimationEventListener listener; + ASSERT_EQ(0, listener.GetNumEvents()); + graphics::Image image(50, 50); + graphics::TestEventGenerator generator(&image); + image.Show(); + + image.AddAnimationEventListener(listener); + ASSERT_EQ(0, listener.GetNumEvents()); + generator.SendAnimationEvent(); + ASSERT_EQ(1, listener.GetNumEvents()); + generator.SendAnimationEvent(); + ASSERT_EQ(2, listener.GetNumEvents()); + image.RemoveAnimationEventListener(listener); + + // Actually removed. + generator.SendAnimationEvent(); + ASSERT_EQ(2, listener.GetNumEvents()); +} + int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); diff --git a/graphics/test/test_event_generator.h b/graphics/test/test_event_generator.h index 2110222..f5dec04 100644 --- a/graphics/test/test_event_generator.h +++ b/graphics/test/test_event_generator.h @@ -46,6 +46,11 @@ class TestEventGenerator { image_->ProcessEvent(); } + void SendAnimationEvent() { + if (!image_->GetDisplayForTesting()) return; + image_->ProcessAnimation(); + } + private: graphics::Image* image_; // Unowned }; From 96289847e1f18bba99d75d7bb4a1a2a449e239af Mon Sep 17 00:00:00 2001 From: Katie Dektar Date: Fri, 23 Oct 2020 09:35:31 -0700 Subject: [PATCH 09/40] Fix bug where some mouse moved events were not sent --- graphics/image.cc | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/graphics/image.cc b/graphics/image.cc index 7b3d544..a7c6e10 100644 --- a/graphics/image.cc +++ b/graphics/image.cc @@ -258,9 +258,9 @@ void Image::ProcessEvent() { for (auto listener : mouse_listeners_) { listener->OnMouseEvent(latest_event_); } - } else if (mouse_x != latest_event_.GetX() && - mouse_y != latest_event_.GetY() && - mouse_x >= 0 && mouse_y >= 0) { + } else if ((mouse_x != latest_event_.GetX() || + mouse_y != latest_event_.GetY()) && + (mouse_x >= 0 && mouse_y >= 0)) { // Mouse position has changed, send a move. latest_event_ = MouseEvent(mouse_x, mouse_y, MouseAction::kMoved); for (auto listener : mouse_listeners_) { From 6c3af102abb67acb1c3ec22d74eb045fae8573e6 Mon Sep 17 00:00:00 2001 From: Katie Dektar Date: Sat, 24 Oct 2020 10:36:40 -0700 Subject: [PATCH 10/40] Fix bug in image.h where wrong image title was used to Show --- graphics/image.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/graphics/image.h b/graphics/image.h index 03da895..c5ae08b 100644 --- a/graphics/image.h +++ b/graphics/image.h @@ -119,7 +119,7 @@ class Image { * Shows the image in a window with the title |title|. Returns false if * the image could not be shown. */ - bool Show(const std::string& title) { return ShowForMs(0, "Image"); } + bool Show(const std::string& title) { return ShowForMs(0, title); } /** * Shows the image in a window for |milliseconds| duration. Returns false if From 87aa8ddeb7d1a479570bfac92302ea56a4bcac9e Mon Sep 17 00:00:00 2001 From: Katie Dektar Date: Wed, 11 Nov 2020 16:12:27 -0800 Subject: [PATCH 11/40] Add license header and Google LLC to copyright holder --- LICENSE | 2 +- README.md | 2 +- graphics/image.cc | 6 ++++++ graphics/image.h | 6 ++++++ graphics/image_event.h | 6 ++++++ graphics/test/Makefile | 6 ++++++ graphics/test/image_test_utils.h | 6 ++++++ graphics/test/image_unittest.cc | 6 ++++++ graphics/test/test_event_generator.h | 6 ++++++ 9 files changed, 44 insertions(+), 2 deletions(-) diff --git a/LICENSE b/LICENSE index 74637fb..d47d372 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ MIT License -Copyright (c) 2018 Paul Salvador Inventado +Copyright (c) 2020 Paul Salvador Inventado and Google LLC Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/README.md b/README.md index faa754e..ea844dd 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # C++ Utils -Libraries for student C++ code. +Libraries for student C++ code available under the MIT license. ## Graphics diff --git a/graphics/image.cc b/graphics/image.cc index a7c6e10..2a384bc 100644 --- a/graphics/image.cc +++ b/graphics/image.cc @@ -1,3 +1,9 @@ +// Copyright 2020 Paul Salvador Inventado and Google LLC +// +// Use of this source code is governed by an MIT-style +// license that can be found in the LICENSE file or at +// https://opensource.org/licenses/MIT. + #include #include #include diff --git a/graphics/image.h b/graphics/image.h index c5ae08b..6171c5c 100644 --- a/graphics/image.h +++ b/graphics/image.h @@ -1,3 +1,9 @@ +// Copyright 2020 Paul Salvador Inventado and Google LLC +// +// Use of this source code is governed by an MIT-style +// license that can be found in the LICENSE file or at +// https://opensource.org/licenses/MIT. + #include #include #include diff --git a/graphics/image_event.h b/graphics/image_event.h index ad43629..0b5599f 100644 --- a/graphics/image_event.h +++ b/graphics/image_event.h @@ -1,3 +1,9 @@ +// Copyright 2020 Paul Salvador Inventado and Google LLC +// +// Use of this source code is governed by an MIT-style +// license that can be found in the LICENSE file or at +// https://opensource.org/licenses/MIT. + #ifndef GRAPHICS_IMAGE_EVENT_H #define GRAPHICS_IMAGE_EVENT_H diff --git a/graphics/test/Makefile b/graphics/test/Makefile index 71a9cd6..cac1210 100644 --- a/graphics/test/Makefile +++ b/graphics/test/Makefile @@ -1,3 +1,9 @@ +# Copyright 2020 Paul Salvador Inventado and Google LLC +# +# Use of this source code is governed by an MIT-style +# license that can be found in the LICENSE file or at +# https://opensource.org/licenses/MIT. + .PHONY: update_cimg image_unittest update_cimg: diff --git a/graphics/test/image_test_utils.h b/graphics/test/image_test_utils.h index df3b4c1..d1d3b42 100644 --- a/graphics/test/image_test_utils.h +++ b/graphics/test/image_test_utils.h @@ -1,3 +1,9 @@ +// Copyright 2020 Paul Salvador Inventado and Google LLC +// +// Use of this source code is governed by an MIT-style +// license that can be found in the LICENSE file or at +// https://opensource.org/licenses/MIT. + #include #include diff --git a/graphics/test/image_unittest.cc b/graphics/test/image_unittest.cc index a3bc41b..a79ffff 100644 --- a/graphics/test/image_unittest.cc +++ b/graphics/test/image_unittest.cc @@ -1,3 +1,9 @@ +// Copyright 2020 Paul Salvador Inventado and Google LLC +// +// Use of this source code is governed by an MIT-style +// license that can be found in the LICENSE file or at +// https://opensource.org/licenses/MIT. + #include #include #include diff --git a/graphics/test/test_event_generator.h b/graphics/test/test_event_generator.h index f5dec04..509dd17 100644 --- a/graphics/test/test_event_generator.h +++ b/graphics/test/test_event_generator.h @@ -1,3 +1,9 @@ +// Copyright 2020 Paul Salvador Inventado and Google LLC +// +// Use of this source code is governed by an MIT-style +// license that can be found in the LICENSE file or at +// https://opensource.org/licenses/MIT. + #include "../cimg/CImg.h" #include "../image.h" From e0956eb0fe19e00a51aff96db3cb9a889f2c1e1b Mon Sep 17 00:00:00 2001 From: Katie Dektar Date: Wed, 2 Dec 2020 16:00:25 -0800 Subject: [PATCH 12/40] Fix #2 where order of drawing points matters, and fix unittest loading png to load bmp --- .gitignore | 2 +- graphics/image.cc | 24 ++++-- graphics/test/example_bmp.bmp | Bin 0 -> 306 bytes graphics/test/image_unittest.cc | 133 +++++++++++++++++++++++++------- 4 files changed, 123 insertions(+), 36 deletions(-) create mode 100644 graphics/test/example_bmp.bmp diff --git a/.gitignore b/.gitignore index ea894b6..a684e47 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,4 @@ *~ graphics/test/image_unittest graphics/test/*.bmp - +!graphics/test/example_bmp.bmp diff --git a/graphics/image.cc b/graphics/image.cc index 2a384bc..cd37217 100644 --- a/graphics/image.cc +++ b/graphics/image.cc @@ -4,13 +4,15 @@ // license that can be found in the LICENSE file or at // https://opensource.org/licenses/MIT. +#include "image.h" + #include + #include #include #include #include "cimg/CImg.h" -#include "image.h" using std::cout; using std::endl; @@ -167,8 +169,8 @@ bool Image::SetBlue(int x, int y, int b) { return SetPixel(x, y, 2, b); } bool Image::DrawLine(int x0, int y0, int x1, int y1, int red, int green, int blue, int thickness) { const int color[] = {red, green, blue}; - if (thickness < 1 || !CheckPixelInBounds(x0, y0) || !CheckPixelInBounds(x1, y1) || - !CheckColorInBounds(color)) { + if (thickness < 1 || !CheckPixelInBounds(x0, y0) || + !CheckPixelInBounds(x1, y1) || !CheckColorInBounds(color)) { return false; } if (x0 == x1 && y0 == y1) { @@ -178,6 +180,18 @@ bool Image::DrawLine(int x0, int y0, int x1, int y1, int red, int green, cimage_->draw_line(x0, y0, x1, y1, color); return true; } + + // Swap x0 and y0 with x1 and y1 so the lower x goes first. + // Fixes test DrawsLinesWithThicknessOrderDoesntMatter. + if (x1 < x0) { + int x_tmp = x1; + int y_tmp = y1; + x1 = x0; + y1 = y0; + x0 = x_tmp; + y0 = y_tmp; + } + // Use CImage::draw_polygon to draw a thick line. const double diff_x = x0 - x1; const double diff_y = y0 - y1; @@ -265,8 +279,8 @@ void Image::ProcessEvent() { listener->OnMouseEvent(latest_event_); } } else if ((mouse_x != latest_event_.GetX() || - mouse_y != latest_event_.GetY()) && - (mouse_x >= 0 && mouse_y >= 0)) { + mouse_y != latest_event_.GetY()) && + (mouse_x >= 0 && mouse_y >= 0)) { // Mouse position has changed, send a move. latest_event_ = MouseEvent(mouse_x, mouse_y, MouseAction::kMoved); for (auto listener : mouse_listeners_) { diff --git a/graphics/test/example_bmp.bmp b/graphics/test/example_bmp.bmp new file mode 100644 index 0000000000000000000000000000000000000000..0ced88e8a19cab36f04852d6773787449f887df4 GIT binary patch literal 306 zcmZ?rHDY7{12Z700mPh8%*Y@C7XJexL297tK-?2tMz|12?*IS)5NR|9A$@R7Kz(qn jKtY6=5DADJghZH$EC(?OAqU|jlL#|`q7b9t47~aPEkAY_ literal 0 HcmV?d00001 diff --git a/graphics/test/image_unittest.cc b/graphics/test/image_unittest.cc index a79ffff..d52285f 100644 --- a/graphics/test/image_unittest.cc +++ b/graphics/test/image_unittest.cc @@ -4,11 +4,13 @@ // license that can be found in the LICENSE file or at // https://opensource.org/licenses/MIT. +#include "../image.h" + #include #include + #include -#include "../image.h" #include "image_test_utils.h" #include "test_event_generator.h" @@ -18,7 +20,7 @@ TEST(ImageTest, CreatesImageWithoutCrashing) { TEST(ImageTest, LoadsImageWithoutCrashing) { graphics::Image image; - image.Load("example_fractal_tree.png"); + image.Load("example_bmp.bmp"); EXPECT_TRUE(image.GetWidth() > 0); EXPECT_TRUE(image.GetHeight() > 0); } @@ -174,6 +176,8 @@ TEST(ImageTest, DrawsLinesWithThickness) { remove("DrawsLinesWithThicknessHorizontal.bmp"); remove("DrawsLinesWithThicknessVertical.bmp"); + // Use an odd size thickness. Even size thickness isn't evenly divisible + // by 2, meaning we can't create a rectangle of the right size. int thickness = 21; int size = 100; graphics::Color blue(0, 0, 255); @@ -184,17 +188,19 @@ TEST(ImageTest, DrawsLinesWithThickness) { // Horizontal rectangle is the same as a thick line. expected.DrawRectangle(10, 40, 81, thickness, blue); actual.DrawLine(10, 50, 90, 50, blue, thickness); - EXPECT_TRUE(ImagesMatch(&expected, &actual, "DrawsLinesWithThicknessHorizontal.bmp", - DiffType::kTypeHighlight)); + EXPECT_TRUE(ImagesMatch(&expected, &actual, + "DrawsLinesWithThicknessHorizontal.bmp", + DiffType::kTypeHighlight)); // Vertical rectangle is the same as a thick line. expected.DrawRectangle(40, 5, thickness, 91, blue); actual.DrawLine(50, 5, 50, 95, blue, thickness); - EXPECT_TRUE(ImagesMatch(&expected, &actual, "DrawsLinesWithThicknessVertical.bmp", - DiffType::kTypeHighlight)); + EXPECT_TRUE(ImagesMatch(&expected, &actual, + "DrawsLinesWithThicknessVertical.bmp", + DiffType::kTypeHighlight)); - // 45 degree rectangle is as thick as expected. Check some points that wouldn't be - // colored unless the line had appropriate thickness. + // 45 degree rectangle is as thick as expected. Check some points that + // wouldn't be colored unless the line had appropriate thickness. graphics::Color green(0, 255, 0); actual.DrawLine(0, 0, size - 1, size - 1, green, thickness); EXPECT_EQ(actual.GetColor(thickness / 2, 0), green); @@ -203,7 +209,69 @@ TEST(ImageTest, DrawsLinesWithThickness) { EXPECT_EQ(actual.GetColor(size / 2, size / 2 + thickness / 2), green); // But not too wide! - EXPECT_NE(actual.GetColor(size / 2, size / 2 + std::sqrt(2 * thickness * thickness)), green); + EXPECT_NE(actual.GetColor(size / 2, + size / 2 + std::sqrt(2 * thickness * thickness)), + green); +} + +TEST(ImageTest, DrawsLinesWithThicknessOrderDoesntMatter) { + remove("DrawsLinesWithThicknessOrderDiagonal1.bmp"); + remove("DrawsLinesWithThicknessOrderDiagonal2.bmp"); + remove("DrawsLinesWithThicknessOrderDiagonal3.bmp"); + remove("DrawsLinesWithThicknessOrderDiagonal4.bmp"); + remove("DrawsLinesWithThicknessOrderHorizontal.bmp"); + remove("DrawsLinesWithThicknessOrderVertical.bmp"); + + int thickness = 10; + int size = 100; + graphics::Color blue(0, 0, 255); + graphics::Color green(0, 255, 0); + graphics::Color black(0, 0, 0); + + graphics::Image expected(size, size); + graphics::Image actual(size, size); + + // Expected has smaller x0 than x1, smaller y0 than y1. + expected.DrawLine(20, 31, 17, 80, blue, thickness); + actual.DrawLine(17, 80, 20, 31, blue, thickness); + ASSERT_TRUE(ImagesMatch(&expected, &actual, + "DrawsLinesWithThicknessOrderDiagonal1.bmp", + DiffType::kTypeHighlight)); + + // Expected has bigger x0 than x1, smaller y0 than y1. + expected.DrawLine(77, 20, 80, 80, black, thickness); + actual.DrawLine(80, 80, 77, 20, black, thickness); + ASSERT_TRUE(ImagesMatch(&expected, &actual, + "DrawsLinesWithThicknessOrderDiagonal2.bmp", + DiffType::kTypeHighlight)); + + // Expected has smaller x0 than x1, bigger y0 than y1. + expected.DrawLine(10, 78, 80, 13, black, thickness); + actual.DrawLine(80, 13, 10, 78, black, thickness); + ASSERT_TRUE(ImagesMatch(&expected, &actual, + "DrawsLinesWithThicknessOrderDiagonal3.bmp", + DiffType::kTypeHighlight)); + + // Expected has bigger x0 than x1, bigger y0 than y1. + expected.DrawLine(57, 80, 80, 20, blue, thickness); + actual.DrawLine(80, 20, 57, 80, blue, thickness); + ASSERT_TRUE(ImagesMatch(&expected, &actual, + "DrawsLinesWithThicknessOrderDiagonal4.bmp", + DiffType::kTypeHighlight)); + + // Horizontal rectangle is the same as a thick line. + expected.DrawLine(10, 50, 90, 50, green, thickness); + actual.DrawLine(90, 50, 10, 50, green, thickness); + ASSERT_TRUE(ImagesMatch(&expected, &actual, + "DrawsLinesWithThicknessOrderHorizontal.bmp", + DiffType::kTypeHighlight)); + + // Vertical rectangle is the same as a thick line. + expected.DrawLine(50, 5, 50, 95, black, thickness); + actual.DrawLine(50, 95, 50, 5, black, thickness); + ASSERT_TRUE(ImagesMatch(&expected, &actual, + "DrawsLinesWithThicknessOrderVertical.bmp", + DiffType::kTypeHighlight)); } class TestEventListener : public graphics::MouseEventListener { @@ -211,18 +279,19 @@ class TestEventListener : public graphics::MouseEventListener { TestEventListener() = default; ~TestEventListener() = default; void OnMouseEvent(const graphics::MouseEvent& event) override { - latest_event_ = graphics::MouseEvent(event.GetX(), event.GetY(), event.GetMouseAction()); + latest_event_ = graphics::MouseEvent(event.GetX(), event.GetY(), + event.GetMouseAction()); } - graphics::MouseEvent GetLatestEvent() { - return latest_event_; - } + graphics::MouseEvent GetLatestEvent() { return latest_event_; } + private: - graphics::MouseEvent latest_event_ = graphics::MouseEvent(0, 0, graphics::MouseAction::kReleased); + graphics::MouseEvent latest_event_ = + graphics::MouseEvent(0, 0, graphics::MouseAction::kReleased); }; -// We can send fake events if we have a reference to the image on which to send events, and we -// are not in the ShowUntilClosed loop. +// We can send fake events if we have a reference to the image on which to send +// events, and we are not in the ShowUntilClosed loop. TEST(ImageEventTest, HandlesEvents) { TestEventListener listener; int size = 100; @@ -234,28 +303,33 @@ TEST(ImageEventTest, HandlesEvents) { generator.MouseDown(10, 20); EXPECT_EQ(listener.GetLatestEvent().GetX(), 10); EXPECT_EQ(listener.GetLatestEvent().GetY(), 20); - EXPECT_EQ(listener.GetLatestEvent().GetMouseAction(), graphics::MouseAction::kPressed); + EXPECT_EQ(listener.GetLatestEvent().GetMouseAction(), + graphics::MouseAction::kPressed); generator.MoveMouseTo(30, 80); EXPECT_EQ(listener.GetLatestEvent().GetX(), 30); EXPECT_EQ(listener.GetLatestEvent().GetY(), 80); - EXPECT_EQ(listener.GetLatestEvent().GetMouseAction(), graphics::MouseAction::kDragged); + EXPECT_EQ(listener.GetLatestEvent().GetMouseAction(), + graphics::MouseAction::kDragged); generator.MoveMouseTo(90, 80); EXPECT_EQ(listener.GetLatestEvent().GetX(), 90); EXPECT_EQ(listener.GetLatestEvent().GetY(), 80); - EXPECT_EQ(listener.GetLatestEvent().GetMouseAction(), graphics::MouseAction::kDragged); + EXPECT_EQ(listener.GetLatestEvent().GetMouseAction(), + graphics::MouseAction::kDragged); generator.MouseUp(); EXPECT_EQ(listener.GetLatestEvent().GetX(), 90); EXPECT_EQ(listener.GetLatestEvent().GetY(), 80); - EXPECT_EQ(listener.GetLatestEvent().GetMouseAction(), graphics::MouseAction::kReleased); + EXPECT_EQ(listener.GetLatestEvent().GetMouseAction(), + graphics::MouseAction::kReleased); generator.MoveMouseTo(30, 30); // Mouse moved event. EXPECT_EQ(listener.GetLatestEvent().GetX(), 30); EXPECT_EQ(listener.GetLatestEvent().GetY(), 30); - EXPECT_EQ(listener.GetLatestEvent().GetMouseAction(), graphics::MouseAction::kMoved); + EXPECT_EQ(listener.GetLatestEvent().GetMouseAction(), + graphics::MouseAction::kMoved); // Ensure other mouse buttons don't interfere. generator.MouseDown(10, 20); @@ -263,10 +337,12 @@ TEST(ImageEventTest, HandlesEvents) { generator.RightMouseUp(); EXPECT_EQ(listener.GetLatestEvent().GetX(), 10); EXPECT_EQ(listener.GetLatestEvent().GetY(), 20); - EXPECT_EQ(listener.GetLatestEvent().GetMouseAction(), graphics::MouseAction::kPressed); + EXPECT_EQ(listener.GetLatestEvent().GetMouseAction(), + graphics::MouseAction::kPressed); generator.RightMouseDown(); generator.MouseUp(); - EXPECT_EQ(listener.GetLatestEvent().GetMouseAction(), graphics::MouseAction::kReleased); + EXPECT_EQ(listener.GetLatestEvent().GetMouseAction(), + graphics::MouseAction::kReleased); image.RemoveMouseEventListener(listener); image.Hide(); @@ -276,13 +352,10 @@ class TestAnimationEventListener : public graphics::AnimationEventListener { public: TestAnimationEventListener() = default; ~TestAnimationEventListener() = default; - void OnAnimationStep() override { - num_events_++; - } + void OnAnimationStep() override { num_events_++; } + + int GetNumEvents() { return num_events_; } - int GetNumEvents() { - return num_events_; - } private: int num_events_ = 0; }; @@ -307,7 +380,7 @@ TEST(AnimationEventTest, CallsAnimationListeners) { ASSERT_EQ(2, listener.GetNumEvents()); } -int main(int argc, char **argv) { +int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } From c0f8cd2ba6e237918aec77edcaaa19fdece25a26 Mon Sep 17 00:00:00 2001 From: Katie Dektar Date: Wed, 2 Dec 2020 16:16:51 -0800 Subject: [PATCH 13/40] Fixes #3 (tested on Mac) --- graphics/test/Makefile | 42 ++++++++++++++++++++++++++++++++++++------ 1 file changed, 36 insertions(+), 6 deletions(-) diff --git a/graphics/test/Makefile b/graphics/test/Makefile index cac1210..542e467 100644 --- a/graphics/test/Makefile +++ b/graphics/test/Makefile @@ -6,19 +6,49 @@ .PHONY: update_cimg image_unittest +OS_NAME := $(shell uname -s | tr A-Z a-z) +SHELL := /bin/bash +HAS_GTEST := $(shell echo -e "int main() { }" >> test.cc ; clang++ test.cc -o test -lgtest 2> /dev/null; echo $$?; rm -f test.cc test;) +COMPILE_FLAGS := -lm -lX11 -lpthread + +ifeq ($(OS_NAME), darwin) + COMPILE_FLAGS := -lm -lpthread -lX11 -I/usr/X11R6/include -L/usr/X11R6/lib + HAS_BREW := $(shell command -v brew 2> /dev/null) +endif + update_cimg: @echo -e "Getting CImg..." @wget -q https://raw.githubusercontent.com/dtschump/CImg/master/CImg.h @mv CImg.h ../cimg/ @echo -e "CImg updated" -/usr/lib/libgtest.a: - @echo -e "google test library not installed\n" +install_gtest: +ifeq ($(HAS_GTEST),1) + @echo -e "google test not installed\n" +ifeq ($(OS_NAME), darwin) +ifndef ($(HAS_BREW)) + @echo -e "Installing brew, please provide your password when asked.\n" + @/bin/bash -c "$$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)" + @brew install coreutils + # Need to redefine the path directories otherwise this will fail the first time. +endif @echo -e "Installing cmake. Please provide the password when asked\n" - @sudo apt-get install cmake # install cmake + @brew install cmake @echo -e "\nDownloading and installing googletest\n" + @cd /tmp/; git clone https://github.com/google/googletest; cd googletest; mkdir build; cd build; cmake .. -DCMAKE_CXX_STANDARD=17; make; make install + @echo -e "Finished installing google test\n" +else +ifneq ($(shell lsb_release -sr), 20.04) @cd /tmp/; git clone https://github.com/google/googletest.git; cd googletest; cmake CMakeLists.txt; make; sudo cp -r googletest/include/. /usr/include; sudo cp -r googlemock/include/. /usr/include; sudo cp lib/*.a /usr/lib - @echo -e "Finished installing google test library\n" +else + @echo -e "Installing cmake. Please provide the password when asked\n" + @sudo apt-get install cmake # install cmake + @echo -e "\nDownloading and installing googletest\n" + @sudo apt-get install libgtest-dev libgmock-dev + @echo -e "Finished installing google test\n" +endif +endif +endif -image_unittest: /usr/lib/libgtest.a - @clang++ -std=c++17 ../image.cc image_unittest.cc -o image_unittest -pthread -lgtest -lm -lX11 -lpthread && ./image_unittest +image_unittest: install_gtest + @clang++ -std=c++17 ../image.cc image_unittest.cc -o image_unittest -pthread -lgtest $(COMPILE_FLAGS) && ./image_unittest From 10a9f6660633f58ba14200f1d8b83cdcf6dfa940 Mon Sep 17 00:00:00 2001 From: Katie Dektar Date: Mon, 23 Nov 2020 22:29:43 -0800 Subject: [PATCH 14/40] Initial version of karel with move and turn left and some drawing --- karel/karel.cc | 243 +++++++++++++++++++++++++++++++++++++++++++++++++ karel/karel.h | 22 +++++ karel/test.cc | 23 +++++ 3 files changed, 288 insertions(+) create mode 100644 karel/karel.cc create mode 100644 karel/karel.h create mode 100644 karel/test.cc diff --git a/karel/karel.cc b/karel/karel.cc new file mode 100644 index 0000000..e24169a --- /dev/null +++ b/karel/karel.cc @@ -0,0 +1,243 @@ +#include "karel.h" + +#include +#include + +namespace karel { + +enum Orientation { + kNorth, + kEast, + kSouth, + kWest, +}; + +class Cell { + public: + int GetNumBeepers() { return num_beepers_; } + void SetNumBeepers(int beepers) { num_beepers_ = beepers; } + // bool HasNorthWall() { return north_wall_; } + // bool HasSouthWall() { return south_wall_; } + // bool HasSouthWall() { return south_wall_; } + // bool HasWestWall() { return west_wall_; } + private: + bool num_beepers_ = 0; + // bool north_wall_ = false; + // bool east_wall_ = false; + // bool south_wall_ = false; + // bool west_wall_ = false; +}; + +const int dimen = 10; +const int pxPerCell = 50; +const int robotSize = 30; +const int beeperSize = 25; +const int eyeSize = 4; +const int legLength = 4; +const graphics::Color eyeColor(50, 50, 50); +const graphics::Color karelColor(125, 125, 125); +const graphics::Color markColor(50, 50, 255); +const graphics::Color beeperColor(200, 0, 200); + +class Robot { + public: + static karel::Robot& GetInstance() { + static Robot instance; + instance.Initialize(); + instance.Show(); + return instance; + } + + // Disallow copy and assign. + Robot(const Robot&) = delete; + karel::Robot& operator=(const Robot&) = delete; + + void Initialize() { + image_.Initialize(dimen * pxPerCell, dimen * pxPerCell); + for (int i = 0; i < dimen; i++) { + world_.push_back(std::vector()); + for (int j = 0; j < dimen; j++) { + world_[i].push_back(Cell()); + } + } + world_[5][3].SetNumBeepers(1); + world_[2][7].SetNumBeepers(1); + DrawWorld(); + DrawRobot(x_ * pxPerCell + robotSize / 2, y_ * pxPerCell + robotSize / 2); + image_.ShowForMs(500, "Karel's World"); + } + + void Show() { image_.Show("Karel's World"); } + + void Move() { + switch (orientation_) { + case Orientation::kNorth: + if (y_ == 0) { + // Cannot move any further. draw an error. + } else { + AnimateMove(x_, y_ - 1); + } + break; + case Orientation::kEast: + if (x_ == dimen - 1) { + } else { + AnimateMove(x_ + 1, y_); + } + break; + case Orientation::kSouth: + if (y_ == dimen - 1) { + } else { + AnimateMove(x_, y_ + 1); + } + break; + case Orientation::kWest: + if (x_ == 0) { + } else { + AnimateMove(x_ - 1, y_); + } + break; + } + } + + void TurnLeft() { + switch (orientation_) { + case Orientation::kNorth: + orientation_ = Orientation::kWest; + break; + case Orientation::kEast: + orientation_ = Orientation::kNorth; + break; + case Orientation::kSouth: + orientation_ = Orientation::kEast; + break; + case Orientation::kWest: + orientation_ = Orientation::kSouth; + break; + } + DrawWorld(); + DrawRobot(); + // todo make this 500 a param or refactor this line as a fn. + image_.ShowForMs(500, "Karel's World"); + } + + void Finish() { image_.ShowUntilClosed("Karel's World"); } + + private: + Robot() {} + + void DrawWorld() { + // TODO draw the beepers and cells + image_.DrawRectangle(0, 0, dimen * pxPerCell, dimen * pxPerCell, + graphics::Color(255, 255, 255)); + for (int i = 0; i < dimen; i++) { + for (int j = 0; j < dimen; j++) { + int x_center = i * pxPerCell + pxPerCell / 2; + int y_center = j * pxPerCell + pxPerCell / 2; + image_.DrawLine(x_center - robotSize / 2, y_center, + x_center + robotSize / 2, y_center, markColor, 3); + image_.DrawLine(x_center, y_center - robotSize / 2, x_center, + y_center + robotSize / 2, graphics::Color(0, 0, 255), + 3); + if (world_[i][j].GetNumBeepers() > 0) { + image_.DrawRectangle(x_center - beeperSize / 2, + y_center - beeperSize / 2, beeperSize, + beeperSize, beeperColor); + } + } + } + for (int i = 0; i < dimen; i++) { + image_.DrawLine(0, i * pxPerCell, 499, i * pxPerCell, + graphics::Color(200, 200, 200)); + image_.DrawLine(i * pxPerCell, 0, i * pxPerCell, 499, + graphics::Color(200, 200, 200)); + } + } + + void DrawRobot() { + DrawRobot(x_ * pxPerCell + robotSize / 2, y_ * pxPerCell + robotSize / 2); + } + + void DrawRobot(int pixel_x, int pixel_y) { + image_.DrawRectangle(pixel_x, pixel_y, robotSize, robotSize, karelColor); + image_.DrawCircle(pixel_x + robotSize / 2, pixel_y + robotSize / 2, eyeSize, + eyeColor); + switch (orientation_) { + case Orientation::kNorth: + image_.DrawCircle(pixel_x + robotSize / 2, pixel_y + 2, eyeSize, + eyeColor); + break; + case Orientation::kEast: + image_.DrawCircle(pixel_x + robotSize - 2, pixel_y + robotSize / 2, + eyeSize, eyeColor); + image_.DrawLine(pixel_x + robotSize / 2 - legLength, + pixel_y + robotSize, + pixel_x + robotSize / 2 - legLength, + pixel_y + robotSize + legLength, karelColor, 5); + image_.DrawLine(pixel_x + robotSize / 2 + legLength, + pixel_y + robotSize, + pixel_x + robotSize / 2 + legLength, + pixel_y + robotSize + legLength, karelColor, 5); + break; + case Orientation::kSouth: + image_.DrawCircle(pixel_x + robotSize / 2, pixel_y + robotSize - 2, + eyeSize, eyeColor); + break; + case Orientation::kWest: + image_.DrawCircle(pixel_x + 2, pixel_y + robotSize / 2, eyeSize, + eyeColor); + break; + } + } + + void AnimateMove(int next_x, int next_y) { + int steps = 10; + for (int i = 1; i <= steps; i++) { + DrawWorld(); + double fraction = i * 1.0 / steps; + double x = x_ * (1 - fraction) + next_x * fraction; + double y = y_ * (1 - fraction) + next_y * fraction; + DrawRobot(x * pxPerCell + robotSize / 2, y * pxPerCell + robotSize / 2); + image_.ShowForMs(60, "Karel's World"); + } + x_ = next_x; + y_ = next_y; + image_.ShowForMs(500, "Karel's World"); + } + + graphics::Image image_; + int x_ = 0; + int y_ = 9; + Orientation orientation_ = Orientation::kEast; + std::vector> world_; +}; + +} // namespace karel + +void Move() { + karel::Robot& r = karel::Robot::GetInstance(); + r.Move(); +} + +void TurnLeft() { + karel::Robot& r = karel::Robot::GetInstance(); + r.TurnLeft(); +} + +void PutBeeper() { karel::Robot& r = karel::Robot::GetInstance(); } + +void PickBeeper() { karel::Robot& r = karel::Robot::GetInstance(); } + +void Finish() { + karel::Robot& r = karel::Robot::GetInstance(); + r.Finish(); +} + +bool FrontIsClear() { + karel::Robot& r = karel::Robot::GetInstance(); + return false; +} + +bool BeepersPresent() { + karel::Robot& r = karel::Robot::GetInstance(); + return false; +} diff --git a/karel/karel.h b/karel/karel.h new file mode 100644 index 0000000..8ce271b --- /dev/null +++ b/karel/karel.h @@ -0,0 +1,22 @@ +#include "../graphics/image.h" +#include "../graphics/image_event.h" + +void Move(); + +void TurnLeft(); + +void PutBeeper(); + +void PickBeeper(); + +bool FrontIsClear(); + +bool BeepersPresent(); + +// Set-up for professors? +// https://csis.pace.edu/~bergin/KarelJava2ed/KJRdocs/kareltherobot/World.html +void SetDimensions(int width, int height); + +void PlaceBeeperAt(int x, int y); + +void Finish(); diff --git a/karel/test.cc b/karel/test.cc new file mode 100644 index 0000000..80be307 --- /dev/null +++ b/karel/test.cc @@ -0,0 +1,23 @@ +#include "karel.h" + +void KarelProgram() { + Move(); + Move(); + Move(); + TurnLeft(); + Move(); + Move(); + TurnLeft(); + // Move(); + // Move(); + // TurnLeft(); + // Move(); + // TurnLeft(); +} + +int main() { + //LoadFromFile("file.kar"); + KarelProgram(); + Finish(); + return 0; +} From b4f8b8add4d419cc286aafdaaff2b8a3442fa773 Mon Sep 17 00:00:00 2001 From: Katie Dektar Date: Tue, 24 Nov 2020 20:14:22 -0800 Subject: [PATCH 15/40] Draw karel and world more nicely --- karel/karel.cc | 108 +++++++++++++++++++++++++++++++++---------------- karel/test.cc | 10 ++--- 2 files changed, 77 insertions(+), 41 deletions(-) diff --git a/karel/karel.cc b/karel/karel.cc index e24169a..d1cf1be 100644 --- a/karel/karel.cc +++ b/karel/karel.cc @@ -2,6 +2,7 @@ #include #include +#include namespace karel { @@ -30,14 +31,18 @@ class Cell { const int dimen = 10; const int pxPerCell = 50; +const int markSize = 10; const int robotSize = 30; -const int beeperSize = 25; +const int beeperSize = 30; const int eyeSize = 4; -const int legLength = 4; +const int legLength = 6; +const int limbWidth = 5; const graphics::Color eyeColor(50, 50, 50); const graphics::Color karelColor(125, 125, 125); -const graphics::Color markColor(50, 50, 255); -const graphics::Color beeperColor(200, 0, 200); +const graphics::Color markColor(150, 150, 255); +const graphics::Color beeperColor(172, 147, 194); +const graphics::Color limbColor(105, 105, 105); +const graphics::Color kWhite(255, 255, 255); class Robot { public: @@ -63,7 +68,7 @@ class Robot { world_[5][3].SetNumBeepers(1); world_[2][7].SetNumBeepers(1); DrawWorld(); - DrawRobot(x_ * pxPerCell + robotSize / 2, y_ * pxPerCell + robotSize / 2); + DrawRobot(x_ * pxPerCell + pxPerCell / 2, y_ * pxPerCell + pxPerCell / 2); image_.ShowForMs(500, "Karel's World"); } @@ -126,23 +131,26 @@ class Robot { Robot() {} void DrawWorld() { - // TODO draw the beepers and cells - image_.DrawRectangle(0, 0, dimen * pxPerCell, dimen * pxPerCell, - graphics::Color(255, 255, 255)); + image_.DrawRectangle(0, 0, dimen * pxPerCell, dimen * pxPerCell, kWhite); for (int i = 0; i < dimen; i++) { for (int j = 0; j < dimen; j++) { int x_center = i * pxPerCell + pxPerCell / 2; int y_center = j * pxPerCell + pxPerCell / 2; - image_.DrawLine(x_center - robotSize / 2, y_center, - x_center + robotSize / 2, y_center, markColor, 3); - image_.DrawLine(x_center, y_center - robotSize / 2, x_center, - y_center + robotSize / 2, graphics::Color(0, 0, 255), - 3); + image_.DrawLine(x_center - markSize / 2, y_center, + x_center + markSize / 2, y_center, markColor, 3); + image_.DrawLine(x_center, y_center - markSize / 2, x_center, + y_center + markSize / 2, markColor, 3); + // trig! + double dimen = sqrt((beeperSize / 2) * (beeperSize / 2) / 2); if (world_[i][j].GetNumBeepers() > 0) { - image_.DrawRectangle(x_center - beeperSize / 2, - y_center - beeperSize / 2, beeperSize, - beeperSize, beeperColor); + image_.DrawLine(x_center - dimen, + y_center - dimen, x_center + dimen, y_center + dimen, + beeperColor, beeperSize); + image_.DrawLine(x_center - dimen, + y_center - dimen, x_center +dimen, y_center + dimen, + beeperColor, beeperSize); } + // TODO: Check for walls and draw them here in a thick darker grey. } } for (int i = 0; i < dimen; i++) { @@ -154,39 +162,69 @@ class Robot { } void DrawRobot() { - DrawRobot(x_ * pxPerCell + robotSize / 2, y_ * pxPerCell + robotSize / 2); + // Center in the cell. + DrawRobot(x_ * pxPerCell + pxPerCell / 2, y_ * pxPerCell + pxPerCell / 2); } + // pixel_x and pixel_y are the center of the cell in pixels. void DrawRobot(int pixel_x, int pixel_y) { - image_.DrawRectangle(pixel_x, pixel_y, robotSize, robotSize, karelColor); - image_.DrawCircle(pixel_x + robotSize / 2, pixel_y + robotSize / 2, eyeSize, - eyeColor); + image_.DrawRectangle(pixel_x - robotSize / 2, pixel_y - robotSize / 2, + robotSize, robotSize, karelColor); switch (orientation_) { case Orientation::kNorth: - image_.DrawCircle(pixel_x + robotSize / 2, pixel_y + 2, eyeSize, - eyeColor); + image_.DrawCircle(pixel_x, pixel_y - robotSize / 2 + eyeSize / 2 + 1, + eyeSize, kWhite); + image_.DrawCircle(pixel_x, pixel_y + 1, eyeSize, kWhite); + image_.DrawCircle(pixel_x, pixel_y - robotSize / 2 + eyeSize / 2, + eyeSize, eyeColor); + image_.DrawLine(pixel_x + robotSize / 2, pixel_y - legLength, + pixel_x + robotSize / 2 + legLength, + pixel_y - legLength, limbColor, limbWidth); + image_.DrawLine(pixel_x + robotSize / 2, pixel_y + legLength, + pixel_x + robotSize / 2 + legLength, + pixel_y + legLength, limbColor, limbWidth); break; case Orientation::kEast: - image_.DrawCircle(pixel_x + robotSize - 2, pixel_y + robotSize / 2, + image_.DrawCircle(pixel_x - 1, pixel_y, eyeSize, kWhite); + image_.DrawCircle(pixel_x + robotSize / 2 - eyeSize / 2 - 1, pixel_y, + eyeSize, kWhite); + image_.DrawCircle(pixel_x + robotSize / 2 - eyeSize / 2, pixel_y, eyeSize, eyeColor); - image_.DrawLine(pixel_x + robotSize / 2 - legLength, - pixel_y + robotSize, - pixel_x + robotSize / 2 - legLength, - pixel_y + robotSize + legLength, karelColor, 5); - image_.DrawLine(pixel_x + robotSize / 2 + legLength, - pixel_y + robotSize, - pixel_x + robotSize / 2 + legLength, - pixel_y + robotSize + legLength, karelColor, 5); + image_.DrawLine( + pixel_x - legLength, pixel_y + robotSize / 2, pixel_x - legLength, + pixel_y + robotSize / 2 + legLength, limbColor, limbWidth); + image_.DrawLine( + pixel_x + legLength, pixel_y + robotSize / 2, pixel_x + legLength, + pixel_y + robotSize / 2 + legLength, limbColor, limbWidth); break; case Orientation::kSouth: - image_.DrawCircle(pixel_x + robotSize / 2, pixel_y + robotSize - 2, + image_.DrawCircle(pixel_x, pixel_y + robotSize / 2 - eyeSize / 2 - 1, + eyeSize, kWhite); + image_.DrawCircle(pixel_x, pixel_y - 1, eyeSize, kWhite); + image_.DrawCircle(pixel_x, pixel_y + robotSize / 2 - eyeSize / 2, eyeSize, eyeColor); + image_.DrawLine(pixel_x - robotSize / 2, pixel_y - legLength, + pixel_x - robotSize / 2 - legLength, + pixel_y - legLength, limbColor, limbWidth); + image_.DrawLine(pixel_x - robotSize / 2, pixel_y + legLength, + pixel_x - robotSize / 2 - legLength, + pixel_y + legLength, limbColor, limbWidth); break; case Orientation::kWest: - image_.DrawCircle(pixel_x + 2, pixel_y + robotSize / 2, eyeSize, - eyeColor); + image_.DrawCircle(pixel_x + 1, pixel_y, eyeSize, kWhite); + image_.DrawCircle(pixel_x - robotSize / 2 + eyeSize / 2 + 1, pixel_y, + eyeSize, kWhite); + image_.DrawCircle(pixel_x - robotSize / 2 + eyeSize / 2, pixel_y, + eyeSize, eyeColor); + image_.DrawLine( + pixel_x - legLength, pixel_y - robotSize / 2, pixel_x - legLength, + pixel_y - robotSize / 2 - legLength, limbColor, limbWidth); + image_.DrawLine( + pixel_x + legLength, pixel_y - robotSize / 2, pixel_x + legLength, + pixel_y - robotSize / 2 - legLength, limbColor, limbWidth); break; } + image_.DrawCircle(pixel_x, pixel_y, eyeSize, eyeColor); } void AnimateMove(int next_x, int next_y) { @@ -196,7 +234,7 @@ class Robot { double fraction = i * 1.0 / steps; double x = x_ * (1 - fraction) + next_x * fraction; double y = y_ * (1 - fraction) + next_y * fraction; - DrawRobot(x * pxPerCell + robotSize / 2, y * pxPerCell + robotSize / 2); + DrawRobot(x * pxPerCell + pxPerCell / 2, y * pxPerCell + pxPerCell / 2); image_.ShowForMs(60, "Karel's World"); } x_ = next_x; diff --git a/karel/test.cc b/karel/test.cc index 80be307..67d005f 100644 --- a/karel/test.cc +++ b/karel/test.cc @@ -1,18 +1,16 @@ #include "karel.h" void KarelProgram() { - Move(); Move(); Move(); TurnLeft(); Move(); Move(); TurnLeft(); - // Move(); - // Move(); - // TurnLeft(); - // Move(); - // TurnLeft(); + Move(); + TurnLeft(); + Move(); + //TurnLeft(); } int main() { From a60d5d2677b0ed307873a20aab1cb38e9ab4d8c4 Mon Sep 17 00:00:00 2001 From: Katie Dektar Date: Tue, 24 Nov 2020 21:12:05 -0800 Subject: [PATCH 16/40] pick and put beepers --- karel/karel.cc | 65 +++++++++++++++++++++++++++++++++++++------------- karel/karel.h | 2 +- karel/test.cc | 6 ++++- 3 files changed, 55 insertions(+), 18 deletions(-) diff --git a/karel/karel.cc b/karel/karel.cc index d1cf1be..cf6fd1d 100644 --- a/karel/karel.cc +++ b/karel/karel.cc @@ -1,16 +1,17 @@ #include "karel.h" +#include + #include #include -#include namespace karel { enum Orientation { - kNorth, - kEast, - kSouth, - kWest, + kNorth = 1, + kEast = 2, + kSouth = 3, + kWest = 4, }; class Cell { @@ -49,7 +50,6 @@ class Robot { static karel::Robot& GetInstance() { static Robot instance; instance.Initialize(); - instance.Show(); return instance; } @@ -58,6 +58,8 @@ class Robot { karel::Robot& operator=(const Robot&) = delete; void Initialize() { + if (initialized_) return; + initialized_ = true; image_.Initialize(dimen * pxPerCell, dimen * pxPerCell); for (int i = 0; i < dimen; i++) { world_.push_back(std::vector()); @@ -125,6 +127,33 @@ class Robot { image_.ShowForMs(500, "Karel's World"); } + void PutBeeper() { + if (!HasBeepersInBag()) { + // TODO error + return; + } + beeper_count_--; + world_[x_][y_].SetNumBeepers(world_[x_][y_].GetNumBeepers() + 1); + DrawWorld(); + DrawRobot(); + image_.ShowForMs(500, "Karel's World"); + } + + void PickBeeper() { + int count = world_[x_][y_].GetNumBeepers(); + if (count < 1) { + // TODO error + return; + } + world_[x_][y_].SetNumBeepers(count - 1); + beeper_count_++; + DrawWorld(); + DrawRobot(); + image_.ShowForMs(500, "Karel's World"); + } + + bool HasBeepersInBag() { return beeper_count_ > 0; } + void Finish() { image_.ShowUntilClosed("Karel's World"); } private: @@ -143,12 +172,8 @@ class Robot { // trig! double dimen = sqrt((beeperSize / 2) * (beeperSize / 2) / 2); if (world_[i][j].GetNumBeepers() > 0) { - image_.DrawLine(x_center - dimen, - y_center - dimen, x_center + dimen, y_center + dimen, - beeperColor, beeperSize); - image_.DrawLine(x_center - dimen, - y_center - dimen, x_center +dimen, y_center + dimen, - beeperColor, beeperSize); + image_.DrawLine(x_center - dimen, y_center - dimen, x_center + dimen, + y_center + dimen, beeperColor, beeperSize); } // TODO: Check for walls and draw them here in a thick darker grey. } @@ -246,7 +271,9 @@ class Robot { int x_ = 0; int y_ = 9; Orientation orientation_ = Orientation::kEast; + int beeper_count_ = 0; std::vector> world_; + bool initialized_ = false; }; } // namespace karel @@ -261,9 +288,15 @@ void TurnLeft() { r.TurnLeft(); } -void PutBeeper() { karel::Robot& r = karel::Robot::GetInstance(); } +void PutBeeper() { + karel::Robot& r = karel::Robot::GetInstance(); + r.PutBeeper(); +} -void PickBeeper() { karel::Robot& r = karel::Robot::GetInstance(); } +void PickBeeper() { + karel::Robot& r = karel::Robot::GetInstance(); + r.PickBeeper(); +} void Finish() { karel::Robot& r = karel::Robot::GetInstance(); @@ -275,7 +308,7 @@ bool FrontIsClear() { return false; } -bool BeepersPresent() { +bool HasBeepersInBag() { karel::Robot& r = karel::Robot::GetInstance(); - return false; + return r.HasBeepersInBag(); } diff --git a/karel/karel.h b/karel/karel.h index 8ce271b..9ec941c 100644 --- a/karel/karel.h +++ b/karel/karel.h @@ -11,7 +11,7 @@ void PickBeeper(); bool FrontIsClear(); -bool BeepersPresent(); +bool HasBeepersInBag(); // Set-up for professors? // https://csis.pace.edu/~bergin/KarelJava2ed/KJRdocs/kareltherobot/World.html diff --git a/karel/test.cc b/karel/test.cc index 67d005f..7439fee 100644 --- a/karel/test.cc +++ b/karel/test.cc @@ -6,11 +6,15 @@ void KarelProgram() { TurnLeft(); Move(); Move(); + PickBeeper(); + Move(); + PutBeeper(); + PickBeeper(); TurnLeft(); Move(); + PutBeeper(); TurnLeft(); Move(); - //TurnLeft(); } int main() { From b065603806643a257ed5192b7576cf3552be7d94 Mon Sep 17 00:00:00 2001 From: Katie Dektar Date: Thu, 3 Dec 2020 13:41:17 -0800 Subject: [PATCH 17/40] Beginning file loading --- karel/karel.cc | 217 ++++++++++++++++++++++----- karel/karel.h | 2 + karel/test.cc | 30 ++-- karel/worlds/1x8.w | 4 + karel/worlds/8x1.w | 4 + karel/worlds/8x8.w | 4 + karel/worlds/CollectNewspaperKarel.w | 15 ++ 7 files changed, 221 insertions(+), 55 deletions(-) create mode 100644 karel/worlds/1x8.w create mode 100644 karel/worlds/8x1.w create mode 100644 karel/worlds/8x8.w create mode 100644 karel/worlds/CollectNewspaperKarel.w diff --git a/karel/karel.cc b/karel/karel.cc index cf6fd1d..c273a03 100644 --- a/karel/karel.cc +++ b/karel/karel.cc @@ -2,7 +2,9 @@ #include +#include #include +#include #include namespace karel { @@ -16,21 +18,32 @@ enum Orientation { class Cell { public: - int GetNumBeepers() { return num_beepers_; } + int GetNumBeepers() const { return num_beepers_; } void SetNumBeepers(int beepers) { num_beepers_ = beepers; } - // bool HasNorthWall() { return north_wall_; } - // bool HasSouthWall() { return south_wall_; } - // bool HasSouthWall() { return south_wall_; } - // bool HasWestWall() { return west_wall_; } + bool HasNorthWall() const { return north_wall_; } + bool HasEastWall() const { return south_wall_; } + bool HasSouthWall() const { return south_wall_; } + bool HasWestWall() const { return west_wall_; } + void SetHasNorthWall(bool has_wall) { north_wall_ = has_wall; } + void SetHasEastWall(bool has_wall) { south_wall_ = has_wall; } + void SetHasSouthWall(bool has_wall) { south_wall_ = has_wall; } + void SetHasWestWall(bool has_wall) { west_wall_ = has_wall; } + private: bool num_beepers_ = 0; - // bool north_wall_ = false; - // bool east_wall_ = false; - // bool south_wall_ = false; - // bool west_wall_ = false; + bool north_wall_ = false; + bool east_wall_ = false; + bool south_wall_ = false; + bool west_wall_ = false; }; -const int dimen = 10; +// ms for a long animation duration to show Karel. +const int kLongDuration = 500; + +// ms for a short animation duration to show Karel. +const int kShortDuration = 50; + +const int kDefaultDimen = 10; const int pxPerCell = 50; const int markSize = 10; const int robotSize = 30; @@ -47,9 +60,22 @@ const graphics::Color kWhite(255, 255, 255); class Robot { public: - static karel::Robot& GetInstance() { + // Get the Robot singleton. + + static karel::Robot& PrivateGetInstance() { static Robot instance; - instance.Initialize(); + return instance; + } + + static karel::Robot& GetInstance() { + karel::Robot& instance = PrivateGetInstance(); + instance.Initialize(""); + return instance; + } + + static karel::Robot& InitializeInstance(std::string filename) { + karel::Robot& instance = PrivateGetInstance(); + instance.Initialize(filename); return instance; } @@ -57,24 +83,123 @@ class Robot { Robot(const Robot&) = delete; karel::Robot& operator=(const Robot&) = delete; - void Initialize() { + void Initialize(std::string filename) { + // Ensure only intitialized once. if (initialized_) return; initialized_ = true; - image_.Initialize(dimen * pxPerCell, dimen * pxPerCell); - for (int i = 0; i < dimen; i++) { - world_.push_back(std::vector()); - for (int j = 0; j < dimen; j++) { - world_[i].push_back(Cell()); + + if (!filename.size()) { + // No file. Default 10x10 blank world with no walls and no beepers. + x_dimen_ = kDefaultDimen; + y_dimen_ = kDefaultDimen; + for (int i = 0; i < x_dimen_; i++) { + world_.push_back(std::vector()); + for (int j = 0; j < y_dimen_; j++) { + world_[i].push_back(Cell()); + } + } + // Nearly infinite beepers. + beeper_count_ = std::numeric_limits::max(); + x_ = 0; + y_ = y_dimen_ - 1; + } else { + std::fstream world_file; + world_file.open(filename); + if (!world_file.is_open()) { + // TODO: Replace throwables with better error codes? + throw std::string("Error opening file " + filename); + } + std::string line; + + const std::string dimension_prefix = "Dimension:"; + const std::string beeper_prefix = "Beeper:"; + const std::string wall_prefix = "Wall:"; + const std::string bag_prefix = "BeeperBag:"; + const std::string karel_prefix = "Karel:"; + const std::string speed_prefix = "Speed:"; + + std::string line_prefix; + char open_paren, comma, closed_paren; + if (!(world_file >> line_prefix >> open_paren >> x_dimen_ >> comma >> + y_dimen_ >> closed_paren)) { + throw std::string("Could not find Dimension in first line"); + } + if (line_prefix != dimension_prefix) { + throw std::string("Could not find Dimension in first line"); } + for (int i = 0; i < x_dimen_; i++) { + world_.push_back(std::vector()); + for (int j = 0; j < y_dimen_; j++) { + world_[i].push_back(Cell()); + } + } + + // Read the rest of the file to get beepers and walls. + // May need better error checking. + while (world_file >> line_prefix) { + if (line_prefix == wall_prefix) { + std::cout << "wall " << std::endl; + } else if (line_prefix == beeper_prefix) { + // TODO + std::cout << "beeper in cell " << std::endl; + } else if (line_prefix == bag_prefix) { + std::string beepers; + world_file >> beepers; + if (beepers == "INFINITY") { + beeper_count_ = std::numeric_limits::max(); + } else { + beeper_count_ = stoi(beepers); + } + std::cout << "num beepers set to " << beeper_count_; + } else if (line_prefix == karel_prefix) { + std::cout << "karel_prefix " << std::endl; + + // set x, y and direction + } else if (line_prefix == speed_prefix) { + world_file >> speed_; + std::cout << "Speed set to " << speed_; + } else { + std::cout << "Default?? " << line_prefix << std::endl; + break; + } + } + + // if (!getline(world_file, line)) { + // throw std::string("File " + filename + " is empty."); + // } + // size_t dimension_index = line.find(dimension_prefix); + // if (dimension_index != std::string::npos) { + // std::string dimension_suffix = line.substr(dimension_prefix.size()); + // + // } else { + // // Error: first line should be dimension. + // throw std::string("Could not find Dimension in first line"); + // } + + // example worlds: + // https://github.com/thisdotrob/karel-the-robot/tree/master/worlds + + // get walls and beepers from file (optional in file) + + // karel initial state + x_ = 2; // from file but map x + y and dimen_ - y + y_ = y_dimen_ - 3; + + // get speed from file too. + speed_ = 1.25; + world_file.close(); } - world_[5][3].SetNumBeepers(1); - world_[2][7].SetNumBeepers(1); + + image_.Initialize(x_dimen_ * pxPerCell, y_dimen_ * pxPerCell); + DrawWorld(); DrawRobot(x_ * pxPerCell + pxPerCell / 2, y_ * pxPerCell + pxPerCell / 2); - image_.ShowForMs(500, "Karel's World"); + Show(kLongDuration); } - void Show() { image_.Show("Karel's World"); } + void Show(int duration) { + image_.ShowForMs(duration / speed_, "Karel's World"); + } void Move() { switch (orientation_) { @@ -86,13 +211,13 @@ class Robot { } break; case Orientation::kEast: - if (x_ == dimen - 1) { + if (x_ == x_dimen_ - 1) { } else { AnimateMove(x_ + 1, y_); } break; case Orientation::kSouth: - if (y_ == dimen - 1) { + if (y_ == y_dimen_ - 1) { } else { AnimateMove(x_, y_ + 1); } @@ -123,8 +248,7 @@ class Robot { } DrawWorld(); DrawRobot(); - // todo make this 500 a param or refactor this line as a fn. - image_.ShowForMs(500, "Karel's World"); + Show(kLongDuration); } void PutBeeper() { @@ -136,7 +260,7 @@ class Robot { world_[x_][y_].SetNumBeepers(world_[x_][y_].GetNumBeepers() + 1); DrawWorld(); DrawRobot(); - image_.ShowForMs(500, "Karel's World"); + Show(kLongDuration); } void PickBeeper() { @@ -149,7 +273,7 @@ class Robot { beeper_count_++; DrawWorld(); DrawRobot(); - image_.ShowForMs(500, "Karel's World"); + Show(kLongDuration); } bool HasBeepersInBag() { return beeper_count_ > 0; } @@ -160,9 +284,10 @@ class Robot { Robot() {} void DrawWorld() { - image_.DrawRectangle(0, 0, dimen * pxPerCell, dimen * pxPerCell, kWhite); - for (int i = 0; i < dimen; i++) { - for (int j = 0; j < dimen; j++) { + image_.DrawRectangle(0, 0, x_dimen_ * pxPerCell, y_dimen_ * pxPerCell, + kWhite); + for (int i = 0; i < x_dimen_; i++) { + for (int j = 0; j < y_dimen_; j++) { int x_center = i * pxPerCell + pxPerCell / 2; int y_center = j * pxPerCell + pxPerCell / 2; image_.DrawLine(x_center - markSize / 2, y_center, @@ -170,18 +295,23 @@ class Robot { image_.DrawLine(x_center, y_center - markSize / 2, x_center, y_center + markSize / 2, markColor, 3); // trig! - double dimen = sqrt((beeperSize / 2) * (beeperSize / 2) / 2); + double line_size = sqrt((beeperSize / 2) * (beeperSize / 2) / 2); if (world_[i][j].GetNumBeepers() > 0) { - image_.DrawLine(x_center - dimen, y_center - dimen, x_center + dimen, - y_center + dimen, beeperColor, beeperSize); + image_.DrawLine(x_center - line_size, y_center - line_size, + x_center + line_size, y_center + line_size, + beeperColor, beeperSize); } // TODO: Check for walls and draw them here in a thick darker grey. } } - for (int i = 0; i < dimen; i++) { - image_.DrawLine(0, i * pxPerCell, 499, i * pxPerCell, + for (int i = 0; i < y_dimen_; i++) { + // Draw horizontal lines. + image_.DrawLine(0, i * pxPerCell, pxPerCell * x_dimen_ - 1, i * pxPerCell, graphics::Color(200, 200, 200)); - image_.DrawLine(i * pxPerCell, 0, i * pxPerCell, 499, + } + for (int i = 0; i < x_dimen_; i++) { + // Draw vertical lines. + image_.DrawLine(i * pxPerCell, 0, i * pxPerCell, pxPerCell * y_dimen_ - 1, graphics::Color(200, 200, 200)); } } @@ -260,24 +390,31 @@ class Robot { double x = x_ * (1 - fraction) + next_x * fraction; double y = y_ * (1 - fraction) + next_y * fraction; DrawRobot(x * pxPerCell + pxPerCell / 2, y * pxPerCell + pxPerCell / 2); - image_.ShowForMs(60, "Karel's World"); + Show(kShortDuration); } x_ = next_x; y_ = next_y; - image_.ShowForMs(500, "Karel's World"); + Show(kLongDuration); } graphics::Image image_; + int x_dimen_ = kDefaultDimen; + int y_dimen_ = kDefaultDimen; int x_ = 0; - int y_ = 9; + int y_ = y_dimen_ - 1; Orientation orientation_ = Orientation::kEast; int beeper_count_ = 0; std::vector> world_; bool initialized_ = false; + double speed_ = 1.0; }; } // namespace karel +void LoadWorld(std::string filename) { + karel::Robot& r = karel::Robot::InitializeInstance(filename); +} + void Move() { karel::Robot& r = karel::Robot::GetInstance(); r.Move(); diff --git a/karel/karel.h b/karel/karel.h index 9ec941c..fa96ee6 100644 --- a/karel/karel.h +++ b/karel/karel.h @@ -20,3 +20,5 @@ void SetDimensions(int width, int height); void PlaceBeeperAt(int x, int y); void Finish(); + +void LoadWorld(std::string filename); diff --git a/karel/test.cc b/karel/test.cc index 7439fee..d5c8493 100644 --- a/karel/test.cc +++ b/karel/test.cc @@ -1,24 +1,24 @@ #include "karel.h" void KarelProgram() { - Move(); - Move(); - TurnLeft(); - Move(); - Move(); - PickBeeper(); - Move(); - PutBeeper(); - PickBeeper(); - TurnLeft(); - Move(); - PutBeeper(); - TurnLeft(); - Move(); + // Move(); + // Move(); + // TurnLeft(); + // Move(); + // Move(); + // PickBeeper(); + // Move(); + // PutBeeper(); + // PickBeeper(); + // TurnLeft(); + // Move(); + // PutBeeper(); + // TurnLeft(); + // Move(); } int main() { - //LoadFromFile("file.kar"); + LoadWorld("worlds/8x1.w"); KarelProgram(); Finish(); return 0; diff --git a/karel/worlds/1x8.w b/karel/worlds/1x8.w new file mode 100644 index 0000000..052a28a --- /dev/null +++ b/karel/worlds/1x8.w @@ -0,0 +1,4 @@ +Dimension: (1, 8) +BeeperBag: INFINITY +Karel: (1, 1) East +Speed: 0.75 diff --git a/karel/worlds/8x1.w b/karel/worlds/8x1.w new file mode 100644 index 0000000..b3c4412 --- /dev/null +++ b/karel/worlds/8x1.w @@ -0,0 +1,4 @@ +Dimension: (8, 1) +BeeperBag: INFINITY +Karel: (1, 1) East +Speed: 0.75 diff --git a/karel/worlds/8x8.w b/karel/worlds/8x8.w new file mode 100644 index 0000000..fe36721 --- /dev/null +++ b/karel/worlds/8x8.w @@ -0,0 +1,4 @@ +Dimension: (8, 8) +BeeperBag: INFINITY +Karel: (1, 1) East +Speed: 0.75 diff --git a/karel/worlds/CollectNewspaperKarel.w b/karel/worlds/CollectNewspaperKarel.w new file mode 100644 index 0000000..ddc1e1d --- /dev/null +++ b/karel/worlds/CollectNewspaperKarel.w @@ -0,0 +1,15 @@ +Dimension: (7, 5) +Wall: (3, 2) west +Wall: (3, 2) south +Wall: (3, 3) west +Wall: (3, 4) west +Wall: (3, 5) south +Wall: (4, 2) south +Wall: (4, 5) south +Wall: (5, 2) south +Wall: (5, 5) south +Wall: (6, 2) west +Wall: (6, 4) west +Beeper: (6, 3) 1 +Karel: (3, 4) east +Speed: 0.00 From b2ecddedfb74a7645c3f43e8e119591bb6dc8dd0 Mon Sep 17 00:00:00 2001 From: Katie Dektar Date: Thu, 3 Dec 2020 14:24:41 -0800 Subject: [PATCH 18/40] Can load some worlds --- karel/karel.cc | 198 +++++++++++++++++++-------------- karel/test.cc | 4 +- karel/worlds/StoneMasonKarel.w | 39 +++++++ 3 files changed, 158 insertions(+), 83 deletions(-) create mode 100644 karel/worlds/StoneMasonKarel.w diff --git a/karel/karel.cc b/karel/karel.cc index c273a03..5559643 100644 --- a/karel/karel.cc +++ b/karel/karel.cc @@ -16,6 +16,12 @@ enum Orientation { kWest = 4, }; +struct PositionAndOrientation { + int x = 0; + int y = 0; + Orientation orientation = Orientation::kNorth; +}; + class Cell { public: int GetNumBeepers() const { return num_beepers_; } @@ -24,10 +30,22 @@ class Cell { bool HasEastWall() const { return south_wall_; } bool HasSouthWall() const { return south_wall_; } bool HasWestWall() const { return west_wall_; } - void SetHasNorthWall(bool has_wall) { north_wall_ = has_wall; } - void SetHasEastWall(bool has_wall) { south_wall_ = has_wall; } - void SetHasSouthWall(bool has_wall) { south_wall_ = has_wall; } - void SetHasWestWall(bool has_wall) { west_wall_ = has_wall; } + void AddWall(Orientation wall_orientation) { + switch (wall_orientation) { + case kNorth: + north_wall_ = true; + break; + case kEast: + east_wall_ = true; + break; + case kSouth: + south_wall_ = true; + break; + case kWest: + west_wall_ = true; + break; + } + } private: bool num_beepers_ = 0; @@ -51,12 +69,14 @@ const int beeperSize = 30; const int eyeSize = 4; const int legLength = 6; const int limbWidth = 5; +const int kWallThickness = 3; const graphics::Color eyeColor(50, 50, 50); const graphics::Color karelColor(125, 125, 125); const graphics::Color markColor(150, 150, 255); const graphics::Color beeperColor(172, 147, 194); const graphics::Color limbColor(105, 105, 105); const graphics::Color kWhite(255, 255, 255); +const graphics::Color kWallColor(125, 125, 125); class Robot { public: @@ -100,8 +120,8 @@ class Robot { } // Nearly infinite beepers. beeper_count_ = std::numeric_limits::max(); - x_ = 0; - y_ = y_dimen_ - 1; + position_.x = 0; + position_.y = y_dimen_ - 1; } else { std::fstream world_file; world_file.open(filename); @@ -135,13 +155,15 @@ class Robot { } // Read the rest of the file to get beepers and walls. - // May need better error checking. + // TODO: May need better error checking. while (world_file >> line_prefix) { if (line_prefix == wall_prefix) { - std::cout << "wall " << std::endl; + PositionAndOrientation wall = ParsePositionAndOrientation(world_file); + world_[wall.x][wall.y].AddWall(wall.orientation); } else if (line_prefix == beeper_prefix) { - // TODO - std::cout << "beeper in cell " << std::endl; + int x, y, count; + world_file >> open_paren >> x >> comma >> y >> closed_paren >> count; + world_[x][y].SetNumBeepers(count); } else if (line_prefix == bag_prefix) { std::string beepers; world_file >> beepers; @@ -150,50 +172,22 @@ class Robot { } else { beeper_count_ = stoi(beepers); } - std::cout << "num beepers set to " << beeper_count_; } else if (line_prefix == karel_prefix) { - std::cout << "karel_prefix " << std::endl; - - // set x, y and direction + position_ = ParsePositionAndOrientation(world_file); } else if (line_prefix == speed_prefix) { - world_file >> speed_; - std::cout << "Speed set to " << speed_; + world_file >> speed_; } else { - std::cout << "Default?? " << line_prefix << std::endl; - break; + std::cout << "unexpected token in file: " << line_prefix << std::endl; + break; } } - - // if (!getline(world_file, line)) { - // throw std::string("File " + filename + " is empty."); - // } - // size_t dimension_index = line.find(dimension_prefix); - // if (dimension_index != std::string::npos) { - // std::string dimension_suffix = line.substr(dimension_prefix.size()); - // - // } else { - // // Error: first line should be dimension. - // throw std::string("Could not find Dimension in first line"); - // } - - // example worlds: - // https://github.com/thisdotrob/karel-the-robot/tree/master/worlds - - // get walls and beepers from file (optional in file) - - // karel initial state - x_ = 2; // from file but map x + y and dimen_ - y - y_ = y_dimen_ - 3; - - // get speed from file too. - speed_ = 1.25; world_file.close(); } - image_.Initialize(x_dimen_ * pxPerCell, y_dimen_ * pxPerCell); DrawWorld(); - DrawRobot(x_ * pxPerCell + pxPerCell / 2, y_ * pxPerCell + pxPerCell / 2); + DrawRobot(position_.x * pxPerCell + pxPerCell / 2, + position_.y * pxPerCell + pxPerCell / 2); Show(kLongDuration); } @@ -202,48 +196,48 @@ class Robot { } void Move() { - switch (orientation_) { + switch (position_.orientation) { case Orientation::kNorth: - if (y_ == 0) { + if (position_.y == 0) { // Cannot move any further. draw an error. } else { - AnimateMove(x_, y_ - 1); + AnimateMove(position_.x, position_.y - 1); } break; case Orientation::kEast: - if (x_ == x_dimen_ - 1) { + if (position_.x == x_dimen_ - 1) { } else { - AnimateMove(x_ + 1, y_); + AnimateMove(position_.x + 1, position_.y); } break; case Orientation::kSouth: - if (y_ == y_dimen_ - 1) { + if (position_.y == y_dimen_ - 1) { } else { - AnimateMove(x_, y_ + 1); + AnimateMove(position_.x, position_.y + 1); } break; case Orientation::kWest: - if (x_ == 0) { + if (position_.x == 0) { } else { - AnimateMove(x_ - 1, y_); + AnimateMove(position_.x - 1, position_.y); } break; } } void TurnLeft() { - switch (orientation_) { + switch (position_.orientation) { case Orientation::kNorth: - orientation_ = Orientation::kWest; + position_.orientation = Orientation::kWest; break; case Orientation::kEast: - orientation_ = Orientation::kNorth; + position_.orientation = Orientation::kNorth; break; case Orientation::kSouth: - orientation_ = Orientation::kEast; + position_.orientation = Orientation::kEast; break; case Orientation::kWest: - orientation_ = Orientation::kSouth; + position_.orientation = Orientation::kSouth; break; } DrawWorld(); @@ -257,19 +251,20 @@ class Robot { return; } beeper_count_--; - world_[x_][y_].SetNumBeepers(world_[x_][y_].GetNumBeepers() + 1); + world_[position_.x][position_.y].SetNumBeepers( + world_[position_.x][position_.y].GetNumBeepers() + 1); DrawWorld(); DrawRobot(); Show(kLongDuration); } void PickBeeper() { - int count = world_[x_][y_].GetNumBeepers(); + int count = world_[position_.x][position_.y].GetNumBeepers(); if (count < 1) { // TODO error return; } - world_[x_][y_].SetNumBeepers(count - 1); + world_[position_.x][position_.y].SetNumBeepers(count - 1); beeper_count_++; DrawWorld(); DrawRobot(); @@ -286,46 +281,60 @@ class Robot { void DrawWorld() { image_.DrawRectangle(0, 0, x_dimen_ * pxPerCell, y_dimen_ * pxPerCell, kWhite); + for (int i = 0; i < y_dimen_; i++) { + // Draw horizontal lines. + image_.DrawLine(0, i * pxPerCell, pxPerCell * x_dimen_ - 1, i * pxPerCell, + graphics::Color(200, 200, 200)); + } + for (int i = 0; i < x_dimen_; i++) { + // Draw vertical lines. + image_.DrawLine(i * pxPerCell, 0, i * pxPerCell, pxPerCell * y_dimen_ - 1, + graphics::Color(200, 200, 200)); + } for (int i = 0; i < x_dimen_; i++) { for (int j = 0; j < y_dimen_; j++) { int x_center = i * pxPerCell + pxPerCell / 2; int y_center = j * pxPerCell + pxPerCell / 2; + // Draw the little plus at the center of the cell. image_.DrawLine(x_center - markSize / 2, y_center, x_center + markSize / 2, y_center, markColor, 3); image_.DrawLine(x_center, y_center - markSize / 2, x_center, y_center + markSize / 2, markColor, 3); // trig! double line_size = sqrt((beeperSize / 2) * (beeperSize / 2) / 2); - if (world_[i][j].GetNumBeepers() > 0) { + Cell& cell = world_[i][j]; + if (cell.GetNumBeepers() > 0) { + // Draw the beepers. Beepers are stacked so you can't tell if there's + // more than one in a stack. image_.DrawLine(x_center - line_size, y_center - line_size, x_center + line_size, y_center + line_size, beeperColor, beeperSize); } - // TODO: Check for walls and draw them here in a thick darker grey. + // Draw the walls. + if (cell.HasNorthWall()) { + image_.DrawLine(i * pxPerCell, j * pxPerCell, (i + 1) * pxPerCell, j * pxPerCell, kWallColor, kWallThickness); + } else if (cell.HasSouthWall()) { + image_.DrawLine(i * pxPerCell, (j + 1) * pxPerCell, (i + 1) * pxPerCell, (j + 1) * pxPerCell, kWallColor, kWallThickness); + } else if (cell.HasWestWall()) { + image_.DrawLine(i * pxPerCell, j * pxPerCell, i * pxPerCell, (j + 1) * pxPerCell, kWallColor, kWallThickness); + } else if (cell.HasEastWall()) { + image_.DrawLine((i + 1) * pxPerCell, j * pxPerCell, (i + 1) * pxPerCell, (j + 1) * pxPerCell, kWallColor, kWallThickness); + } } } - for (int i = 0; i < y_dimen_; i++) { - // Draw horizontal lines. - image_.DrawLine(0, i * pxPerCell, pxPerCell * x_dimen_ - 1, i * pxPerCell, - graphics::Color(200, 200, 200)); - } - for (int i = 0; i < x_dimen_; i++) { - // Draw vertical lines. - image_.DrawLine(i * pxPerCell, 0, i * pxPerCell, pxPerCell * y_dimen_ - 1, - graphics::Color(200, 200, 200)); - } } void DrawRobot() { // Center in the cell. - DrawRobot(x_ * pxPerCell + pxPerCell / 2, y_ * pxPerCell + pxPerCell / 2); + DrawRobot(position_.x * pxPerCell + pxPerCell / 2, + position_.y * pxPerCell + pxPerCell / 2); } // pixel_x and pixel_y are the center of the cell in pixels. void DrawRobot(int pixel_x, int pixel_y) { image_.DrawRectangle(pixel_x - robotSize / 2, pixel_y - robotSize / 2, robotSize, robotSize, karelColor); - switch (orientation_) { + switch (position_.orientation) { case Orientation::kNorth: image_.DrawCircle(pixel_x, pixel_y - robotSize / 2 + eyeSize / 2 + 1, eyeSize, kWhite); @@ -387,22 +396,47 @@ class Robot { for (int i = 1; i <= steps; i++) { DrawWorld(); double fraction = i * 1.0 / steps; - double x = x_ * (1 - fraction) + next_x * fraction; - double y = y_ * (1 - fraction) + next_y * fraction; + double x = position_.x * (1 - fraction) + next_x * fraction; + double y = position_.y * (1 - fraction) + next_y * fraction; DrawRobot(x * pxPerCell + pxPerCell / 2, y * pxPerCell + pxPerCell / 2); Show(kShortDuration); } - x_ = next_x; - y_ = next_y; + position_.x = next_x; + position_.y = next_y; Show(kLongDuration); } + PositionAndOrientation ParsePositionAndOrientation(std::fstream& file) { + std::string direction; + char open_paren, comma, closed_paren; + int x, y; + file >> open_paren >> x >> comma >> y >> closed_paren >> direction; + // Convert y in the file to y on-screen. In the file, (1, 1) is the + // bottom left corner. + // In Karel coordinates, that's (0, y_dimen - 1). + PositionAndOrientation result; + result.y = y_dimen_ - y; + result.x = x - 1; + // Ensure the first character is lower cased. + direction[0] = tolower(direction[0]); + if (direction == "north") { + result.orientation = Orientation::kNorth; + } else if (direction == "east") { + result.orientation = Orientation::kEast; + } else if (direction == "south") { + result.orientation = Orientation::kSouth; + } else if (direction == "west") { + result.orientation = Orientation::kWest; + } else { + throw std::string("Unknown direction " + direction); + } + return result; + } + graphics::Image image_; int x_dimen_ = kDefaultDimen; int y_dimen_ = kDefaultDimen; - int x_ = 0; - int y_ = y_dimen_ - 1; - Orientation orientation_ = Orientation::kEast; + PositionAndOrientation position_ = {0, y_dimen_ - 1, Orientation::kEast}; int beeper_count_ = 0; std::vector> world_; bool initialized_ = false; diff --git a/karel/test.cc b/karel/test.cc index d5c8493..a61450f 100644 --- a/karel/test.cc +++ b/karel/test.cc @@ -18,7 +18,9 @@ void KarelProgram() { } int main() { - LoadWorld("worlds/8x1.w"); + LoadWorld("worlds/CollectNewspaperKarel.w"); + // LoadWorld("worlds/8x8.w"); + //LoadWorld("worlds/StoneMasonKarel.w"); KarelProgram(); Finish(); return 0; diff --git a/karel/worlds/StoneMasonKarel.w b/karel/worlds/StoneMasonKarel.w new file mode 100644 index 0000000..6def864 --- /dev/null +++ b/karel/worlds/StoneMasonKarel.w @@ -0,0 +1,39 @@ +Dimension: (13, 13) +Beeper: (1, 4) 1 +Beeper: (1, 5) 1 +Wall: (1, 6) South +Wall: (2, 6) West +Wall: (2, 7) South +Wall: (3, 7) West +Wall: (3, 8) South +Wall: (4, 7) West +Wall: (4, 7) South +Beeper: (5, 1) 1 +Beeper: (5, 2) 1 +Beeper: (5, 4) 1 +Wall: (5, 6) West +Wall: (5, 6) South +Wall: (6, 6) West +Wall: (6, 7) South +Wall: (7, 7) West +Wall: (7, 8) South +Wall: (8, 7) West +Wall: (8, 7) South +Beeper: (9, 3) 1 +Beeper: (9, 5) 1 +Wall: (9, 6) West +Wall: (9, 6) South +Wall: (10, 6) West +Wall: (10, 7) South +Wall: (11, 7) West +Wall: (11, 8) South +Wall: (12, 7) West +Wall: (12, 7) South +Beeper: (13, 1) 1 +Beeper: (13, 3) 1 +Beeper: (13, 5) 1 +Wall: (13, 6) West +Wall: (13, 6) South +BeeperBag: INFINITE +Karel: (1, 1) East +Speed: 0.5 From 6d270d0729fc74ff91812cd1acf9acfed72a8984 Mon Sep 17 00:00:00 2001 From: Katie Dektar Date: Thu, 3 Dec 2020 15:21:00 -0800 Subject: [PATCH 19/40] Complete loading worlds --- karel/karel.cc | 74 +++++++++++++++++++++++++++++++++------------- karel/test.cc | 4 +-- karel/worlds/8x8.w | 4 +++ 3 files changed, 59 insertions(+), 23 deletions(-) diff --git a/karel/karel.cc b/karel/karel.cc index 5559643..ef327c8 100644 --- a/karel/karel.cc +++ b/karel/karel.cc @@ -27,7 +27,7 @@ class Cell { int GetNumBeepers() const { return num_beepers_; } void SetNumBeepers(int beepers) { num_beepers_ = beepers; } bool HasNorthWall() const { return north_wall_; } - bool HasEastWall() const { return south_wall_; } + bool HasEastWall() const { return east_wall_; } bool HasSouthWall() const { return south_wall_; } bool HasWestWall() const { return west_wall_; } void AddWall(Orientation wall_orientation) { @@ -161,23 +161,35 @@ class Robot { PositionAndOrientation wall = ParsePositionAndOrientation(world_file); world_[wall.x][wall.y].AddWall(wall.orientation); } else if (line_prefix == beeper_prefix) { - int x, y, count; - world_file >> open_paren >> x >> comma >> y >> closed_paren >> count; - world_[x][y].SetNumBeepers(count); + PositionAndOrientation beeper = ParsePosition(world_file); + int count; + if (!(world_file >> count)) { + throw std::string("Error reading Beeper count"); + } + world_[beeper.x][beeper.y].SetNumBeepers(count); } else if (line_prefix == bag_prefix) { std::string beepers; - world_file >> beepers; - if (beepers == "INFINITY") { + if (!(world_file >> beepers)) { + throw std::string("Error reading quantity for BeeperBag"); + } + if (beepers == "INFINITY" || beepers == "INFINITE") { beeper_count_ = std::numeric_limits::max(); } else { - beeper_count_ = stoi(beepers); + try { + beeper_count_ = stoi(beepers); + } catch (std::invalid_argument& e) { + throw std::string("Unknown BeeperBag quanity, " + beepers); + } } } else if (line_prefix == karel_prefix) { position_ = ParsePositionAndOrientation(world_file); } else if (line_prefix == speed_prefix) { - world_file >> speed_; + if (!(world_file >> speed_)) { + throw std::string("Error reading Speed"); + } } else { - std::cout << "unexpected token in file: " << line_prefix << std::endl; + std::cout << "unexpected token in file: " << line_prefix << std::endl + << std::flush; break; } } @@ -312,13 +324,22 @@ class Robot { } // Draw the walls. if (cell.HasNorthWall()) { - image_.DrawLine(i * pxPerCell, j * pxPerCell, (i + 1) * pxPerCell, j * pxPerCell, kWallColor, kWallThickness); - } else if (cell.HasSouthWall()) { - image_.DrawLine(i * pxPerCell, (j + 1) * pxPerCell, (i + 1) * pxPerCell, (j + 1) * pxPerCell, kWallColor, kWallThickness); - } else if (cell.HasWestWall()) { - image_.DrawLine(i * pxPerCell, j * pxPerCell, i * pxPerCell, (j + 1) * pxPerCell, kWallColor, kWallThickness); - } else if (cell.HasEastWall()) { - image_.DrawLine((i + 1) * pxPerCell, j * pxPerCell, (i + 1) * pxPerCell, (j + 1) * pxPerCell, kWallColor, kWallThickness); + image_.DrawLine(i * pxPerCell, j * pxPerCell, (i + 1) * pxPerCell - 1, + j * pxPerCell, kWallColor, kWallThickness); + } + if (cell.HasSouthWall()) { + image_.DrawLine(i * pxPerCell, (j + 1) * pxPerCell - 1, + (i + 1) * pxPerCell - 1, (j + 1) * pxPerCell - 1, kWallColor, + kWallThickness); + } + if (cell.HasWestWall()) { + image_.DrawLine(i * pxPerCell, j * pxPerCell, i * pxPerCell, + (j + 1) * pxPerCell - 1, kWallColor, kWallThickness); + } + if (cell.HasEastWall()) { + image_.DrawLine((i + 1) * pxPerCell - 1, j * pxPerCell, + (i + 1) * pxPerCell - 1, (j + 1) * pxPerCell - 1, kWallColor, + kWallThickness); } } } @@ -406,17 +427,28 @@ class Robot { Show(kLongDuration); } - PositionAndOrientation ParsePositionAndOrientation(std::fstream& file) { - std::string direction; + // Note that the orientation is unused. + PositionAndOrientation ParsePosition(std::fstream& file) { char open_paren, comma, closed_paren; int x, y; - file >> open_paren >> x >> comma >> y >> closed_paren >> direction; + if (!(file >> open_paren >> x >> comma >> y >> closed_paren)) { + throw std::string("Error reading position"); + } + PositionAndOrientation result; // Convert y in the file to y on-screen. In the file, (1, 1) is the // bottom left corner. // In Karel coordinates, that's (0, y_dimen - 1). - PositionAndOrientation result; result.y = y_dimen_ - y; result.x = x - 1; + return result; + } + + PositionAndOrientation ParsePositionAndOrientation(std::fstream& file) { + PositionAndOrientation result = ParsePosition(file); + std::string direction; + if (!(file >> direction)) { + throw std::string("Error reading orientation"); + } // Ensure the first character is lower cased. direction[0] = tolower(direction[0]); if (direction == "north") { @@ -428,7 +460,7 @@ class Robot { } else if (direction == "west") { result.orientation = Orientation::kWest; } else { - throw std::string("Unknown direction " + direction); + throw std::string("Unknown orientation " + direction); } return result; } diff --git a/karel/test.cc b/karel/test.cc index a61450f..59c8f7c 100644 --- a/karel/test.cc +++ b/karel/test.cc @@ -18,9 +18,9 @@ void KarelProgram() { } int main() { - LoadWorld("worlds/CollectNewspaperKarel.w"); + //LoadWorld("worlds/CollectNewspaperKarel.w"); // LoadWorld("worlds/8x8.w"); - //LoadWorld("worlds/StoneMasonKarel.w"); + LoadWorld("worlds/StoneMasonKarel.w"); KarelProgram(); Finish(); return 0; diff --git a/karel/worlds/8x8.w b/karel/worlds/8x8.w index fe36721..4a48dbe 100644 --- a/karel/worlds/8x8.w +++ b/karel/worlds/8x8.w @@ -1,4 +1,8 @@ Dimension: (8, 8) +Wall: (3, 2) west +Wall: (3, 2) south +Wall: (3, 2) north +Wall: (3, 2) east BeeperBag: INFINITY Karel: (1, 1) East Speed: 0.75 From 7b6a7ef8dda7d211d79b9e053e53a1041abcb203 Mon Sep 17 00:00:00 2001 From: Katie Dektar Date: Thu, 3 Dec 2020 15:32:53 -0800 Subject: [PATCH 20/40] Nicer drawing --- karel/karel.cc | 40 +++++++++++++++++++++++----------------- karel/test.cc | 28 ++++++++++++++-------------- 2 files changed, 37 insertions(+), 31 deletions(-) diff --git a/karel/karel.cc b/karel/karel.cc index ef327c8..2fa3d54 100644 --- a/karel/karel.cc +++ b/karel/karel.cc @@ -56,10 +56,10 @@ class Cell { }; // ms for a long animation duration to show Karel. -const int kLongDuration = 500; +const int kLongDuration = 300; // ms for a short animation duration to show Karel. -const int kShortDuration = 50; +const int kShortDuration = 30; const int kDefaultDimen = 10; const int pxPerCell = 50; @@ -67,16 +67,17 @@ const int markSize = 10; const int robotSize = 30; const int beeperSize = 30; const int eyeSize = 4; +const int eyeOffset = 2; const int legLength = 6; const int limbWidth = 5; const int kWallThickness = 3; const graphics::Color eyeColor(50, 50, 50); const graphics::Color karelColor(125, 125, 125); const graphics::Color markColor(150, 150, 255); -const graphics::Color beeperColor(172, 147, 194); +const graphics::Color innerBeeperColor(172, 147, 194); const graphics::Color limbColor(105, 105, 105); const graphics::Color kWhite(255, 255, 255); -const graphics::Color kWallColor(125, 125, 125); +const graphics::Color kWallColor(50, 50, 50); class Robot { public: @@ -309,18 +310,23 @@ class Robot { int y_center = j * pxPerCell + pxPerCell / 2; // Draw the little plus at the center of the cell. image_.DrawLine(x_center - markSize / 2, y_center, - x_center + markSize / 2, y_center, markColor, 3); + x_center + markSize / 2, y_center, markColor, kWallThickness); image_.DrawLine(x_center, y_center - markSize / 2, x_center, - y_center + markSize / 2, markColor, 3); - // trig! - double line_size = sqrt((beeperSize / 2) * (beeperSize / 2) / 2); + y_center + markSize / 2, markColor, kWallThickness); Cell& cell = world_[i][j]; if (cell.GetNumBeepers() > 0) { // Draw the beepers. Beepers are stacked so you can't tell if there's // more than one in a stack. + // trig to get diamonds from thick lines! + double line_size = sqrt((beeperSize / 2) * (beeperSize / 2) / 2); + int inner_beeper_size = beeperSize - kWallThickness * 2; + double inner_line_size = sqrt((inner_beeper_size / 2) * (inner_beeper_size / 2) / 2); image_.DrawLine(x_center - line_size, y_center - line_size, x_center + line_size, y_center + line_size, - beeperColor, beeperSize); + kWallColor, beeperSize); + image_.DrawLine(x_center - inner_line_size, y_center - inner_line_size, + x_center + inner_line_size, y_center + inner_line_size, + innerBeeperColor, inner_beeper_size); } // Draw the walls. if (cell.HasNorthWall()) { @@ -357,9 +363,9 @@ class Robot { robotSize, robotSize, karelColor); switch (position_.orientation) { case Orientation::kNorth: - image_.DrawCircle(pixel_x, pixel_y - robotSize / 2 + eyeSize / 2 + 1, + image_.DrawCircle(pixel_x, pixel_y - robotSize / 2 + eyeSize / 2 + eyeOffset, eyeSize, kWhite); - image_.DrawCircle(pixel_x, pixel_y + 1, eyeSize, kWhite); + image_.DrawCircle(pixel_x, pixel_y + eyeOffset, eyeSize, kWhite); image_.DrawCircle(pixel_x, pixel_y - robotSize / 2 + eyeSize / 2, eyeSize, eyeColor); image_.DrawLine(pixel_x + robotSize / 2, pixel_y - legLength, @@ -370,8 +376,8 @@ class Robot { pixel_y + legLength, limbColor, limbWidth); break; case Orientation::kEast: - image_.DrawCircle(pixel_x - 1, pixel_y, eyeSize, kWhite); - image_.DrawCircle(pixel_x + robotSize / 2 - eyeSize / 2 - 1, pixel_y, + image_.DrawCircle(pixel_x - eyeOffset, pixel_y, eyeSize, kWhite); + image_.DrawCircle(pixel_x + robotSize / 2 - eyeSize / 2 - eyeOffset, pixel_y, eyeSize, kWhite); image_.DrawCircle(pixel_x + robotSize / 2 - eyeSize / 2, pixel_y, eyeSize, eyeColor); @@ -383,9 +389,9 @@ class Robot { pixel_y + robotSize / 2 + legLength, limbColor, limbWidth); break; case Orientation::kSouth: - image_.DrawCircle(pixel_x, pixel_y + robotSize / 2 - eyeSize / 2 - 1, + image_.DrawCircle(pixel_x, pixel_y + robotSize / 2 - eyeSize / 2 - eyeOffset, eyeSize, kWhite); - image_.DrawCircle(pixel_x, pixel_y - 1, eyeSize, kWhite); + image_.DrawCircle(pixel_x, pixel_y - eyeOffset, eyeSize, kWhite); image_.DrawCircle(pixel_x, pixel_y + robotSize / 2 - eyeSize / 2, eyeSize, eyeColor); image_.DrawLine(pixel_x - robotSize / 2, pixel_y - legLength, @@ -396,8 +402,8 @@ class Robot { pixel_y + legLength, limbColor, limbWidth); break; case Orientation::kWest: - image_.DrawCircle(pixel_x + 1, pixel_y, eyeSize, kWhite); - image_.DrawCircle(pixel_x - robotSize / 2 + eyeSize / 2 + 1, pixel_y, + image_.DrawCircle(pixel_x + eyeOffset, pixel_y, eyeSize, kWhite); + image_.DrawCircle(pixel_x - robotSize / 2 + eyeSize / 2 + eyeOffset, pixel_y, eyeSize, kWhite); image_.DrawCircle(pixel_x - robotSize / 2 + eyeSize / 2, pixel_y, eyeSize, eyeColor); diff --git a/karel/test.cc b/karel/test.cc index 59c8f7c..47ec892 100644 --- a/karel/test.cc +++ b/karel/test.cc @@ -1,20 +1,20 @@ #include "karel.h" void KarelProgram() { - // Move(); - // Move(); - // TurnLeft(); - // Move(); - // Move(); - // PickBeeper(); - // Move(); - // PutBeeper(); - // PickBeeper(); - // TurnLeft(); - // Move(); - // PutBeeper(); - // TurnLeft(); - // Move(); + Move(); + Move(); + TurnLeft(); + Move(); + Move(); + PickBeeper(); + Move(); + PutBeeper(); + PickBeeper(); + TurnLeft(); + Move(); + PutBeeper(); + TurnLeft(); + Move(); } int main() { From 4ef96ec9144138f97b3fcfe8e9c55ae47159f595 Mon Sep 17 00:00:00 2001 From: Katie Dektar Date: Thu, 3 Dec 2020 16:32:04 -0800 Subject: [PATCH 21/40] Starting to get if statements --- karel/karel.cc | 186 ++++++++++++++++++++++----- karel/test.cc | 5 +- karel/worlds/CollectNewspaperKarel.w | 2 +- 3 files changed, 160 insertions(+), 33 deletions(-) diff --git a/karel/karel.cc b/karel/karel.cc index 2fa3d54..17def9d 100644 --- a/karel/karel.cc +++ b/karel/karel.cc @@ -7,6 +7,12 @@ #include #include +// TODO: Finish shouldn't showuntilclosed in testing. +// Testing should have a non-graphical way to go. +// Save to file +// document +// phew + namespace karel { enum Orientation { @@ -71,6 +77,8 @@ const int eyeOffset = 2; const int legLength = 6; const int limbWidth = 5; const int kWallThickness = 3; +const int fontSize = 16; +const int margin = 32; const graphics::Color eyeColor(50, 50, 50); const graphics::Color karelColor(125, 125, 125); const graphics::Color markColor(150, 150, 255); @@ -78,6 +86,8 @@ const graphics::Color innerBeeperColor(172, 147, 194); const graphics::Color limbColor(105, 105, 105); const graphics::Color kWhite(255, 255, 255); const graphics::Color kWallColor(50, 50, 50); +const graphics::Color kGridColor(220, 220, 220); +const graphics::Color kErrorColor(200, 0, 50); class Robot { public: @@ -196,7 +206,8 @@ class Robot { } world_file.close(); } - image_.Initialize(x_dimen_ * pxPerCell, y_dimen_ * pxPerCell); + image_.Initialize(x_dimen_ * pxPerCell + margin, + y_dimen_ * pxPerCell + margin); DrawWorld(); DrawRobot(position_.x * pxPerCell + pxPerCell / 2, @@ -205,6 +216,7 @@ class Robot { } void Show(int duration) { + if (finished_) return; image_.ShowForMs(duration / speed_, "Karel's World"); } @@ -212,25 +224,36 @@ class Robot { switch (position_.orientation) { case Orientation::kNorth: if (position_.y == 0) { - // Cannot move any further. draw an error. + Error("Cannot move north"); + } else if (world_[position_.x][position_.y].HasNorthWall() || world_[position_.x][position_.y - 1].HasSouthWall()) { + Error("Cannot move north"); } else { AnimateMove(position_.x, position_.y - 1); } break; case Orientation::kEast: if (position_.x == x_dimen_ - 1) { + Error("Cannot move east"); + } else if (world_[position_.x][position_.y].HasEastWall() || world_[position_.x + 1][position_.y].HasWestWall()) { + Error("Cannot move east"); } else { AnimateMove(position_.x + 1, position_.y); } break; case Orientation::kSouth: if (position_.y == y_dimen_ - 1) { + Error("Cannot move south"); + } else if (world_[position_.x][position_.y].HasSouthWall() || world_[position_.x][position_.y + 1].HasNorthWall()) { + Error("Cannot move south"); } else { AnimateMove(position_.x, position_.y + 1); } break; case Orientation::kWest: if (position_.x == 0) { + Error("Cannot move west"); + } else if (world_[position_.x][position_.y].HasWestWall() || world_[position_.x - 1][position_.y].HasEastWall()) { + Error("Cannot move west"); } else { AnimateMove(position_.x - 1, position_.y); } @@ -260,7 +283,7 @@ class Robot { void PutBeeper() { if (!HasBeepersInBag()) { - // TODO error + Error("No beepers left in bag"); return; } beeper_count_--; @@ -274,7 +297,7 @@ class Robot { void PickBeeper() { int count = world_[position_.x][position_.y].GetNumBeepers(); if (count < 1) { - // TODO error + Error("No beeper to pick up"); return; } world_[position_.x][position_.y].SetNumBeepers(count - 1); @@ -286,23 +309,102 @@ class Robot { bool HasBeepersInBag() { return beeper_count_ > 0; } - void Finish() { image_.ShowUntilClosed("Karel's World"); } + bool FrontIsClear() { + return DirectionIsClear(position_.orientation); + } + + bool FrontIsBlocked() { + return !DirectionIsClear(position_.orientation); + } + + bool LeftIsClear() { + return DirectionIsClear((Orientation) (((int) position_.orientation + 1) % 4)); + } + + bool LeftIsBlocked() { + return !DirectionIsClear((Orientation)(((int) position_.orientation + 1) % 4)); + } + + void Finish() { + if (finished_) return; + finished_ = true; + image_.ShowUntilClosed("Karel's World"); + } private: Robot() {} + // TODO: Take an error code instead of a message so that it's easier to + // test. + void Error(std::string message) { + std::cout << message << std::endl << std::flush; + image_.DrawText(image_.GetWidth() / 2, image_.GetHeight() / 2, message, fontSize, kErrorColor); + Finish(); + } + + bool DirectionIsClear(Orientation orientation) { + switch (orientation) { + case Orientation::kNorth: + if (position_.y == 0) { + return false; + } else if (world_[position_.x][position_.y].HasNorthWall() || world_[position_.x][position_.y - 1].HasSouthWall()) { + return false; + } else { + return true; + } + break; + case Orientation::kEast: + if (position_.x == x_dimen_ - 1) { + return false; + } else if (world_[position_.x][position_.y].HasEastWall() || world_[position_.x + 1][position_.y].HasWestWall()) { + return false; + } else { + return true; + } + break; + case Orientation::kSouth: + if (position_.y == y_dimen_ - 1) { + return false; + } else if (world_[position_.x][position_.y].HasSouthWall() || world_[position_.x][position_.y + 1].HasNorthWall()) { + return false; + } else { + return true; + } + break; + case Orientation::kWest: + if (position_.x == 0) { + return false; + } else if (world_[position_.x][position_.y].HasWestWall() || world_[position_.x - 1][position_.y].HasEastWall()) { + return false; + } else { + return true; + } + break; + } + } + void DrawWorld() { image_.DrawRectangle(0, 0, x_dimen_ * pxPerCell, y_dimen_ * pxPerCell, kWhite); - for (int i = 0; i < y_dimen_; i++) { - // Draw horizontal lines. - image_.DrawLine(0, i * pxPerCell, pxPerCell * x_dimen_ - 1, i * pxPerCell, - graphics::Color(200, 200, 200)); + for (int i = 0; i <= y_dimen_; i++) { + // Draw horizontal lines and indexes. + int x = pxPerCell * x_dimen_ - 1; + int y = i * pxPerCell; + image_.DrawLine(0, y, x, y, kGridColor, kWallThickness); + if (i < y_dimen_) { + image_.DrawText(x + fontSize / 2, y + (pxPerCell - fontSize) / 2, + std::to_string(i + 1), fontSize, kWallColor); + } } - for (int i = 0; i < x_dimen_; i++) { - // Draw vertical lines. - image_.DrawLine(i * pxPerCell, 0, i * pxPerCell, pxPerCell * y_dimen_ - 1, - graphics::Color(200, 200, 200)); + for (int i = 0; i <= x_dimen_; i++) { + // Draw vertical lines and indexes. + int x = i * pxPerCell; + int y = pxPerCell * y_dimen_ - 1; + image_.DrawLine(x, 0, x, y, kGridColor, kWallThickness); + if (i < x_dimen_) { + image_.DrawText(x + (pxPerCell - fontSize) / 2, y + fontSize / 2, + std::to_string(i + 1), fontSize, kWallColor); + } } for (int i = 0; i < x_dimen_; i++) { for (int j = 0; j < y_dimen_; j++) { @@ -310,7 +412,8 @@ class Robot { int y_center = j * pxPerCell + pxPerCell / 2; // Draw the little plus at the center of the cell. image_.DrawLine(x_center - markSize / 2, y_center, - x_center + markSize / 2, y_center, markColor, kWallThickness); + x_center + markSize / 2, y_center, markColor, + kWallThickness); image_.DrawLine(x_center, y_center - markSize / 2, x_center, y_center + markSize / 2, markColor, kWallThickness); Cell& cell = world_[i][j]; @@ -320,13 +423,15 @@ class Robot { // trig to get diamonds from thick lines! double line_size = sqrt((beeperSize / 2) * (beeperSize / 2) / 2); int inner_beeper_size = beeperSize - kWallThickness * 2; - double inner_line_size = sqrt((inner_beeper_size / 2) * (inner_beeper_size / 2) / 2); + double inner_line_size = + sqrt((inner_beeper_size / 2) * (inner_beeper_size / 2) / 2); image_.DrawLine(x_center - line_size, y_center - line_size, x_center + line_size, y_center + line_size, kWallColor, beeperSize); - image_.DrawLine(x_center - inner_line_size, y_center - inner_line_size, - x_center + inner_line_size, y_center + inner_line_size, - innerBeeperColor, inner_beeper_size); + image_.DrawLine( + x_center - inner_line_size, y_center - inner_line_size, + x_center + inner_line_size, y_center + inner_line_size, + innerBeeperColor, inner_beeper_size); } // Draw the walls. if (cell.HasNorthWall()) { @@ -335,8 +440,8 @@ class Robot { } if (cell.HasSouthWall()) { image_.DrawLine(i * pxPerCell, (j + 1) * pxPerCell - 1, - (i + 1) * pxPerCell - 1, (j + 1) * pxPerCell - 1, kWallColor, - kWallThickness); + (i + 1) * pxPerCell - 1, (j + 1) * pxPerCell - 1, + kWallColor, kWallThickness); } if (cell.HasWestWall()) { image_.DrawLine(i * pxPerCell, j * pxPerCell, i * pxPerCell, @@ -344,8 +449,8 @@ class Robot { } if (cell.HasEastWall()) { image_.DrawLine((i + 1) * pxPerCell - 1, j * pxPerCell, - (i + 1) * pxPerCell - 1, (j + 1) * pxPerCell - 1, kWallColor, - kWallThickness); + (i + 1) * pxPerCell - 1, (j + 1) * pxPerCell - 1, + kWallColor, kWallThickness); } } } @@ -363,7 +468,8 @@ class Robot { robotSize, robotSize, karelColor); switch (position_.orientation) { case Orientation::kNorth: - image_.DrawCircle(pixel_x, pixel_y - robotSize / 2 + eyeSize / 2 + eyeOffset, + image_.DrawCircle(pixel_x, + pixel_y - robotSize / 2 + eyeSize / 2 + eyeOffset, eyeSize, kWhite); image_.DrawCircle(pixel_x, pixel_y + eyeOffset, eyeSize, kWhite); image_.DrawCircle(pixel_x, pixel_y - robotSize / 2 + eyeSize / 2, @@ -377,8 +483,8 @@ class Robot { break; case Orientation::kEast: image_.DrawCircle(pixel_x - eyeOffset, pixel_y, eyeSize, kWhite); - image_.DrawCircle(pixel_x + robotSize / 2 - eyeSize / 2 - eyeOffset, pixel_y, - eyeSize, kWhite); + image_.DrawCircle(pixel_x + robotSize / 2 - eyeSize / 2 - eyeOffset, + pixel_y, eyeSize, kWhite); image_.DrawCircle(pixel_x + robotSize / 2 - eyeSize / 2, pixel_y, eyeSize, eyeColor); image_.DrawLine( @@ -389,7 +495,8 @@ class Robot { pixel_y + robotSize / 2 + legLength, limbColor, limbWidth); break; case Orientation::kSouth: - image_.DrawCircle(pixel_x, pixel_y + robotSize / 2 - eyeSize / 2 - eyeOffset, + image_.DrawCircle(pixel_x, + pixel_y + robotSize / 2 - eyeSize / 2 - eyeOffset, eyeSize, kWhite); image_.DrawCircle(pixel_x, pixel_y - eyeOffset, eyeSize, kWhite); image_.DrawCircle(pixel_x, pixel_y + robotSize / 2 - eyeSize / 2, @@ -403,8 +510,8 @@ class Robot { break; case Orientation::kWest: image_.DrawCircle(pixel_x + eyeOffset, pixel_y, eyeSize, kWhite); - image_.DrawCircle(pixel_x - robotSize / 2 + eyeSize / 2 + eyeOffset, pixel_y, - eyeSize, kWhite); + image_.DrawCircle(pixel_x - robotSize / 2 + eyeSize / 2 + eyeOffset, + pixel_y, eyeSize, kWhite); image_.DrawCircle(pixel_x - robotSize / 2 + eyeSize / 2, pixel_y, eyeSize, eyeColor); image_.DrawLine( @@ -433,7 +540,9 @@ class Robot { Show(kLongDuration); } - // Note that the orientation is unused. + // Note that the orientation is not populated. This is just a helper to + // get the x and y position from a file with the next items in the stream + // being (x, y) PositionAndOrientation ParsePosition(std::fstream& file) { char open_paren, comma, closed_paren; int x, y; @@ -449,6 +558,9 @@ class Robot { return result; } + // Helper to get orientation of the form, `(x, y) direction`, for example, + // (3, 7) East + // Direction may be lower-case or have an uppercase first letter. PositionAndOrientation ParsePositionAndOrientation(std::fstream& file) { PositionAndOrientation result = ParsePosition(file); std::string direction; @@ -471,13 +583,27 @@ class Robot { return result; } + // Underlying image. graphics::Image image_; + + // Grid dimensions. int x_dimen_ = kDefaultDimen; int y_dimen_ = kDefaultDimen; + + // Karel's position and orientation. PositionAndOrientation position_ = {0, y_dimen_ - 1, Orientation::kEast}; + + // Karel's beeper bag. int beeper_count_ = 0; + + // The cells in the world. std::vector> world_; + + // Whether the world has been initialized. It will not re-initialize. bool initialized_ = false; + bool finished_ = false; + + // Speed multiplier for animation. double speed_ = 1.0; }; @@ -514,7 +640,7 @@ void Finish() { bool FrontIsClear() { karel::Robot& r = karel::Robot::GetInstance(); - return false; + return r.FrontIsClear(); } bool HasBeepersInBag() { diff --git a/karel/test.cc b/karel/test.cc index 47ec892..b2cf412 100644 --- a/karel/test.cc +++ b/karel/test.cc @@ -1,6 +1,7 @@ #include "karel.h" void KarelProgram() { + Move(); Move(); Move(); TurnLeft(); @@ -18,9 +19,9 @@ void KarelProgram() { } int main() { - //LoadWorld("worlds/CollectNewspaperKarel.w"); + LoadWorld("worlds/CollectNewspaperKarel.w"); // LoadWorld("worlds/8x8.w"); - LoadWorld("worlds/StoneMasonKarel.w"); + // LoadWorld("worlds/StoneMasonKarel.w"); KarelProgram(); Finish(); return 0; diff --git a/karel/worlds/CollectNewspaperKarel.w b/karel/worlds/CollectNewspaperKarel.w index ddc1e1d..98805d7 100644 --- a/karel/worlds/CollectNewspaperKarel.w +++ b/karel/worlds/CollectNewspaperKarel.w @@ -12,4 +12,4 @@ Wall: (6, 2) west Wall: (6, 4) west Beeper: (6, 3) 1 Karel: (3, 4) east -Speed: 0.00 +Speed: 1.00 From 4a66069b0358c4a9b842e6ce5c5ce0c4b3c9265e Mon Sep 17 00:00:00 2001 From: Katie Dektar Date: Thu, 3 Dec 2020 16:46:07 -0800 Subject: [PATCH 22/40] Needs lots of testing but all functions exist now --- karel/karel.cc | 180 ++++++++++++++++++++++++++++++++++++++++++------- karel/karel.h | 39 +++++++++-- 2 files changed, 187 insertions(+), 32 deletions(-) diff --git a/karel/karel.cc b/karel/karel.cc index 17def9d..f74d9ad 100644 --- a/karel/karel.cc +++ b/karel/karel.cc @@ -7,6 +7,8 @@ #include #include +#include "../graphics/image.h" + // TODO: Finish shouldn't showuntilclosed in testing. // Testing should have a non-graphical way to go. // Save to file @@ -28,6 +30,8 @@ struct PositionAndOrientation { Orientation orientation = Orientation::kNorth; }; +// Class representing a cell in Karel's world, including a count of beepers +// and whether or not there are walls. class Cell { public: int GetNumBeepers() const { return num_beepers_; } @@ -92,18 +96,13 @@ const graphics::Color kErrorColor(200, 0, 50); class Robot { public: // Get the Robot singleton. - - static karel::Robot& PrivateGetInstance() { - static Robot instance; - return instance; - } - static karel::Robot& GetInstance() { karel::Robot& instance = PrivateGetInstance(); instance.Initialize(""); return instance; } + // Get the Robot singleton and intialize it from a file. static karel::Robot& InitializeInstance(std::string filename) { karel::Robot& instance = PrivateGetInstance(); instance.Initialize(filename); @@ -221,11 +220,13 @@ class Robot { } void Move() { + if (finished_) return; switch (position_.orientation) { case Orientation::kNorth: if (position_.y == 0) { Error("Cannot move north"); - } else if (world_[position_.x][position_.y].HasNorthWall() || world_[position_.x][position_.y - 1].HasSouthWall()) { + } else if (world_[position_.x][position_.y].HasNorthWall() || + world_[position_.x][position_.y - 1].HasSouthWall()) { Error("Cannot move north"); } else { AnimateMove(position_.x, position_.y - 1); @@ -234,7 +235,8 @@ class Robot { case Orientation::kEast: if (position_.x == x_dimen_ - 1) { Error("Cannot move east"); - } else if (world_[position_.x][position_.y].HasEastWall() || world_[position_.x + 1][position_.y].HasWestWall()) { + } else if (world_[position_.x][position_.y].HasEastWall() || + world_[position_.x + 1][position_.y].HasWestWall()) { Error("Cannot move east"); } else { AnimateMove(position_.x + 1, position_.y); @@ -243,7 +245,8 @@ class Robot { case Orientation::kSouth: if (position_.y == y_dimen_ - 1) { Error("Cannot move south"); - } else if (world_[position_.x][position_.y].HasSouthWall() || world_[position_.x][position_.y + 1].HasNorthWall()) { + } else if (world_[position_.x][position_.y].HasSouthWall() || + world_[position_.x][position_.y + 1].HasNorthWall()) { Error("Cannot move south"); } else { AnimateMove(position_.x, position_.y + 1); @@ -252,7 +255,8 @@ class Robot { case Orientation::kWest: if (position_.x == 0) { Error("Cannot move west"); - } else if (world_[position_.x][position_.y].HasWestWall() || world_[position_.x - 1][position_.y].HasEastWall()) { + } else if (world_[position_.x][position_.y].HasWestWall() || + world_[position_.x - 1][position_.y].HasEastWall()) { Error("Cannot move west"); } else { AnimateMove(position_.x - 1, position_.y); @@ -262,6 +266,7 @@ class Robot { } void TurnLeft() { + if (finished_) return; switch (position_.orientation) { case Orientation::kNorth: position_.orientation = Orientation::kWest; @@ -282,6 +287,7 @@ class Robot { } void PutBeeper() { + if (finished_) return; if (!HasBeepersInBag()) { Error("No beepers left in bag"); return; @@ -295,12 +301,13 @@ class Robot { } void PickBeeper() { - int count = world_[position_.x][position_.y].GetNumBeepers(); - if (count < 1) { + if (finished_) return; + if (!BeepersPresent()) { Error("No beeper to pick up"); return; } - world_[position_.x][position_.y].SetNumBeepers(count - 1); + world_[position_.x][position_.y].SetNumBeepers( + world_[position_.x][position_.y].GetNumBeepers() - 1); beeper_count_++; DrawWorld(); DrawRobot(); @@ -309,22 +316,54 @@ class Robot { bool HasBeepersInBag() { return beeper_count_ > 0; } - bool FrontIsClear() { - return DirectionIsClear(position_.orientation); - } + bool NoBeepersInBag() { return !HasBeepersInBag(); } - bool FrontIsBlocked() { - return !DirectionIsClear(position_.orientation); + bool BeepersPresent() { + return world_[position_.x][position_.y].GetNumBeepers() > 0; } + bool NoBeepersPresent() { return !BeepersPresent(); } + + bool FrontIsClear() { return DirectionIsClear(position_.orientation); } + + bool FrontIsBlocked() { return !DirectionIsClear(position_.orientation); } + bool LeftIsClear() { - return DirectionIsClear((Orientation) (((int) position_.orientation + 1) % 4)); + return DirectionIsClear( + (Orientation)(((int)position_.orientation + 1) % 4)); } bool LeftIsBlocked() { - return !DirectionIsClear((Orientation)(((int) position_.orientation + 1) % 4)); + return !DirectionIsClear( + (Orientation)(((int)position_.orientation + 1) % 4)); } + bool RightIsClear() { + return DirectionIsClear( + (Orientation)(((int)position_.orientation - 1) % 4)); + } + + bool RightIsBlocked() { + return !DirectionIsClear( + (Orientation)(((int)position_.orientation - 1) % 4)); + } + + bool FacingNorth() { return position_.orientation == Orientation::kNorth; } + + bool NotFacingNorth() { return !FacingNorth(); } + + bool FacingEast() { return position_.orientation == Orientation::kEast; } + + bool NotFacingEast() { return !FacingEast(); } + + bool FacingSouth() { return position_.orientation == Orientation::kSouth; } + + bool NotFacingSouth() { return !FacingSouth(); } + + bool FacingWest() { return position_.orientation == Orientation::kWest; } + + bool NotFacingWest() { return !FacingWest(); } + void Finish() { if (finished_) return; finished_ = true; @@ -334,11 +373,18 @@ class Robot { private: Robot() {} + // Singleton. + static karel::Robot& PrivateGetInstance() { + static Robot instance; + return instance; + } + // TODO: Take an error code instead of a message so that it's easier to // test. void Error(std::string message) { std::cout << message << std::endl << std::flush; - image_.DrawText(image_.GetWidth() / 2, image_.GetHeight() / 2, message, fontSize, kErrorColor); + image_.DrawText(image_.GetWidth() / 2, image_.GetHeight() / 2, message, + fontSize, kErrorColor); Finish(); } @@ -347,7 +393,8 @@ class Robot { case Orientation::kNorth: if (position_.y == 0) { return false; - } else if (world_[position_.x][position_.y].HasNorthWall() || world_[position_.x][position_.y - 1].HasSouthWall()) { + } else if (world_[position_.x][position_.y].HasNorthWall() || + world_[position_.x][position_.y - 1].HasSouthWall()) { return false; } else { return true; @@ -356,7 +403,8 @@ class Robot { case Orientation::kEast: if (position_.x == x_dimen_ - 1) { return false; - } else if (world_[position_.x][position_.y].HasEastWall() || world_[position_.x + 1][position_.y].HasWestWall()) { + } else if (world_[position_.x][position_.y].HasEastWall() || + world_[position_.x + 1][position_.y].HasWestWall()) { return false; } else { return true; @@ -365,7 +413,8 @@ class Robot { case Orientation::kSouth: if (position_.y == y_dimen_ - 1) { return false; - } else if (world_[position_.x][position_.y].HasSouthWall() || world_[position_.x][position_.y + 1].HasNorthWall()) { + } else if (world_[position_.x][position_.y].HasSouthWall() || + world_[position_.x][position_.y + 1].HasNorthWall()) { return false; } else { return true; @@ -374,7 +423,8 @@ class Robot { case Orientation::kWest: if (position_.x == 0) { return false; - } else if (world_[position_.x][position_.y].HasWestWall() || world_[position_.x - 1][position_.y].HasEastWall()) { + } else if (world_[position_.x][position_.y].HasWestWall() || + world_[position_.x - 1][position_.y].HasEastWall()) { return false; } else { return true; @@ -643,7 +693,87 @@ bool FrontIsClear() { return r.FrontIsClear(); } +bool FrontIsBlocked() { + karel::Robot& r = karel::Robot::GetInstance(); + return r.FrontIsBlocked(); +} + +bool LeftIsClear() { + karel::Robot& r = karel::Robot::GetInstance(); + return r.LeftIsClear(); +} + +bool LeftIsBlocked() { + karel::Robot& r = karel::Robot::GetInstance(); + return r.LeftIsBlocked(); +} + +bool RightIsClear() { + karel::Robot& r = karel::Robot::GetInstance(); + return r.RightIsClear(); +} + +bool RightIsBlocked() { + karel::Robot& r = karel::Robot::GetInstance(); + return r.RightIsBlocked(); +} + bool HasBeepersInBag() { karel::Robot& r = karel::Robot::GetInstance(); return r.HasBeepersInBag(); } + +bool NoBeepersInBag() { + karel::Robot& r = karel::Robot::GetInstance(); + return r.NoBeepersInBag(); +} + +bool BeepersPresent() { + karel::Robot& r = karel::Robot::GetInstance(); + return r.BeepersPresent(); +} + +bool NoBeepersPresent() { + karel::Robot& r = karel::Robot::GetInstance(); + return r.NoBeepersPresent(); +} + +bool FacingNorth() { + karel::Robot& r = karel::Robot::GetInstance(); + return r.FacingNorth(); +} + +bool NotFacingNorth() { + karel::Robot& r = karel::Robot::GetInstance(); + return r.NotFacingNorth(); +} + +bool FacingEast() { + karel::Robot& r = karel::Robot::GetInstance(); + return r.FacingEast(); +} + +bool NotFacingEast() { + karel::Robot& r = karel::Robot::GetInstance(); + return r.NotFacingEast(); +} + +bool FacingSouth() { + karel::Robot& r = karel::Robot::GetInstance(); + return r.FacingSouth(); +} + +bool NotFacingSouth() { + karel::Robot& r = karel::Robot::GetInstance(); + return r.NotFacingSouth(); +} + +bool FacingWest() { + karel::Robot& r = karel::Robot::GetInstance(); + return r.FacingWest(); +} + +bool NotFacingWest() { + karel::Robot& r = karel::Robot::GetInstance(); + return r.NotFacingWest(); +} diff --git a/karel/karel.h b/karel/karel.h index fa96ee6..d0ac118 100644 --- a/karel/karel.h +++ b/karel/karel.h @@ -1,5 +1,4 @@ -#include "../graphics/image.h" -#include "../graphics/image_event.h" +#include void Move(); @@ -11,14 +10,40 @@ void PickBeeper(); bool FrontIsClear(); +bool FrontIsBlocked(); + +bool LeftIsClear(); + +bool LeftIsBlocked(); + +bool RightIsClear(); + +bool RightIsBlocked(); + bool HasBeepersInBag(); -// Set-up for professors? -// https://csis.pace.edu/~bergin/KarelJava2ed/KJRdocs/kareltherobot/World.html -void SetDimensions(int width, int height); +bool NoBeepersInBag(); -void PlaceBeeperAt(int x, int y); +bool BeepersPresent(); -void Finish(); +bool NoBeepersPresent(); + +bool FacingNorth(); + +bool NotFacingNorth(); +bool FacingEast(); + +bool NotFacingEast(); + +bool FacingSouth(); + +bool NotFacingSouth(); + +bool FacingWest(); + +bool NotFacingWest(); + +// For the instructor void LoadWorld(std::string filename); +void Finish(); From 10d6710813db1fedccb311656897b48f61d15e07 Mon Sep 17 00:00:00 2001 From: Katie Dektar Date: Fri, 4 Dec 2020 14:31:13 -0800 Subject: [PATCH 23/40] Better error handling and refactoring --- karel/karel.cc | 666 +--------------------------- karel/src/cell.h | 45 ++ karel/src/error.h | 20 + karel/src/orientation.h | 21 + karel/src/robot.cc | 666 ++++++++++++++++++++++++++++ karel/src/robot.h | 195 ++++++++ karel/test.cc | 6 +- karel/worlds/2x1.w | 4 + karel/worlds/MidpointFindingKarel.w | 4 + karel/worlds/SampleQuad2.w | 35 ++ 10 files changed, 999 insertions(+), 663 deletions(-) create mode 100644 karel/src/cell.h create mode 100644 karel/src/error.h create mode 100644 karel/src/orientation.h create mode 100644 karel/src/robot.cc create mode 100644 karel/src/robot.h create mode 100644 karel/worlds/2x1.w create mode 100644 karel/worlds/MidpointFindingKarel.w create mode 100644 karel/worlds/SampleQuad2.w diff --git a/karel/karel.cc b/karel/karel.cc index f74d9ad..d149ad3 100644 --- a/karel/karel.cc +++ b/karel/karel.cc @@ -1,666 +1,14 @@ #include "karel.h" -#include - -#include -#include -#include -#include - -#include "../graphics/image.h" - -// TODO: Finish shouldn't showuntilclosed in testing. -// Testing should have a non-graphical way to go. -// Save to file -// document -// phew - -namespace karel { - -enum Orientation { - kNorth = 1, - kEast = 2, - kSouth = 3, - kWest = 4, -}; - -struct PositionAndOrientation { - int x = 0; - int y = 0; - Orientation orientation = Orientation::kNorth; -}; - -// Class representing a cell in Karel's world, including a count of beepers -// and whether or not there are walls. -class Cell { - public: - int GetNumBeepers() const { return num_beepers_; } - void SetNumBeepers(int beepers) { num_beepers_ = beepers; } - bool HasNorthWall() const { return north_wall_; } - bool HasEastWall() const { return east_wall_; } - bool HasSouthWall() const { return south_wall_; } - bool HasWestWall() const { return west_wall_; } - void AddWall(Orientation wall_orientation) { - switch (wall_orientation) { - case kNorth: - north_wall_ = true; - break; - case kEast: - east_wall_ = true; - break; - case kSouth: - south_wall_ = true; - break; - case kWest: - west_wall_ = true; - break; - } - } - - private: - bool num_beepers_ = 0; - bool north_wall_ = false; - bool east_wall_ = false; - bool south_wall_ = false; - bool west_wall_ = false; -}; - -// ms for a long animation duration to show Karel. -const int kLongDuration = 300; - -// ms for a short animation duration to show Karel. -const int kShortDuration = 30; - -const int kDefaultDimen = 10; -const int pxPerCell = 50; -const int markSize = 10; -const int robotSize = 30; -const int beeperSize = 30; -const int eyeSize = 4; -const int eyeOffset = 2; -const int legLength = 6; -const int limbWidth = 5; -const int kWallThickness = 3; -const int fontSize = 16; -const int margin = 32; -const graphics::Color eyeColor(50, 50, 50); -const graphics::Color karelColor(125, 125, 125); -const graphics::Color markColor(150, 150, 255); -const graphics::Color innerBeeperColor(172, 147, 194); -const graphics::Color limbColor(105, 105, 105); -const graphics::Color kWhite(255, 255, 255); -const graphics::Color kWallColor(50, 50, 50); -const graphics::Color kGridColor(220, 220, 220); -const graphics::Color kErrorColor(200, 0, 50); - -class Robot { - public: - // Get the Robot singleton. - static karel::Robot& GetInstance() { - karel::Robot& instance = PrivateGetInstance(); - instance.Initialize(""); - return instance; - } - - // Get the Robot singleton and intialize it from a file. - static karel::Robot& InitializeInstance(std::string filename) { - karel::Robot& instance = PrivateGetInstance(); - instance.Initialize(filename); - return instance; - } - - // Disallow copy and assign. - Robot(const Robot&) = delete; - karel::Robot& operator=(const Robot&) = delete; - - void Initialize(std::string filename) { - // Ensure only intitialized once. - if (initialized_) return; - initialized_ = true; - - if (!filename.size()) { - // No file. Default 10x10 blank world with no walls and no beepers. - x_dimen_ = kDefaultDimen; - y_dimen_ = kDefaultDimen; - for (int i = 0; i < x_dimen_; i++) { - world_.push_back(std::vector()); - for (int j = 0; j < y_dimen_; j++) { - world_[i].push_back(Cell()); - } - } - // Nearly infinite beepers. - beeper_count_ = std::numeric_limits::max(); - position_.x = 0; - position_.y = y_dimen_ - 1; - } else { - std::fstream world_file; - world_file.open(filename); - if (!world_file.is_open()) { - // TODO: Replace throwables with better error codes? - throw std::string("Error opening file " + filename); - } - std::string line; - - const std::string dimension_prefix = "Dimension:"; - const std::string beeper_prefix = "Beeper:"; - const std::string wall_prefix = "Wall:"; - const std::string bag_prefix = "BeeperBag:"; - const std::string karel_prefix = "Karel:"; - const std::string speed_prefix = "Speed:"; - - std::string line_prefix; - char open_paren, comma, closed_paren; - if (!(world_file >> line_prefix >> open_paren >> x_dimen_ >> comma >> - y_dimen_ >> closed_paren)) { - throw std::string("Could not find Dimension in first line"); - } - if (line_prefix != dimension_prefix) { - throw std::string("Could not find Dimension in first line"); - } - for (int i = 0; i < x_dimen_; i++) { - world_.push_back(std::vector()); - for (int j = 0; j < y_dimen_; j++) { - world_[i].push_back(Cell()); - } - } - - // Read the rest of the file to get beepers and walls. - // TODO: May need better error checking. - while (world_file >> line_prefix) { - if (line_prefix == wall_prefix) { - PositionAndOrientation wall = ParsePositionAndOrientation(world_file); - world_[wall.x][wall.y].AddWall(wall.orientation); - } else if (line_prefix == beeper_prefix) { - PositionAndOrientation beeper = ParsePosition(world_file); - int count; - if (!(world_file >> count)) { - throw std::string("Error reading Beeper count"); - } - world_[beeper.x][beeper.y].SetNumBeepers(count); - } else if (line_prefix == bag_prefix) { - std::string beepers; - if (!(world_file >> beepers)) { - throw std::string("Error reading quantity for BeeperBag"); - } - if (beepers == "INFINITY" || beepers == "INFINITE") { - beeper_count_ = std::numeric_limits::max(); - } else { - try { - beeper_count_ = stoi(beepers); - } catch (std::invalid_argument& e) { - throw std::string("Unknown BeeperBag quanity, " + beepers); - } - } - } else if (line_prefix == karel_prefix) { - position_ = ParsePositionAndOrientation(world_file); - } else if (line_prefix == speed_prefix) { - if (!(world_file >> speed_)) { - throw std::string("Error reading Speed"); - } - } else { - std::cout << "unexpected token in file: " << line_prefix << std::endl - << std::flush; - break; - } - } - world_file.close(); - } - image_.Initialize(x_dimen_ * pxPerCell + margin, - y_dimen_ * pxPerCell + margin); - - DrawWorld(); - DrawRobot(position_.x * pxPerCell + pxPerCell / 2, - position_.y * pxPerCell + pxPerCell / 2); - Show(kLongDuration); - } - - void Show(int duration) { - if (finished_) return; - image_.ShowForMs(duration / speed_, "Karel's World"); - } - - void Move() { - if (finished_) return; - switch (position_.orientation) { - case Orientation::kNorth: - if (position_.y == 0) { - Error("Cannot move north"); - } else if (world_[position_.x][position_.y].HasNorthWall() || - world_[position_.x][position_.y - 1].HasSouthWall()) { - Error("Cannot move north"); - } else { - AnimateMove(position_.x, position_.y - 1); - } - break; - case Orientation::kEast: - if (position_.x == x_dimen_ - 1) { - Error("Cannot move east"); - } else if (world_[position_.x][position_.y].HasEastWall() || - world_[position_.x + 1][position_.y].HasWestWall()) { - Error("Cannot move east"); - } else { - AnimateMove(position_.x + 1, position_.y); - } - break; - case Orientation::kSouth: - if (position_.y == y_dimen_ - 1) { - Error("Cannot move south"); - } else if (world_[position_.x][position_.y].HasSouthWall() || - world_[position_.x][position_.y + 1].HasNorthWall()) { - Error("Cannot move south"); - } else { - AnimateMove(position_.x, position_.y + 1); - } - break; - case Orientation::kWest: - if (position_.x == 0) { - Error("Cannot move west"); - } else if (world_[position_.x][position_.y].HasWestWall() || - world_[position_.x - 1][position_.y].HasEastWall()) { - Error("Cannot move west"); - } else { - AnimateMove(position_.x - 1, position_.y); - } - break; - } - } - - void TurnLeft() { - if (finished_) return; - switch (position_.orientation) { - case Orientation::kNorth: - position_.orientation = Orientation::kWest; - break; - case Orientation::kEast: - position_.orientation = Orientation::kNorth; - break; - case Orientation::kSouth: - position_.orientation = Orientation::kEast; - break; - case Orientation::kWest: - position_.orientation = Orientation::kSouth; - break; - } - DrawWorld(); - DrawRobot(); - Show(kLongDuration); - } - - void PutBeeper() { - if (finished_) return; - if (!HasBeepersInBag()) { - Error("No beepers left in bag"); - return; - } - beeper_count_--; - world_[position_.x][position_.y].SetNumBeepers( - world_[position_.x][position_.y].GetNumBeepers() + 1); - DrawWorld(); - DrawRobot(); - Show(kLongDuration); - } - - void PickBeeper() { - if (finished_) return; - if (!BeepersPresent()) { - Error("No beeper to pick up"); - return; - } - world_[position_.x][position_.y].SetNumBeepers( - world_[position_.x][position_.y].GetNumBeepers() - 1); - beeper_count_++; - DrawWorld(); - DrawRobot(); - Show(kLongDuration); - } - - bool HasBeepersInBag() { return beeper_count_ > 0; } - - bool NoBeepersInBag() { return !HasBeepersInBag(); } - - bool BeepersPresent() { - return world_[position_.x][position_.y].GetNumBeepers() > 0; - } - - bool NoBeepersPresent() { return !BeepersPresent(); } - - bool FrontIsClear() { return DirectionIsClear(position_.orientation); } - - bool FrontIsBlocked() { return !DirectionIsClear(position_.orientation); } - - bool LeftIsClear() { - return DirectionIsClear( - (Orientation)(((int)position_.orientation + 1) % 4)); - } - - bool LeftIsBlocked() { - return !DirectionIsClear( - (Orientation)(((int)position_.orientation + 1) % 4)); - } - - bool RightIsClear() { - return DirectionIsClear( - (Orientation)(((int)position_.orientation - 1) % 4)); - } - - bool RightIsBlocked() { - return !DirectionIsClear( - (Orientation)(((int)position_.orientation - 1) % 4)); - } - - bool FacingNorth() { return position_.orientation == Orientation::kNorth; } - - bool NotFacingNorth() { return !FacingNorth(); } - - bool FacingEast() { return position_.orientation == Orientation::kEast; } - - bool NotFacingEast() { return !FacingEast(); } - - bool FacingSouth() { return position_.orientation == Orientation::kSouth; } - - bool NotFacingSouth() { return !FacingSouth(); } - - bool FacingWest() { return position_.orientation == Orientation::kWest; } - - bool NotFacingWest() { return !FacingWest(); } - - void Finish() { - if (finished_) return; - finished_ = true; - image_.ShowUntilClosed("Karel's World"); - } - - private: - Robot() {} - - // Singleton. - static karel::Robot& PrivateGetInstance() { - static Robot instance; - return instance; - } - - // TODO: Take an error code instead of a message so that it's easier to - // test. - void Error(std::string message) { - std::cout << message << std::endl << std::flush; - image_.DrawText(image_.GetWidth() / 2, image_.GetHeight() / 2, message, - fontSize, kErrorColor); - Finish(); - } - - bool DirectionIsClear(Orientation orientation) { - switch (orientation) { - case Orientation::kNorth: - if (position_.y == 0) { - return false; - } else if (world_[position_.x][position_.y].HasNorthWall() || - world_[position_.x][position_.y - 1].HasSouthWall()) { - return false; - } else { - return true; - } - break; - case Orientation::kEast: - if (position_.x == x_dimen_ - 1) { - return false; - } else if (world_[position_.x][position_.y].HasEastWall() || - world_[position_.x + 1][position_.y].HasWestWall()) { - return false; - } else { - return true; - } - break; - case Orientation::kSouth: - if (position_.y == y_dimen_ - 1) { - return false; - } else if (world_[position_.x][position_.y].HasSouthWall() || - world_[position_.x][position_.y + 1].HasNorthWall()) { - return false; - } else { - return true; - } - break; - case Orientation::kWest: - if (position_.x == 0) { - return false; - } else if (world_[position_.x][position_.y].HasWestWall() || - world_[position_.x - 1][position_.y].HasEastWall()) { - return false; - } else { - return true; - } - break; - } - } - - void DrawWorld() { - image_.DrawRectangle(0, 0, x_dimen_ * pxPerCell, y_dimen_ * pxPerCell, - kWhite); - for (int i = 0; i <= y_dimen_; i++) { - // Draw horizontal lines and indexes. - int x = pxPerCell * x_dimen_ - 1; - int y = i * pxPerCell; - image_.DrawLine(0, y, x, y, kGridColor, kWallThickness); - if (i < y_dimen_) { - image_.DrawText(x + fontSize / 2, y + (pxPerCell - fontSize) / 2, - std::to_string(i + 1), fontSize, kWallColor); - } - } - for (int i = 0; i <= x_dimen_; i++) { - // Draw vertical lines and indexes. - int x = i * pxPerCell; - int y = pxPerCell * y_dimen_ - 1; - image_.DrawLine(x, 0, x, y, kGridColor, kWallThickness); - if (i < x_dimen_) { - image_.DrawText(x + (pxPerCell - fontSize) / 2, y + fontSize / 2, - std::to_string(i + 1), fontSize, kWallColor); - } - } - for (int i = 0; i < x_dimen_; i++) { - for (int j = 0; j < y_dimen_; j++) { - int x_center = i * pxPerCell + pxPerCell / 2; - int y_center = j * pxPerCell + pxPerCell / 2; - // Draw the little plus at the center of the cell. - image_.DrawLine(x_center - markSize / 2, y_center, - x_center + markSize / 2, y_center, markColor, - kWallThickness); - image_.DrawLine(x_center, y_center - markSize / 2, x_center, - y_center + markSize / 2, markColor, kWallThickness); - Cell& cell = world_[i][j]; - if (cell.GetNumBeepers() > 0) { - // Draw the beepers. Beepers are stacked so you can't tell if there's - // more than one in a stack. - // trig to get diamonds from thick lines! - double line_size = sqrt((beeperSize / 2) * (beeperSize / 2) / 2); - int inner_beeper_size = beeperSize - kWallThickness * 2; - double inner_line_size = - sqrt((inner_beeper_size / 2) * (inner_beeper_size / 2) / 2); - image_.DrawLine(x_center - line_size, y_center - line_size, - x_center + line_size, y_center + line_size, - kWallColor, beeperSize); - image_.DrawLine( - x_center - inner_line_size, y_center - inner_line_size, - x_center + inner_line_size, y_center + inner_line_size, - innerBeeperColor, inner_beeper_size); - } - // Draw the walls. - if (cell.HasNorthWall()) { - image_.DrawLine(i * pxPerCell, j * pxPerCell, (i + 1) * pxPerCell - 1, - j * pxPerCell, kWallColor, kWallThickness); - } - if (cell.HasSouthWall()) { - image_.DrawLine(i * pxPerCell, (j + 1) * pxPerCell - 1, - (i + 1) * pxPerCell - 1, (j + 1) * pxPerCell - 1, - kWallColor, kWallThickness); - } - if (cell.HasWestWall()) { - image_.DrawLine(i * pxPerCell, j * pxPerCell, i * pxPerCell, - (j + 1) * pxPerCell - 1, kWallColor, kWallThickness); - } - if (cell.HasEastWall()) { - image_.DrawLine((i + 1) * pxPerCell - 1, j * pxPerCell, - (i + 1) * pxPerCell - 1, (j + 1) * pxPerCell - 1, - kWallColor, kWallThickness); - } - } - } - } - - void DrawRobot() { - // Center in the cell. - DrawRobot(position_.x * pxPerCell + pxPerCell / 2, - position_.y * pxPerCell + pxPerCell / 2); - } - - // pixel_x and pixel_y are the center of the cell in pixels. - void DrawRobot(int pixel_x, int pixel_y) { - image_.DrawRectangle(pixel_x - robotSize / 2, pixel_y - robotSize / 2, - robotSize, robotSize, karelColor); - switch (position_.orientation) { - case Orientation::kNorth: - image_.DrawCircle(pixel_x, - pixel_y - robotSize / 2 + eyeSize / 2 + eyeOffset, - eyeSize, kWhite); - image_.DrawCircle(pixel_x, pixel_y + eyeOffset, eyeSize, kWhite); - image_.DrawCircle(pixel_x, pixel_y - robotSize / 2 + eyeSize / 2, - eyeSize, eyeColor); - image_.DrawLine(pixel_x + robotSize / 2, pixel_y - legLength, - pixel_x + robotSize / 2 + legLength, - pixel_y - legLength, limbColor, limbWidth); - image_.DrawLine(pixel_x + robotSize / 2, pixel_y + legLength, - pixel_x + robotSize / 2 + legLength, - pixel_y + legLength, limbColor, limbWidth); - break; - case Orientation::kEast: - image_.DrawCircle(pixel_x - eyeOffset, pixel_y, eyeSize, kWhite); - image_.DrawCircle(pixel_x + robotSize / 2 - eyeSize / 2 - eyeOffset, - pixel_y, eyeSize, kWhite); - image_.DrawCircle(pixel_x + robotSize / 2 - eyeSize / 2, pixel_y, - eyeSize, eyeColor); - image_.DrawLine( - pixel_x - legLength, pixel_y + robotSize / 2, pixel_x - legLength, - pixel_y + robotSize / 2 + legLength, limbColor, limbWidth); - image_.DrawLine( - pixel_x + legLength, pixel_y + robotSize / 2, pixel_x + legLength, - pixel_y + robotSize / 2 + legLength, limbColor, limbWidth); - break; - case Orientation::kSouth: - image_.DrawCircle(pixel_x, - pixel_y + robotSize / 2 - eyeSize / 2 - eyeOffset, - eyeSize, kWhite); - image_.DrawCircle(pixel_x, pixel_y - eyeOffset, eyeSize, kWhite); - image_.DrawCircle(pixel_x, pixel_y + robotSize / 2 - eyeSize / 2, - eyeSize, eyeColor); - image_.DrawLine(pixel_x - robotSize / 2, pixel_y - legLength, - pixel_x - robotSize / 2 - legLength, - pixel_y - legLength, limbColor, limbWidth); - image_.DrawLine(pixel_x - robotSize / 2, pixel_y + legLength, - pixel_x - robotSize / 2 - legLength, - pixel_y + legLength, limbColor, limbWidth); - break; - case Orientation::kWest: - image_.DrawCircle(pixel_x + eyeOffset, pixel_y, eyeSize, kWhite); - image_.DrawCircle(pixel_x - robotSize / 2 + eyeSize / 2 + eyeOffset, - pixel_y, eyeSize, kWhite); - image_.DrawCircle(pixel_x - robotSize / 2 + eyeSize / 2, pixel_y, - eyeSize, eyeColor); - image_.DrawLine( - pixel_x - legLength, pixel_y - robotSize / 2, pixel_x - legLength, - pixel_y - robotSize / 2 - legLength, limbColor, limbWidth); - image_.DrawLine( - pixel_x + legLength, pixel_y - robotSize / 2, pixel_x + legLength, - pixel_y - robotSize / 2 - legLength, limbColor, limbWidth); - break; - } - image_.DrawCircle(pixel_x, pixel_y, eyeSize, eyeColor); - } - - void AnimateMove(int next_x, int next_y) { - int steps = 10; - for (int i = 1; i <= steps; i++) { - DrawWorld(); - double fraction = i * 1.0 / steps; - double x = position_.x * (1 - fraction) + next_x * fraction; - double y = position_.y * (1 - fraction) + next_y * fraction; - DrawRobot(x * pxPerCell + pxPerCell / 2, y * pxPerCell + pxPerCell / 2); - Show(kShortDuration); - } - position_.x = next_x; - position_.y = next_y; - Show(kLongDuration); - } - - // Note that the orientation is not populated. This is just a helper to - // get the x and y position from a file with the next items in the stream - // being (x, y) - PositionAndOrientation ParsePosition(std::fstream& file) { - char open_paren, comma, closed_paren; - int x, y; - if (!(file >> open_paren >> x >> comma >> y >> closed_paren)) { - throw std::string("Error reading position"); - } - PositionAndOrientation result; - // Convert y in the file to y on-screen. In the file, (1, 1) is the - // bottom left corner. - // In Karel coordinates, that's (0, y_dimen - 1). - result.y = y_dimen_ - y; - result.x = x - 1; - return result; - } - - // Helper to get orientation of the form, `(x, y) direction`, for example, - // (3, 7) East - // Direction may be lower-case or have an uppercase first letter. - PositionAndOrientation ParsePositionAndOrientation(std::fstream& file) { - PositionAndOrientation result = ParsePosition(file); - std::string direction; - if (!(file >> direction)) { - throw std::string("Error reading orientation"); - } - // Ensure the first character is lower cased. - direction[0] = tolower(direction[0]); - if (direction == "north") { - result.orientation = Orientation::kNorth; - } else if (direction == "east") { - result.orientation = Orientation::kEast; - } else if (direction == "south") { - result.orientation = Orientation::kSouth; - } else if (direction == "west") { - result.orientation = Orientation::kWest; - } else { - throw std::string("Unknown orientation " + direction); - } - return result; - } - - // Underlying image. - graphics::Image image_; - - // Grid dimensions. - int x_dimen_ = kDefaultDimen; - int y_dimen_ = kDefaultDimen; - - // Karel's position and orientation. - PositionAndOrientation position_ = {0, y_dimen_ - 1, Orientation::kEast}; - - // Karel's beeper bag. - int beeper_count_ = 0; - - // The cells in the world. - std::vector> world_; - - // Whether the world has been initialized. It will not re-initialize. - bool initialized_ = false; - bool finished_ = false; - - // Speed multiplier for animation. - double speed_ = 1.0; -}; - -} // namespace karel +#include "src/robot.h" void LoadWorld(std::string filename) { - karel::Robot& r = karel::Robot::InitializeInstance(filename); + try { + karel::Robot& r = karel::Robot::InitializeInstance(filename); + } catch (std::string error) { + std::cout << "Error loading world file " << filename << ": \n" << error << std::endl; + exit(1); + } } void Move() { diff --git a/karel/src/cell.h b/karel/src/cell.h new file mode 100644 index 0000000..95f0b4b --- /dev/null +++ b/karel/src/cell.h @@ -0,0 +1,45 @@ +#include "orientation.h" + +#ifndef CELL_H +#define CELL_H + +namespace karel { + +// Class representing a cell in Karel's world, including a count of beepers +// and whether or not there are walls. +class Cell { + public: + int GetNumBeepers() const { return num_beepers_; } + void SetNumBeepers(int beepers) { num_beepers_ = beepers; } + bool HasNorthWall() const { return north_wall_; } + bool HasEastWall() const { return east_wall_; } + bool HasSouthWall() const { return south_wall_; } + bool HasWestWall() const { return west_wall_; } + void AddWall(Orientation wall_orientation) { + switch (wall_orientation) { + case kNorth: + north_wall_ = true; + break; + case kEast: + east_wall_ = true; + break; + case kSouth: + south_wall_ = true; + break; + case kWest: + west_wall_ = true; + break; + } + } + + private: + bool num_beepers_ = 0; + bool north_wall_ = false; + bool east_wall_ = false; + bool south_wall_ = false; + bool west_wall_ = false; +}; + +} // namespace karel + +#endif // CELL_H diff --git a/karel/src/error.h b/karel/src/error.h new file mode 100644 index 0000000..0432812 --- /dev/null +++ b/karel/src/error.h @@ -0,0 +1,20 @@ +#include "orientation.h" + +#ifndef ERROR_H +#define ERROR_H + +namespace karel { + +enum RobotError { + kNoError = 0, + kCannotMoveNorth, + kCannotMoveEast, + kCannotMoveSouth, + kCannotMoveWest, + kCannotPutBeeper, + kCannotPickBeeper, +}; + +} // namespace karel + +#endif diff --git a/karel/src/orientation.h b/karel/src/orientation.h new file mode 100644 index 0000000..979f263 --- /dev/null +++ b/karel/src/orientation.h @@ -0,0 +1,21 @@ +#ifndef ORIENTATION_H +#define ORIENTATION_H + +namespace karel { + +enum Orientation { + kNorth = 1, + kEast = 2, + kSouth = 3, + kWest = 4, +}; + +struct PositionAndOrientation { + int x = 0; + int y = 0; + Orientation orientation = Orientation::kNorth; +}; + +} // namespace karel + +#endif // ORIENTATION_H diff --git a/karel/src/robot.cc b/karel/src/robot.cc new file mode 100644 index 0000000..5412f09 --- /dev/null +++ b/karel/src/robot.cc @@ -0,0 +1,666 @@ +#include "robot.h" + +#include + +#include +#include +#include +#include + +#include "../../graphics/image.h" +#include "cell.h" +#include "error.h" +#include "orientation.h" + +// TODO: Finish shouldn't showuntilclosed in testing. +// Testing should have a non-graphical way to go. +// Save to file +// document +// phew + +namespace karel { + +namespace { + +// Default width and height in cells. +const int kDefaultDimen = 10; + +// Milliseconds for a long animation duration to show Karel, used after each +// Karel action. +const int kLongDuration = 300; + +// Milliseconds for a short animation duration to show Karel, used when Karel +// is moving. +const int kShortDuration = 30; + +// Number of steps to take in the animation moving karel between cells. +const int kNumAnimationSteps = 10; + +// Pixel constants. +const int pxPerCell = 50; +const int markSize = 10; +const int robotSize = 30; +const int beeperSize = 30; +const int eyeSize = 4; +const int eyeOffset = 2; +const int legLength = 6; +const int limbWidth = 5; +const int kWallThickness = 3; +const int fontSize = 16; +const int kErrorFontSize = 20; +const int margin = 32; + +// Color constants. +const graphics::Color eyeColor(50, 50, 50); +const graphics::Color karelColor(125, 125, 125); +const graphics::Color markColor(150, 150, 255); +const graphics::Color innerBeeperColor(172, 147, 194); +const graphics::Color limbColor(105, 105, 105); +const graphics::Color kWhite(255, 255, 255); +const graphics::Color kWallColor(50, 50, 50); +const graphics::Color kGridColor(220, 220, 220); +const graphics::Color kErrorColor(173, 0, 35); + +} // namespace + +Robot::Robot() {} + +// Singleton. Static. +karel::Robot& Robot::PrivateGetInstance() { + static Robot instance; + return instance; +} + +// static. +karel::Robot& Robot::GetInstance() { + karel::Robot& instance = PrivateGetInstance(); + instance.Initialize("", /* enable graphics */ true); + return instance; +} + +// Get the Robot singleton and intialize it from a file. +// static. +karel::Robot& Robot::InitializeInstance(std::string filename, + bool enable_graphics) { + karel::Robot& instance = PrivateGetInstance(); + instance.Initialize(filename, enable_graphics); + return instance; +} + +void Robot::Initialize(std::string filename, bool enable_graphics) { + // Ensure only intitialized once. + if (initialized_) return; + initialized_ = true; + + enable_animations_ = enable_graphics; + + if (!filename.size()) { + // No file. Default 10x10 blank world with no walls and no beepers. + x_dimen_ = kDefaultDimen; + y_dimen_ = kDefaultDimen; + for (int i = 0; i < x_dimen_; i++) { + world_.push_back(std::vector()); + for (int j = 0; j < y_dimen_; j++) { + world_[i].push_back(Cell()); + } + } + // Nearly infinite beepers. + beeper_count_ = std::numeric_limits::max(); + PositionAndOrientation position_ = {0, y_dimen_ - 1, Orientation::kEast}; + } else { + std::fstream world_file; + world_file.open(filename); + if (!world_file.is_open()) { + // TODO: Replace throwables with better error codes? + throw std::string("Error opening file"); + } + std::string line; + + const std::string dimension_prefix = "Dimension:"; + const std::string beeper_prefix = "Beeper:"; + const std::string wall_prefix = "Wall:"; + const std::string bag_prefix = "BeeperBag:"; + const std::string karel_prefix = "Karel:"; + const std::string speed_prefix = "Speed:"; + + std::string line_prefix; + char open_paren, comma, closed_paren; + if (!(world_file >> line_prefix >> open_paren >> x_dimen_ >> comma >> + y_dimen_ >> closed_paren)) { + throw std::string("Could not find Dimension in first line"); + } + if (line_prefix != dimension_prefix) { + throw std::string("Could not find Dimension in first line"); + } + if (x_dimen_ < 2 || y_dimen_ < 1) { + throw std::string( + "Cannot load a world less than 2 cells wide or less than 1 cell " + "tall"); + } + for (int i = 0; i < x_dimen_; i++) { + world_.push_back(std::vector()); + for (int j = 0; j < y_dimen_; j++) { + world_[i].push_back(Cell()); + } + } + + // Read the rest of the file to get beepers and walls. + // TODO: May need better error checking. + while (world_file >> line_prefix) { + if (line_prefix == wall_prefix) { + PositionAndOrientation wall = ParsePositionAndOrientation(world_file); + world_[wall.x][wall.y].AddWall(wall.orientation); + } else if (line_prefix == beeper_prefix) { + PositionAndOrientation beeper = ParsePosition(world_file); + int count; + if (!(world_file >> count)) { + throw std::string("Error reading Beeper count"); + } + world_[beeper.x][beeper.y].SetNumBeepers(count); + } else if (line_prefix == bag_prefix) { + std::string beepers; + if (!(world_file >> beepers)) { + throw std::string("Error reading quantity for BeeperBag"); + } + if (beepers == "INFINITY" || beepers == "INFINITE") { + beeper_count_ = std::numeric_limits::max(); + } else { + try { + beeper_count_ = stoi(beepers); + } catch (std::invalid_argument& e) { + throw std::string("Unknown BeeperBag quanity, " + beepers); + } + } + } else if (line_prefix == karel_prefix) { + position_ = ParsePositionAndOrientation(world_file); + } else if (line_prefix == speed_prefix) { + if (!(world_file >> speed_)) { + throw std::string("Error reading Speed"); + } + } else { + std::cout << "unexpected token in file: " << line_prefix << std::endl + << std::flush; + break; + } + } + world_file.close(); + } + image_.Initialize(x_dimen_ * pxPerCell + margin, + y_dimen_ * pxPerCell + margin); + + DrawWorld(); + DrawRobot(position_.x * pxPerCell + pxPerCell / 2, + position_.y * pxPerCell + pxPerCell / 2); + Show(kLongDuration); +} + +void Robot::Move() { + if (finished_) return; + switch (position_.orientation) { + case Orientation::kNorth: + if (position_.y == 0) { + Error(RobotError::kCannotMoveNorth); + } else if (world_[position_.x][position_.y].HasNorthWall() || + world_[position_.x][position_.y - 1].HasSouthWall()) { + Error(RobotError::kCannotMoveNorth); + } else { + AnimateMove(position_.x, position_.y - 1); + } + break; + case Orientation::kEast: + if (position_.x == x_dimen_ - 1) { + Error(RobotError::kCannotMoveEast); + } else if (world_[position_.x][position_.y].HasEastWall() || + world_[position_.x + 1][position_.y].HasWestWall()) { + Error(RobotError::kCannotMoveEast); + } else { + AnimateMove(position_.x + 1, position_.y); + } + break; + case Orientation::kSouth: + if (position_.y == y_dimen_ - 1) { + Error(RobotError::kCannotMoveSouth); + } else if (world_[position_.x][position_.y].HasSouthWall() || + world_[position_.x][position_.y + 1].HasNorthWall()) { + Error(RobotError::kCannotMoveSouth); + } else { + AnimateMove(position_.x, position_.y + 1); + } + break; + case Orientation::kWest: + if (position_.x == 0) { + Error(RobotError::kCannotMoveWest); + } else if (world_[position_.x][position_.y].HasWestWall() || + world_[position_.x - 1][position_.y].HasEastWall()) { + Error(RobotError::kCannotMoveWest); + } else { + AnimateMove(position_.x - 1, position_.y); + } + break; + } +} + +void Robot::TurnLeft() { + if (finished_) return; + switch (position_.orientation) { + case Orientation::kNorth: + position_.orientation = Orientation::kWest; + break; + case Orientation::kEast: + position_.orientation = Orientation::kNorth; + break; + case Orientation::kSouth: + position_.orientation = Orientation::kEast; + break; + case Orientation::kWest: + position_.orientation = Orientation::kSouth; + break; + } + DrawWorld(); + DrawRobot(); + Show(kLongDuration); +} + +void Robot::PutBeeper() { + if (finished_) return; + if (!HasBeepersInBag()) { + Error(RobotError::kCannotPutBeeper); + return; + } + beeper_count_--; + Cell& cell = world_[position_.x][position_.y]; + cell.SetNumBeepers(cell.GetNumBeepers() + 1); + DrawWorld(); + DrawRobot(); + Show(kLongDuration); +} + +void Robot::PickBeeper() { + if (finished_) return; + if (!BeepersPresent()) { + Error(RobotError::kCannotPickBeeper); + return; + } + Cell& cell = world_[position_.x][position_.y]; + cell.SetNumBeepers(cell.GetNumBeepers() - 1); + beeper_count_++; + DrawWorld(); + DrawRobot(); + Show(kLongDuration); +} + +bool Robot::HasBeepersInBag() const { return beeper_count_ > 0; } + +bool Robot::NoBeepersInBag() const { return !HasBeepersInBag(); } + +bool Robot::BeepersPresent() const { + return world_[position_.x][position_.y].GetNumBeepers() > 0; +} + +bool Robot::NoBeepersPresent() const { return !BeepersPresent(); } + +bool Robot::FrontIsClear() const { + return DirectionIsClear(position_.orientation); +} + +bool Robot::FrontIsBlocked() const { + return !DirectionIsClear(position_.orientation); +} + +bool Robot::LeftIsClear() const { + return DirectionIsClear((Orientation)(((int)position_.orientation + 1) % 4)); +} + +bool Robot::LeftIsBlocked() const { + return !DirectionIsClear((Orientation)(((int)position_.orientation + 1) % 4)); +} + +bool Robot::RightIsClear() const { + return DirectionIsClear((Orientation)(((int)position_.orientation - 1) % 4)); +} + +bool Robot::RightIsBlocked() const { + return !DirectionIsClear((Orientation)(((int)position_.orientation - 1) % 4)); +} + +bool Robot::FacingNorth() const { + return position_.orientation == Orientation::kNorth; +} + +bool Robot::NotFacingNorth() const { return !FacingNorth(); } + +bool Robot::FacingEast() const { + return position_.orientation == Orientation::kEast; +} + +bool Robot::NotFacingEast() const { return !FacingEast(); } + +bool Robot::FacingSouth() const { + return position_.orientation == Orientation::kSouth; +} + +bool Robot::NotFacingSouth() const { return !FacingSouth(); } + +bool Robot::FacingWest() const { + return position_.orientation == Orientation::kWest; +} + +bool Robot::NotFacingWest() const { return !FacingWest(); } + +void Robot::Finish() { + if (finished_) return; + finished_ = true; + if (enable_animations_) { + image_.ShowUntilClosed("Karel's World"); + } +} + +Orientation Robot::GetOrientation() const { return position_.orientation; } + +int Robot::GetXPosition() const { return position_.x + 1; } + +int Robot::GetYPosition() const { return y_dimen_ - position_.y; } + +int Robot::GetNumBeepersInBag() const { return beeper_count_; } + +const Cell& Robot::GetCell(int x, int y) const { + return world_[x - 1][y_dimen_ - y]; +} + +RobotError Robot::GetError() const { return error_; } + +void Robot::Show(int duration) { + if (finished_) return; + if (enable_animations_) { + image_.ShowForMs(duration / speed_, "Karel's World"); + } +} + +void Robot::Error(RobotError error) { + error_ = error; + std::string message = "Error: "; + switch (error) { + case kNoError: + return; + case kCannotMoveNorth: + message += " Cannot move north"; + break; + case kCannotMoveEast: + message += " Cannot move east"; + break; + case kCannotMoveSouth: + message += " Cannot move south"; + break; + case kCannotMoveWest: + message += " Cannot move west"; + break; + case kCannotPickBeeper: + message += "Cannot pick beeper\n(No beepers present)"; + break; + case kCannotPutBeeper: + message += " Cannot put beeper\n(No beepers in bag)"; + break; + } + std::cout << message << std::endl << std::flush; + int approx_width = 25 * kErrorFontSize / 4; + int text_x = std::max(2, image_.GetWidth() / 2 - approx_width); + int text_y = image_.GetHeight() / 2 - kErrorFontSize / 2; + image_.DrawText(text_x - 2, text_y - 2, message, + kErrorFontSize, kWhite); + image_.DrawText(text_x + 2, text_y - 2, message, + kErrorFontSize, kWhite); + image_.DrawText(text_x - 2, text_y + 2, message, + kErrorFontSize, kWhite); + image_.DrawText(text_x + 2, text_y + 2, message, + kErrorFontSize, kWhite); + image_.DrawText(text_x, text_y, message, kErrorFontSize, + kErrorColor); + Finish(); +} + +bool Robot::DirectionIsClear(Orientation orientation) const { + switch (orientation) { + case Orientation::kNorth: + if (position_.y == 0) { + return false; + } else if (world_[position_.x][position_.y].HasNorthWall() || + world_[position_.x][position_.y - 1].HasSouthWall()) { + return false; + } else { + return true; + } + break; + case Orientation::kEast: + if (position_.x == x_dimen_ - 1) { + return false; + } else if (world_[position_.x][position_.y].HasEastWall() || + world_[position_.x + 1][position_.y].HasWestWall()) { + return false; + } else { + return true; + } + break; + case Orientation::kSouth: + if (position_.y == y_dimen_ - 1) { + return false; + } else if (world_[position_.x][position_.y].HasSouthWall() || + world_[position_.x][position_.y + 1].HasNorthWall()) { + return false; + } else { + return true; + } + break; + case Orientation::kWest: + if (position_.x == 0) { + return false; + } else if (world_[position_.x][position_.y].HasWestWall() || + world_[position_.x - 1][position_.y].HasEastWall()) { + return false; + } else { + return true; + } + break; + } +} + +void Robot::DrawWorld() { + image_.DrawRectangle(0, 0, x_dimen_ * pxPerCell, y_dimen_ * pxPerCell, + kWhite); + for (int i = 0; i <= y_dimen_; i++) { + // Draw horizontal lines and indexes. + int x = pxPerCell * x_dimen_ - 1; + int y = i * pxPerCell; + image_.DrawLine(0, y, x, y, kGridColor, kWallThickness); + if (i < y_dimen_) { + image_.DrawText(x + fontSize / 2, y + (pxPerCell - fontSize) / 2, + std::to_string(i + 1), fontSize, kWallColor); + } + } + for (int i = 0; i <= x_dimen_; i++) { + // Draw vertical lines and indexes. + int x = i * pxPerCell; + int y = pxPerCell * y_dimen_ - 1; + image_.DrawLine(x, 0, x, y, kGridColor, kWallThickness); + if (i < x_dimen_) { + image_.DrawText(x + (pxPerCell - fontSize) / 2, y + fontSize / 2, + std::to_string(i + 1), fontSize, kWallColor); + } + } + for (int i = 0; i < x_dimen_; i++) { + for (int j = 0; j < y_dimen_; j++) { + int x_center = i * pxPerCell + pxPerCell / 2; + int y_center = j * pxPerCell + pxPerCell / 2; + // Draw the little plus at the center of the cell. + image_.DrawLine(x_center - markSize / 2, y_center, + x_center + markSize / 2, y_center, markColor, + kWallThickness); + image_.DrawLine(x_center, y_center - markSize / 2, x_center, + y_center + markSize / 2, markColor, kWallThickness); + Cell& cell = world_[i][j]; + if (cell.GetNumBeepers() > 0) { + // Draw the beepers. Beepers are stacked so you can't tell if there's + // more than one in a stack. + // trig to get diamonds from thick lines! + double line_size = sqrt((beeperSize / 2) * (beeperSize / 2) / 2); + int inner_beeper_size = beeperSize - kWallThickness * 2; + double inner_line_size = + sqrt((inner_beeper_size / 2) * (inner_beeper_size / 2) / 2); + image_.DrawLine(x_center - line_size, y_center - line_size, + x_center + line_size, y_center + line_size, kWallColor, + beeperSize); + image_.DrawLine(x_center - inner_line_size, y_center - inner_line_size, + x_center + inner_line_size, y_center + inner_line_size, + innerBeeperColor, inner_beeper_size); + } + // Draw the walls. + if (cell.HasNorthWall()) { + image_.DrawLine(i * pxPerCell, j * pxPerCell, (i + 1) * pxPerCell - 1, + j * pxPerCell, kWallColor, kWallThickness); + } + if (cell.HasSouthWall()) { + image_.DrawLine(i * pxPerCell, (j + 1) * pxPerCell - 1, + (i + 1) * pxPerCell - 1, (j + 1) * pxPerCell - 1, + kWallColor, kWallThickness); + } + if (cell.HasWestWall()) { + image_.DrawLine(i * pxPerCell, j * pxPerCell, i * pxPerCell, + (j + 1) * pxPerCell - 1, kWallColor, kWallThickness); + } + if (cell.HasEastWall()) { + image_.DrawLine((i + 1) * pxPerCell - 1, j * pxPerCell, + (i + 1) * pxPerCell - 1, (j + 1) * pxPerCell - 1, + kWallColor, kWallThickness); + } + } + } +} + +void Robot::DrawRobot() { + // Center in the cell. + DrawRobot(position_.x * pxPerCell + pxPerCell / 2, + position_.y * pxPerCell + pxPerCell / 2); +} + +// pixel_x and pixel_y are the center of the cell in pixels. +void Robot::DrawRobot(int pixel_x, int pixel_y) { + image_.DrawRectangle(pixel_x - robotSize / 2, pixel_y - robotSize / 2, + robotSize, robotSize, karelColor); + switch (position_.orientation) { + case Orientation::kNorth: + image_.DrawCircle(pixel_x, + pixel_y - robotSize / 2 + eyeSize / 2 + eyeOffset, + eyeSize, kWhite); + image_.DrawCircle(pixel_x, pixel_y + eyeOffset, eyeSize, kWhite); + image_.DrawCircle(pixel_x, pixel_y - robotSize / 2 + eyeSize / 2, eyeSize, + eyeColor); + image_.DrawLine(pixel_x + robotSize / 2, pixel_y - legLength, + pixel_x + robotSize / 2 + legLength, pixel_y - legLength, + limbColor, limbWidth); + image_.DrawLine(pixel_x + robotSize / 2, pixel_y + legLength, + pixel_x + robotSize / 2 + legLength, pixel_y + legLength, + limbColor, limbWidth); + break; + case Orientation::kEast: + image_.DrawCircle(pixel_x - eyeOffset, pixel_y, eyeSize, kWhite); + image_.DrawCircle(pixel_x + robotSize / 2 - eyeSize / 2 - eyeOffset, + pixel_y, eyeSize, kWhite); + image_.DrawCircle(pixel_x + robotSize / 2 - eyeSize / 2, pixel_y, eyeSize, + eyeColor); + image_.DrawLine(pixel_x - legLength, pixel_y + robotSize / 2, + pixel_x - legLength, pixel_y + robotSize / 2 + legLength, + limbColor, limbWidth); + image_.DrawLine(pixel_x + legLength, pixel_y + robotSize / 2, + pixel_x + legLength, pixel_y + robotSize / 2 + legLength, + limbColor, limbWidth); + break; + case Orientation::kSouth: + image_.DrawCircle(pixel_x, + pixel_y + robotSize / 2 - eyeSize / 2 - eyeOffset, + eyeSize, kWhite); + image_.DrawCircle(pixel_x, pixel_y - eyeOffset, eyeSize, kWhite); + image_.DrawCircle(pixel_x, pixel_y + robotSize / 2 - eyeSize / 2, eyeSize, + eyeColor); + image_.DrawLine(pixel_x - robotSize / 2, pixel_y - legLength, + pixel_x - robotSize / 2 - legLength, pixel_y - legLength, + limbColor, limbWidth); + image_.DrawLine(pixel_x - robotSize / 2, pixel_y + legLength, + pixel_x - robotSize / 2 - legLength, pixel_y + legLength, + limbColor, limbWidth); + break; + case Orientation::kWest: + image_.DrawCircle(pixel_x + eyeOffset, pixel_y, eyeSize, kWhite); + image_.DrawCircle(pixel_x - robotSize / 2 + eyeSize / 2 + eyeOffset, + pixel_y, eyeSize, kWhite); + image_.DrawCircle(pixel_x - robotSize / 2 + eyeSize / 2, pixel_y, eyeSize, + eyeColor); + image_.DrawLine(pixel_x - legLength, pixel_y - robotSize / 2, + pixel_x - legLength, pixel_y - robotSize / 2 - legLength, + limbColor, limbWidth); + image_.DrawLine(pixel_x + legLength, pixel_y - robotSize / 2, + pixel_x + legLength, pixel_y - robotSize / 2 - legLength, + limbColor, limbWidth); + break; + } + image_.DrawCircle(pixel_x, pixel_y, eyeSize, eyeColor); +} + +void Robot::AnimateMove(int next_x, int next_y) { + int steps = enable_animations_ ? kNumAnimationSteps : 0; + for (int i = 1; i <= steps; i++) { + DrawWorld(); + double fraction = i * 1.0 / steps; + double x = position_.x * (1 - fraction) + next_x * fraction; + double y = position_.y * (1 - fraction) + next_y * fraction; + DrawRobot(x * pxPerCell + pxPerCell / 2, y * pxPerCell + pxPerCell / 2); + Show(kShortDuration); + } + position_.x = next_x; + position_.y = next_y; + Show(kLongDuration); +} + +// Note that the orientation is not populated. This is just a helper to +// get the x and y position from a file with the next items in the stream +// being (x, y) +PositionAndOrientation Robot::ParsePosition(std::fstream& file) const { + char open_paren, comma, closed_paren; + int x, y; + if (!(file >> open_paren >> x >> comma >> y >> closed_paren)) { + throw std::string("Error reading position"); + } + PositionAndOrientation result; + // Convert y in the file to y on-screen. In the file, (1, 1) is the + // bottom left corner. + // In Karel coordinates, that's (0, y_dimen - 1). + result.y = y_dimen_ - y; + result.x = x - 1; + return result; +} + +// Helper to get orientation of the form, `(x, y) direction`, for example, +// (3, 7) East +// Direction may be lower-case or have an uppercase first letter. +PositionAndOrientation Robot::ParsePositionAndOrientation( + std::fstream& file) const { + PositionAndOrientation result = ParsePosition(file); + std::string direction; + if (!(file >> direction)) { + throw std::string("Error reading orientation"); + } + // Ensure the first character is lower cased. + direction[0] = tolower(direction[0]); + if (direction == "north") { + result.orientation = Orientation::kNorth; + } else if (direction == "east") { + result.orientation = Orientation::kEast; + } else if (direction == "south") { + result.orientation = Orientation::kSouth; + } else if (direction == "west") { + result.orientation = Orientation::kWest; + } else { + throw std::string("Unknown orientation " + direction); + } + return result; +} + +} // namespace karel diff --git a/karel/src/robot.h b/karel/src/robot.h new file mode 100644 index 0000000..48780ff --- /dev/null +++ b/karel/src/robot.h @@ -0,0 +1,195 @@ +#include + +#include +#include +#include +#include + +#include "../../graphics/image.h" +#include "cell.h" +#include "orientation.h" +#include "error.h" + +#ifndef ROBOT_H +#define ROBOT_H + +namespace karel { + +class Robot { + public: + /** + * Get the Robot singleton. Initializes it with default values if it isn't + * already initialized. + */ + static karel::Robot& GetInstance(); + + /** + * Get the Robot singleton and intialize it from a file. + */ + static karel::Robot& InitializeInstance(std::string filename, + bool enable_graphics = true); + + // Disallow copy and assign. + Robot(const Robot&) = delete; + karel::Robot& operator=(const Robot&) = delete; + + /** + * Move Karel forward one step. Results in an error if Karel cannot move + * forward. + */ + void Move(); + + void TurnLeft(); + + void PutBeeper(); + + void PickBeeper(); + + bool HasBeepersInBag() const; + + bool NoBeepersInBag() const; + + bool BeepersPresent() const; + + bool NoBeepersPresent() const; + + bool FrontIsClear() const; + + bool FrontIsBlocked() const; + + bool LeftIsClear() const; + + bool LeftIsBlocked() const; + + bool RightIsClear() const; + + bool RightIsBlocked() const; + + bool FacingNorth() const; + + bool NotFacingNorth() const; + + bool FacingEast() const; + + bool NotFacingEast() const; + + bool FacingSouth() const; + + bool NotFacingSouth() const; + + bool FacingWest() const; + + bool NotFacingWest() const; + + void Finish(); + + // Methods for tests. Tests should access robot with GetInstance + // and may inspect its state with these methods. + + /** + * Gets the orientation that Karel is facing. May be simpler to use this in + * tests than Facing* functions. + */ + Orientation GetOrientation() const; + + /** + * Gets the X position with respect to the grid coordinates. 1 is the + * left-most cell. + */ + int GetXPosition() const; + + /** + * Gets the Y position with respect to the grid coordinates. 1 is the bottom + * cell. + */ + int GetYPosition() const; + + /** + * Gets the total number of beepers in Karel's bag. + */ + int GetNumBeepersInBag() const; + + /** + * Gets the current grid. Takes in grid coordinates, where (1, 1) is the + * bottom left cell. + */ + const Cell& GetCell(int x, int y) const; + + /** + * Returns the robot's current error state or kNoError if it has none. + */ + RobotError GetError() const; + + private: + // Private constructor: Robot can only be accessed with GetInstance. + Robot(); + + // Singleton. + static karel::Robot& PrivateGetInstance(); + + /** + * Loads a Karel world from a file, or if |filename| is the empty string loads + * a default world with Karel in a default position. + */ + void Initialize(std::string filename, bool enable_graphics); + + void Show(int duration); + + void Error(RobotError error); + + bool DirectionIsClear(Orientation orientation) const; + + void DrawWorld(); + + void DrawRobot(); + + /** + * Draws Karel at a location on the image. |pixel_x| and |pixel_y| are the + * center of the cell in pixels. + */ + void DrawRobot(int pixel_x, int pixel_y); + + void AnimateMove(int next_x, int next_y); + + // Note that the orientation is not populated. This is just a helper to + // get the x and y position from a file with the next items in the stream + // being (x, y) + PositionAndOrientation ParsePosition(std::fstream& file) const; + + // Helper to get orientation of the form, `(x, y) direction`, for example, + // (3, 7) East + // Direction may be lower-case or have an uppercase first letter. + PositionAndOrientation ParsePositionAndOrientation(std::fstream& file) const; + + // Whether animations are enabled. They should probably be disabled for + // testing. + bool enable_animations_ = true; + + // Underlying image. + graphics::Image image_; + + // Grid dimensions. + int x_dimen_; + int y_dimen_; + + // Karel's position and orientation. + PositionAndOrientation position_; + + // Karel's beeper bag. + int beeper_count_ = 0; + + // The cells in the world. + std::vector> world_; + + // Whether the world has been initialized. It will not re-initialize. + bool initialized_ = false; + bool finished_ = false; + RobotError error_ = RobotError::kNoError; + + // Speed multiplier for animation. + double speed_ = 1.0; +}; + +} // namespace karel + +#endif // ROBOT_H diff --git a/karel/test.cc b/karel/test.cc index b2cf412..ab5bbc6 100644 --- a/karel/test.cc +++ b/karel/test.cc @@ -1,13 +1,13 @@ #include "karel.h" void KarelProgram() { + TurnLeft(); Move(); + PickBeeper(); Move(); Move(); - TurnLeft(); Move(); Move(); - PickBeeper(); Move(); PutBeeper(); PickBeeper(); @@ -20,8 +20,6 @@ void KarelProgram() { int main() { LoadWorld("worlds/CollectNewspaperKarel.w"); - // LoadWorld("worlds/8x8.w"); - // LoadWorld("worlds/StoneMasonKarel.w"); KarelProgram(); Finish(); return 0; diff --git a/karel/worlds/2x1.w b/karel/worlds/2x1.w new file mode 100644 index 0000000..7a09778 --- /dev/null +++ b/karel/worlds/2x1.w @@ -0,0 +1,4 @@ +Dimension: (2, 1) +Karel: (1, 1) east +BeeperBag: INFINITE +Speed: 0.75 diff --git a/karel/worlds/MidpointFindingKarel.w b/karel/worlds/MidpointFindingKarel.w new file mode 100644 index 0000000..914d87e --- /dev/null +++ b/karel/worlds/MidpointFindingKarel.w @@ -0,0 +1,4 @@ +Dimension: (9, 9) +BeeperBag: INFINITE +Karel: (1, 1) East +Speed: 0.50 diff --git a/karel/worlds/SampleQuad2.w b/karel/worlds/SampleQuad2.w new file mode 100644 index 0000000..3382e46 --- /dev/null +++ b/karel/worlds/SampleQuad2.w @@ -0,0 +1,35 @@ +Dimension: (13, 9) +Beeper: (1, 1) 1 +Beeper: (1, 2) 1 +Wall: (1, 4) South +Wall: (2, 4) West +Wall: (2, 5) South +Wall: (3, 4) West +Wall: (3, 4) South +Wall: (4, 4) West +Wall: (4, 5) South +Beeper: (5, 1) 1 +Wall: (5, 5) West +Beeper: (5, 5) 1 +Wall: (5, 6) South +Wall: (6, 5) West +Wall: (6, 5) South +Wall: (7, 4) West +Wall: (7, 4) South +Wall: (8, 3) West +Wall: (8, 3) South +Wall: (9, 2) West +Wall: (9, 2) South +Wall: (10, 2) West +Wall: (10, 3) South +Wall: (11, 3) West +Wall: (11, 4) South +Wall: (12, 4) West +Wall: (12, 5) South +Beeper: (13, 1) 1 +Beeper: (13, 3) 1 +Wall: (13, 4) West +Wall: (13, 4) South +BeeperBag: INFINITE +Karel: (1, 1) East +Speed: 0.5 From 40b2e826b715c495e7e26b1473199fa35ee0088c Mon Sep 17 00:00:00 2001 From: Katie Dektar Date: Mon, 7 Dec 2020 11:18:33 -0800 Subject: [PATCH 24/40] Add to README and some unittest --- .github/workflows/c-cpp.yml | 3 + .gitignore | 1 + README.md | 18 +- karel/README.md | 97 ++++++++ karel/karel.cc | 6 + karel/karel.h | 6 + karel/src/cell.h | 8 +- karel/src/error.h | 6 + karel/src/orientation.h | 6 + karel/src/robot.cc | 52 +++-- karel/src/robot.h | 44 +++- karel/src/test/Makefile | 48 ++++ karel/src/test/karel_unittest.cc | 216 ++++++++++++++++++ karel/{ => src/test}/worlds/1x8.w | 0 karel/{ => src/test}/worlds/2x1.w | 0 karel/{ => src/test}/worlds/8x1.w | 0 karel/{ => src/test}/worlds/8x8.w | 0 .../test}/worlds/CollectNewspaperKarel.w | 0 .../test}/worlds/MidpointFindingKarel.w | 0 karel/{ => src/test}/worlds/SampleQuad2.w | 0 karel/{ => src/test}/worlds/StoneMasonKarel.w | 0 karel/test.cc | 13 +- 22 files changed, 488 insertions(+), 36 deletions(-) create mode 100644 karel/README.md create mode 100644 karel/src/test/Makefile create mode 100644 karel/src/test/karel_unittest.cc rename karel/{ => src/test}/worlds/1x8.w (100%) rename karel/{ => src/test}/worlds/2x1.w (100%) rename karel/{ => src/test}/worlds/8x1.w (100%) rename karel/{ => src/test}/worlds/8x8.w (100%) rename karel/{ => src/test}/worlds/CollectNewspaperKarel.w (100%) rename karel/{ => src/test}/worlds/MidpointFindingKarel.w (100%) rename karel/{ => src/test}/worlds/SampleQuad2.w (100%) rename karel/{ => src/test}/worlds/StoneMasonKarel.w (100%) diff --git a/.github/workflows/c-cpp.yml b/.github/workflows/c-cpp.yml index cdfa76f..7b1bc32 100644 --- a/.github/workflows/c-cpp.yml +++ b/.github/workflows/c-cpp.yml @@ -21,3 +21,6 @@ jobs: - name: make image_unittest run: make image_unittest working-directory: graphics/test + - name: make karel_unittest + run: make karel_unittest + working-directory: karel/src/test diff --git a/.gitignore b/.gitignore index a684e47..0ece1af 100644 --- a/.gitignore +++ b/.gitignore @@ -2,3 +2,4 @@ graphics/test/image_unittest graphics/test/*.bmp !graphics/test/example_bmp.bmp +karel/src/test/karel_unittest diff --git a/README.md b/README.md index ea844dd..0f8426a 100644 --- a/README.md +++ b/README.md @@ -2,15 +2,27 @@ Libraries for student C++ code available under the MIT license. -## Graphics +## Graphics: Image library -graphics/image.h can be used to create, view, load and save images. Example: +``graphics/image.h`` can be used to create, view, load and save images. Example: ![example fractal tree](graphics/test/example_fractal_tree.png) +``graphics/image_event.h`` allows for interactive graphical programs with animation and mouse event handling. + +### Usage + +Learn more about how to use the C++ Utils graphics class in this [interactive tutorial](https://lab.cs50.io/ILXL-guides/intro-to-graphics). + +## Karel the Robot in C++ + +Karel the Robot is a gentle introductory programming language created by [Dr. Richard Pattis](https://www.ics.uci.edu/~pattis/) in [*Karel the Robot: A Gentle Introduction to The Art of Programming*](https://www.google.com/books/edition/_/ghcZAQAAIAAJ?hl=en&gbpv=1). The Karel language emphasizes logic while hiding tricky syntax, allowing anyone to begin making exciting graphical programs with very little background. + +To create graphical Karel the Robot programs in C++, include ``karel/karel.h``. + ### Usage -Learn more about how to C++ Utils graphics class on [ILXL-Guides](https://github.com/ILXL-guides/intro-to-graphics). +(TODO): Learn more about how to use the C++ Utils Karel the Robot functions in this [interactive tutorial](https://github.com/ILXL-guides/intro-to-karel) ## For developers and instructors diff --git a/karel/README.md b/karel/README.md new file mode 100644 index 0000000..436ceae --- /dev/null +++ b/karel/README.md @@ -0,0 +1,97 @@ +# Karel the Robot in C++ + +TODO: Port README to a ILXL guide and the CPPUtils wiki. + +## History + +Karel the Robot is a gentle introductory programming language created by [Dr. Richard Pattis](https://www.ics.uci.edu/~pattis/) in [*Karel the Robot: A Gentle Introduction to The Art of Programming*](https://www.google.com/books/edition/_/ghcZAQAAIAAJ?hl=en&gbpv=1). The Karel language emphasizes logic while hiding tricky syntax, allowing students to begin making exciting graphical programs with very little background. + +Karel is named "after the Czech playwright Karel Čapek, whose 1923 play R.U.R. (Rossum’s Universal Robots) gave the word robot to the English language." ([Karel Reader](https://web.stanford.edu/class/archive/cs/cs106a/cs106a.1194/karelReader/en/chapter1.html)) + +This C++ version of Karel the Robot was created with permission from Dr. Pattis. + +## Overview + +Karel lives in a two-dimensional grid where (1, 1) is at the bottom left corner. Karel has a position and an orientation in the grid (north, east, south or west). + +Each square of the grid may contain one or more beepers, or no beepers at all. Karel has a bag of beepers which may be empty or may contain many or even infinite beepers. + +Karel can move one cell and turn left. Karel can put down a beeper or pick up a beeper. In addition, Karel is able to check state of the area around themselves. + +Cells may be separated by walls. Karel cannot move through walls or off the edge of the world. + +Karel has four actions: + +```cpp +void Move(); +void TurnLeft(); +void PutBeeper(); +void PickBeeper(); +``` + +Karel has several booleans for getting robot state: +```cpp +bool FrontIsClear(); +bool FrontIsBlocked(); +bool LeftIsClear(); +bool LeftIsBlocked(); +bool RightIsClear(); +bool RightIsBlocked(); +bool HasBeepersInBag(); +bool NoBeepersInBag(); +bool BeepersPresent(); +bool NoBeepersPresent(); +bool FacingNorth(); +bool NotFacingNorth(); +bool FacingEast(); +bool NotFacingEast(); +bool FacingSouth(); +bool NotFacingSouth(); +bool FacingWest(); +bool NotFacingWest(); +``` + +``robot.h`` provides a Karel the Robot implementation in C++. This is functional programming: simply ``#include "cpputils/karel/karel.h"`` and call the Karel functions in the global namespace. + +### Building + +Compile (from the directory containing cpputils) with: + +``clang++ -std=c++17 main.cc cpputils/karel/karel.cc cpputils/karel/src/robot.cc cpputils/graphics/image.cc -o main -lm -lX11 -lpthread`` + +A few more flags are needed in Mac. + +## For instructors + +Instructors should call ``LoadWorld`` before student code and ``Finish`` after. + +```cpp +void LoadWorld(std::string filename); +void Finish(); +``` + +### World files + +Same as Stanford 106A. Dimension must be the first line. + +### Unit testing + +See ``src/test/karel_unittest.cc`` + +Must get robot instance with enable animations set to false -- so unittest shouldn't run over code that does Setup (and maybe not Finish either). Should just run over student functions. + +### Example CS1 course structure with Karel + +first weeks: +`make build` +karel: + logic + vars (ints) + loops & ifs + functions --> TurnRight() { TurnLeft(); TurnLeft(); TurnLeft(); } + +later weeks: +clang++ main.cc -o main +doubles +vectors +strings diff --git a/karel/karel.cc b/karel/karel.cc index d149ad3..0ec68cf 100644 --- a/karel/karel.cc +++ b/karel/karel.cc @@ -1,3 +1,9 @@ +// Copyright 2020 Paul Salvador Inventado and Google LLC +// +// Use of this source code is governed by an MIT-style +// license that can be found in the LICENSE file or at +// https://opensource.org/licenses/MIT. + #include "karel.h" #include "src/robot.h" diff --git a/karel/karel.h b/karel/karel.h index d0ac118..dc7405e 100644 --- a/karel/karel.h +++ b/karel/karel.h @@ -1,3 +1,9 @@ +// Copyright 2020 Paul Salvador Inventado and Google LLC +// +// Use of this source code is governed by an MIT-style +// license that can be found in the LICENSE file or at +// https://opensource.org/licenses/MIT. + #include void Move(); diff --git a/karel/src/cell.h b/karel/src/cell.h index 95f0b4b..976dd89 100644 --- a/karel/src/cell.h +++ b/karel/src/cell.h @@ -1,3 +1,9 @@ +// Copyright 2020 Paul Salvador Inventado and Google LLC +// +// Use of this source code is governed by an MIT-style +// license that can be found in the LICENSE file or at +// https://opensource.org/licenses/MIT. + #include "orientation.h" #ifndef CELL_H @@ -33,7 +39,7 @@ class Cell { } private: - bool num_beepers_ = 0; + int num_beepers_ = 0; bool north_wall_ = false; bool east_wall_ = false; bool south_wall_ = false; diff --git a/karel/src/error.h b/karel/src/error.h index 0432812..e5df255 100644 --- a/karel/src/error.h +++ b/karel/src/error.h @@ -1,3 +1,9 @@ +// Copyright 2020 Paul Salvador Inventado and Google LLC +// +// Use of this source code is governed by an MIT-style +// license that can be found in the LICENSE file or at +// https://opensource.org/licenses/MIT. + #include "orientation.h" #ifndef ERROR_H diff --git a/karel/src/orientation.h b/karel/src/orientation.h index 979f263..c12b784 100644 --- a/karel/src/orientation.h +++ b/karel/src/orientation.h @@ -1,3 +1,9 @@ +// Copyright 2020 Paul Salvador Inventado and Google LLC +// +// Use of this source code is governed by an MIT-style +// license that can be found in the LICENSE file or at +// https://opensource.org/licenses/MIT. + #ifndef ORIENTATION_H #define ORIENTATION_H diff --git a/karel/src/robot.cc b/karel/src/robot.cc index 5412f09..414e2a8 100644 --- a/karel/src/robot.cc +++ b/karel/src/robot.cc @@ -1,3 +1,9 @@ +// Copyright 2020 Paul Salvador Inventado and Google LLC +// +// Use of this source code is governed by an MIT-style +// license that can be found in the LICENSE file or at +// https://opensource.org/licenses/MIT. + #include "robot.h" #include @@ -12,11 +18,8 @@ #include "error.h" #include "orientation.h" -// TODO: Finish shouldn't showuntilclosed in testing. -// Testing should have a non-graphical way to go. -// Save to file +// TODO: Save to image file (maybe for testing) // document -// phew namespace karel { @@ -72,25 +75,27 @@ karel::Robot& Robot::PrivateGetInstance() { } // static. -karel::Robot& Robot::GetInstance() { +karel::Robot& Robot::GetInstance(bool enable_graphics, bool force_initialize) { karel::Robot& instance = PrivateGetInstance(); - instance.Initialize("", /* enable graphics */ true); + instance.Initialize("", enable_graphics, force_initialize); return instance; } // Get the Robot singleton and intialize it from a file. // static. karel::Robot& Robot::InitializeInstance(std::string filename, - bool enable_graphics) { + bool enable_graphics, bool force_initialize) { karel::Robot& instance = PrivateGetInstance(); - instance.Initialize(filename, enable_graphics); + instance.Initialize(filename, enable_graphics, force_initialize); return instance; } -void Robot::Initialize(std::string filename, bool enable_graphics) { - // Ensure only intitialized once. - if (initialized_) return; +void Robot::Initialize(std::string filename, bool enable_graphics, bool force_initialize) { + // Ensure only intitialized once unless |force_initialize| is true. + if (initialized_ && !force_initialize) return; initialized_ = true; + error_ = RobotError::kNoError; + finished_ = false; enable_animations_ = enable_graphics; @@ -106,10 +111,14 @@ void Robot::Initialize(std::string filename, bool enable_graphics) { } // Nearly infinite beepers. beeper_count_ = std::numeric_limits::max(); - PositionAndOrientation position_ = {0, y_dimen_ - 1, Orientation::kEast}; + position_ = {0, kDefaultDimen - 1, Orientation::kEast}; } else { std::fstream world_file; - world_file.open(filename); + try { + world_file.open(filename); + } catch (std::ifstream::failure e) { + throw std::string("Error opening file"); + } if (!world_file.is_open()) { // TODO: Replace throwables with better error codes? throw std::string("Error opening file"); @@ -132,9 +141,9 @@ void Robot::Initialize(std::string filename, bool enable_graphics) { if (line_prefix != dimension_prefix) { throw std::string("Could not find Dimension in first line"); } - if (x_dimen_ < 2 || y_dimen_ < 1) { + if (x_dimen_ < 1 || y_dimen_ < 1) { throw std::string( - "Cannot load a world less than 2 cells wide or less than 1 cell " + "Cannot load a world less than 1 cell wide or less than 1 cell " "tall"); } for (int i = 0; i < x_dimen_; i++) { @@ -177,6 +186,9 @@ void Robot::Initialize(std::string filename, bool enable_graphics) { if (!(world_file >> speed_)) { throw std::string("Error reading Speed"); } + if (speed_ < 0) { + throw std::string("Speed must be greater than 0"); + } } else { std::cout << "unexpected token in file: " << line_prefix << std::endl << std::flush; @@ -185,7 +197,8 @@ void Robot::Initialize(std::string filename, bool enable_graphics) { } world_file.close(); } - image_.Initialize(x_dimen_ * pxPerCell + margin, + int min_width = 5 * pxPerCell + margin; + image_.Initialize(std::max(x_dimen_ * pxPerCell + margin, min_width), y_dimen_ * pxPerCell + margin); DrawWorld(); @@ -367,12 +380,16 @@ const Cell& Robot::GetCell(int x, int y) const { return world_[x - 1][y_dimen_ - y]; } +int Robot::GetWorldWidth() const { return x_dimen_; } + +int Robot::GetWorldHeight() const { return y_dimen_; } + RobotError Robot::GetError() const { return error_; } void Robot::Show(int duration) { if (finished_) return; if (enable_animations_) { - image_.ShowForMs(duration / speed_, "Karel's World"); + image_.ShowForMs(duration * speed_, "Karel's World"); } } @@ -381,6 +398,7 @@ void Robot::Error(RobotError error) { std::string message = "Error: "; switch (error) { case kNoError: + // This shouldn't happen. return; case kCannotMoveNorth: message += " Cannot move north"; diff --git a/karel/src/robot.h b/karel/src/robot.h index 48780ff..4011c4a 100644 --- a/karel/src/robot.h +++ b/karel/src/robot.h @@ -1,3 +1,9 @@ +// Copyright 2020 Paul Salvador Inventado and Google LLC +// +// Use of this source code is governed by an MIT-style +// license that can be found in the LICENSE file or at +// https://opensource.org/licenses/MIT. + #include #include @@ -7,8 +13,8 @@ #include "../../graphics/image.h" #include "cell.h" -#include "orientation.h" #include "error.h" +#include "orientation.h" #ifndef ROBOT_H #define ROBOT_H @@ -19,15 +25,19 @@ class Robot { public: /** * Get the Robot singleton. Initializes it with default values if it isn't - * already initialized. + * already initialized. Set |enable_graphics| to false for testing, which + * will disable animations. Use |force_initialize| for testing which resets + * the singleton state. */ - static karel::Robot& GetInstance(); + static karel::Robot& GetInstance(bool enable_graphics = true, bool force_initialize = false); /** - * Get the Robot singleton and intialize it from a file. + * Get the Robot singleton and intialize it from a file. Set |enable_graphics| + * to false for testing, which will disable animations. Use |force_initialize| for testing which resets + * the singleton state. */ static karel::Robot& InitializeInstance(std::string filename, - bool enable_graphics = true); + bool enable_graphics = true, bool force_initialize = false); // Disallow copy and assign. Robot(const Robot&) = delete; @@ -83,8 +93,10 @@ class Robot { void Finish(); - // Methods for tests. Tests should access robot with GetInstance - // and may inspect its state with these methods. + // + // Methods for tests. Tests should access Robot with GetInstance + // and may inspect its state with the following methods. + // /** * Gets the orientation that Karel is facing. May be simpler to use this in @@ -115,6 +127,16 @@ class Robot { */ const Cell& GetCell(int x, int y) const; + /** + * Gets the width of the current world. + */ + int GetWorldWidth() const; + + /** + * Gets the height of the current world. + */ + int GetWorldHeight() const; + /** * Returns the robot's current error state or kNoError if it has none. */ @@ -131,7 +153,7 @@ class Robot { * Loads a Karel world from a file, or if |filename| is the empty string loads * a default world with Karel in a default position. */ - void Initialize(std::string filename, bool enable_graphics); + void Initialize(std::string filename, bool enable_graphics, bool force_initialize); void Show(int duration); @@ -165,6 +187,9 @@ class Robot { // testing. bool enable_animations_ = true; + // Speed multiplier for animation. + double speed_ = 1.0; + // Underlying image. graphics::Image image_; @@ -185,9 +210,6 @@ class Robot { bool initialized_ = false; bool finished_ = false; RobotError error_ = RobotError::kNoError; - - // Speed multiplier for animation. - double speed_ = 1.0; }; } // namespace karel diff --git a/karel/src/test/Makefile b/karel/src/test/Makefile new file mode 100644 index 0000000..6cd9b29 --- /dev/null +++ b/karel/src/test/Makefile @@ -0,0 +1,48 @@ +# Copyright 2020 Paul Salvador Inventado and Google LLC +# +# Use of this source code is governed by an MIT-style +# license that can be found in the LICENSE file or at +# https://opensource.org/licenses/MIT. + +.PHONY: install_gtest karel_unittest + +OS_NAME := $(shell uname -s | tr A-Z a-z) +SHELL := /bin/bash +HAS_GTEST := $(shell echo -e "int main() { }" >> test.cc ; clang++ test.cc -o test -lgtest 2> /dev/null; echo $$?; rm -f test.cc test;) +COMPILE_FLAGS := -lm -lX11 -lpthread + +ifeq ($(OS_NAME), darwin) + COMPILE_FLAGS := -lm -lpthread -lX11 -I/usr/X11R6/include -L/usr/X11R6/lib + HAS_BREW := $(shell command -v brew 2> /dev/null) +endif + +install_gtest: +ifeq ($(HAS_GTEST),1) + @echo -e "google test not installed\n" +ifeq ($(OS_NAME), darwin) +ifndef ($(HAS_BREW)) + @echo -e "Installing brew, please provide your password when asked.\n" + @/bin/bash -c "$$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)" + @brew install coreutils + # Need to redefine the path directories otherwise this will fail the first time. +endif + @echo -e "Installing cmake. Please provide the password when asked\n" + @brew install cmake + @echo -e "\nDownloading and installing googletest\n" + @cd /tmp/; git clone https://github.com/google/googletest; cd googletest; mkdir build; cd build; cmake .. -DCMAKE_CXX_STANDARD=17; make; make install + @echo -e "Finished installing google test\n" +else +ifneq ($(shell lsb_release -sr), 20.04) + @cd /tmp/; git clone https://github.com/google/googletest.git; cd googletest; cmake CMakeLists.txt; make; sudo cp -r googletest/include/. /usr/include; sudo cp -r googlemock/include/. /usr/include; sudo cp lib/*.a /usr/lib +else + @echo -e "Installing cmake. Please provide the password when asked\n" + @sudo apt-get install cmake # install cmake + @echo -e "\nDownloading and installing googletest\n" + @sudo apt-get install libgtest-dev libgmock-dev + @echo -e "Finished installing google test\n" +endif +endif +endif + +karel_unittest: install_gtest + @clang++ -std=c++17 ../../../graphics/image.cc ../robot.cc ../../karel.cc karel_unittest.cc -o karel_unittest -pthread -lgtest $(COMPILE_FLAGS) && ./karel_unittest diff --git a/karel/src/test/karel_unittest.cc b/karel/src/test/karel_unittest.cc new file mode 100644 index 0000000..c02de63 --- /dev/null +++ b/karel/src/test/karel_unittest.cc @@ -0,0 +1,216 @@ +// Copyright 2020 Paul Salvador Inventado and Google LLC +// +// Use of this source code is governed by an MIT-style +// license that can be found in the LICENSE file or at +// https://opensource.org/licenses/MIT. + +#include "../../karel.h" + +#include +#include + +#include "../../../graphics/image.h" +#include "../cell.h" +#include "../error.h" +#include "../orientation.h" +#include "../robot.h" + +using karel::Cell; +using karel::Orientation; +using karel::Robot; +using karel::RobotError; + +// Test TODOs: +// Test walls, loading maps with walls, not walking through walls +// Test error states +// Test loading beepers +// Test putting/picking beepers not at (1, 1) + +bool IsBasicallyInfinite(int number) { + return number > std::numeric_limits::max() / 2; +} + +void CellIsEmptyWithNoWalls(const Cell& cell) { + ASSERT_EQ(0, cell.GetNumBeepers()); + ASSERT_FALSE(cell.HasNorthWall()); + ASSERT_FALSE(cell.HasEastWall()); + ASSERT_FALSE(cell.HasSouthWall()); + ASSERT_FALSE(cell.HasWestWall()); +} + +class KarelTest : public testing::Test { + public: + void SetUp() override { + // TODO. + } +}; + +TEST_F(KarelTest, GetsKarelInstance) { + Robot& r = Robot::GetInstance(/* enable animations */ false, + /* force initialize */ true); +} + +TEST_F(KarelTest, DefaultWorld) { + Robot& r = Robot::GetInstance(/* enable animations */ false, + /* force initialize */ true); + + // Default world is 10x10. + ASSERT_EQ(10, r.GetWorldWidth()); + ASSERT_EQ(10, r.GetWorldHeight()); + + // Default world has no beepers and no walls. + for (int i = 1; i <= 10; i++) { + for (int j = 1; j <= 10; j++) { + CellIsEmptyWithNoWalls(r.GetCell(i, j)); + } + } + + // Default Karel is in bottom left with infinite beepers. + ASSERT_EQ(1, r.GetXPosition()); + ASSERT_EQ(1, r.GetYPosition()); + ASSERT_EQ(Orientation::kEast, r.GetOrientation()); + ASSERT_TRUE(IsBasicallyInfinite(r.GetNumBeepersInBag())); +} + +TEST_F(KarelTest, LoadsWorld) { + Robot& r = + Robot::InitializeInstance("worlds/2x1.w", /* enable animations */ false, + /* force initialize */ true); + ASSERT_EQ(2, r.GetWorldWidth()); + ASSERT_EQ(1, r.GetWorldHeight()); + CellIsEmptyWithNoWalls(r.GetCell(1, 1)); + CellIsEmptyWithNoWalls(r.GetCell(2, 1)); + + ASSERT_EQ(1, r.GetXPosition()); + ASSERT_EQ(1, r.GetYPosition()); + ASSERT_EQ(Orientation::kEast, r.GetOrientation()); + ASSERT_TRUE(IsBasicallyInfinite(r.GetNumBeepersInBag())); +} + +TEST_F(KarelTest, PutsAndPicksBeeper) { + // Default world has no beepers, and Karel has infinite. + Robot& r = Robot::GetInstance(/* enable animations */ false, + /* force initialize */ true); + ASSERT_FALSE(BeepersPresent()); + ASSERT_EQ(0, r.GetCell(1, 1).GetNumBeepers()); + int count = 10; + for (int i = 1; i <= count; i++) { + PutBeeper(); + ASSERT_TRUE(BeepersPresent()); + EXPECT_EQ(i, r.GetCell(1, 1).GetNumBeepers()); + } + for (int i = count - 1; i >= 0; i--) { + PickBeeper(); + if (i > 0) { + ASSERT_TRUE(BeepersPresent()); + } else { + ASSERT_FALSE(BeepersPresent()); + } + EXPECT_EQ(i, r.GetCell(1, 1).GetNumBeepers()); + } +} + +TEST_F(KarelTest, TurnsLeft) { + Robot& r = Robot::GetInstance(/* enable animations */ false, + /* force initialize */ true); + int count = 10; + // Starts facing East. + for (int i = 0; i < count; i++) { + if (i % 4 == 0) { + // Facing east. + ASSERT_EQ(Orientation::kEast, r.GetOrientation()); + EXPECT_FALSE(FacingNorth()); + EXPECT_TRUE(NotFacingNorth()); + EXPECT_TRUE(FacingEast()); + EXPECT_FALSE(NotFacingEast()); + EXPECT_FALSE(FacingSouth()); + EXPECT_TRUE(NotFacingSouth()); + EXPECT_FALSE(FacingWest()); + EXPECT_TRUE(NotFacingWest()); + } else if (i % 4 == 1) { + // Facing north. + ASSERT_EQ(Orientation::kNorth, r.GetOrientation()); + EXPECT_TRUE(FacingNorth()); + EXPECT_FALSE(NotFacingNorth()); + EXPECT_FALSE(FacingEast()); + EXPECT_TRUE(NotFacingEast()); + EXPECT_FALSE(FacingSouth()); + EXPECT_TRUE(NotFacingSouth()); + EXPECT_FALSE(FacingWest()); + EXPECT_TRUE(NotFacingWest()); + } else if (i % 4 == 2) { + // Facing west. + ASSERT_EQ(Orientation::kWest, r.GetOrientation()); + EXPECT_FALSE(FacingNorth()); + EXPECT_TRUE(NotFacingNorth()); + EXPECT_FALSE(FacingEast()); + EXPECT_TRUE(NotFacingEast()); + EXPECT_FALSE(FacingSouth()); + EXPECT_TRUE(NotFacingSouth()); + EXPECT_TRUE(FacingWest()); + EXPECT_FALSE(NotFacingWest()); + } else { + // Facing south. + ASSERT_EQ(Orientation::kSouth, r.GetOrientation()); + EXPECT_FALSE(FacingNorth()); + EXPECT_TRUE(NotFacingNorth()); + EXPECT_FALSE(FacingEast()); + EXPECT_TRUE(NotFacingEast()); + EXPECT_TRUE(FacingSouth()); + EXPECT_FALSE(NotFacingSouth()); + EXPECT_FALSE(FacingWest()); + EXPECT_TRUE(NotFacingWest()); + } + TurnLeft(); + } +} + +TEST_F(KarelTest, MovesEastAndWest) { + Robot& r = + Robot::InitializeInstance("worlds/8x1.w", /* enable animations */ false, + /* force initialize */ true); + ASSERT_EQ(8, r.GetWorldWidth()); + ASSERT_EQ(1, r.GetWorldHeight()); + for (int i = 2; i <= 8; i++) { + Move(); + ASSERT_EQ(i, r.GetXPosition()); + EXPECT_EQ(1, r.GetYPosition()); + ASSERT_EQ(RobotError::kNoError, r.GetError()); + } + TurnLeft(); + TurnLeft(); + for (int i = 7; i > 0; i--) { + Move(); + ASSERT_EQ(i, r.GetXPosition()); + EXPECT_EQ(1, r.GetYPosition()); + ASSERT_EQ(RobotError::kNoError, r.GetError()); + } +} + +TEST_F(KarelTest, MovesNorthAndSouth) { + Robot& r = + Robot::InitializeInstance("worlds/1x8.w", /* enable animations */ false, + /* force initialize */ true); + ASSERT_EQ(1, r.GetWorldWidth()); + ASSERT_EQ(8, r.GetWorldHeight()); + TurnLeft(); // Face north. + for (int i = 2; i <= 8; i++) { + Move(); + ASSERT_EQ(1, r.GetXPosition()); + EXPECT_EQ(i, r.GetYPosition()); + ASSERT_EQ(RobotError::kNoError, r.GetError()); + } + TurnLeft(); + TurnLeft(); + for (int i = 7; i > 0; i--) { + Move(); + ASSERT_EQ(1, r.GetXPosition()); + EXPECT_EQ(i, r.GetYPosition()); + ASSERT_EQ(RobotError::kNoError, r.GetError()); + } +} + +int main(int argc, char** argv) { + testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} diff --git a/karel/worlds/1x8.w b/karel/src/test/worlds/1x8.w similarity index 100% rename from karel/worlds/1x8.w rename to karel/src/test/worlds/1x8.w diff --git a/karel/worlds/2x1.w b/karel/src/test/worlds/2x1.w similarity index 100% rename from karel/worlds/2x1.w rename to karel/src/test/worlds/2x1.w diff --git a/karel/worlds/8x1.w b/karel/src/test/worlds/8x1.w similarity index 100% rename from karel/worlds/8x1.w rename to karel/src/test/worlds/8x1.w diff --git a/karel/worlds/8x8.w b/karel/src/test/worlds/8x8.w similarity index 100% rename from karel/worlds/8x8.w rename to karel/src/test/worlds/8x8.w diff --git a/karel/worlds/CollectNewspaperKarel.w b/karel/src/test/worlds/CollectNewspaperKarel.w similarity index 100% rename from karel/worlds/CollectNewspaperKarel.w rename to karel/src/test/worlds/CollectNewspaperKarel.w diff --git a/karel/worlds/MidpointFindingKarel.w b/karel/src/test/worlds/MidpointFindingKarel.w similarity index 100% rename from karel/worlds/MidpointFindingKarel.w rename to karel/src/test/worlds/MidpointFindingKarel.w diff --git a/karel/worlds/SampleQuad2.w b/karel/src/test/worlds/SampleQuad2.w similarity index 100% rename from karel/worlds/SampleQuad2.w rename to karel/src/test/worlds/SampleQuad2.w diff --git a/karel/worlds/StoneMasonKarel.w b/karel/src/test/worlds/StoneMasonKarel.w similarity index 100% rename from karel/worlds/StoneMasonKarel.w rename to karel/src/test/worlds/StoneMasonKarel.w diff --git a/karel/test.cc b/karel/test.cc index ab5bbc6..4b7f555 100644 --- a/karel/test.cc +++ b/karel/test.cc @@ -1,9 +1,12 @@ +// Copyright 2020 Paul Salvador Inventado and Google LLC +// +// Use of this source code is governed by an MIT-style +// license that can be found in the LICENSE file or at +// https://opensource.org/licenses/MIT. + #include "karel.h" void KarelProgram() { - TurnLeft(); - Move(); - PickBeeper(); Move(); Move(); Move(); @@ -16,10 +19,12 @@ void KarelProgram() { PutBeeper(); TurnLeft(); Move(); + TurnLeft(); + TurnLeft(); } int main() { - LoadWorld("worlds/CollectNewspaperKarel.w"); + LoadWorld("src/test/worlds/1x8.w"); KarelProgram(); Finish(); return 0; From 42e17f77b6148216bcb8c9f4749d3eb3578c75d3 Mon Sep 17 00:00:00 2001 From: Katie Dektar Date: Mon, 7 Dec 2020 20:29:34 -0800 Subject: [PATCH 25/40] Refactor and clean-up --- karel/karel.cc | 72 ++++++------------ karel/karel.h | 114 ++++++++++++++++++++++++++--- karel/src/robot.cc | 45 +++--------- karel/src/robot.h | 121 ++++++++++++++++++++++--------- karel/src/test/karel_unittest.cc | 1 + 5 files changed, 224 insertions(+), 129 deletions(-) diff --git a/karel/karel.cc b/karel/karel.cc index 0ec68cf..2cbd515 100644 --- a/karel/karel.cc +++ b/karel/karel.cc @@ -12,7 +12,8 @@ void LoadWorld(std::string filename) { try { karel::Robot& r = karel::Robot::InitializeInstance(filename); } catch (std::string error) { - std::cout << "Error loading world file " << filename << ": \n" << error << std::endl; + std::cout << "Error loading world file " << filename << ": \n" + << error << std::endl; exit(1); } } @@ -37,97 +38,70 @@ void PickBeeper() { r.PickBeeper(); } -void Finish() { +bool HasBeepersInBag() { karel::Robot& r = karel::Robot::GetInstance(); - r.Finish(); + return r.HasBeepersInBag(); } -bool FrontIsClear() { +bool NoBeepersInBag() { return !HasBeepersInBag(); } + +bool BeepersPresent() { karel::Robot& r = karel::Robot::GetInstance(); - return r.FrontIsClear(); + return r.BeepersPresent(); } -bool FrontIsBlocked() { +bool NoBeepersPresent() { return !BeepersPresent(); } + +bool FrontIsClear() { karel::Robot& r = karel::Robot::GetInstance(); - return r.FrontIsBlocked(); + return r.FrontIsClear(); } +bool FrontIsBlocked() { return !FrontIsClear(); } + bool LeftIsClear() { karel::Robot& r = karel::Robot::GetInstance(); return r.LeftIsClear(); } -bool LeftIsBlocked() { - karel::Robot& r = karel::Robot::GetInstance(); - return r.LeftIsBlocked(); -} +bool LeftIsBlocked() { return !LeftIsClear(); } bool RightIsClear() { karel::Robot& r = karel::Robot::GetInstance(); return r.RightIsClear(); } -bool RightIsBlocked() { - karel::Robot& r = karel::Robot::GetInstance(); - return r.RightIsBlocked(); -} - -bool HasBeepersInBag() { - karel::Robot& r = karel::Robot::GetInstance(); - return r.HasBeepersInBag(); -} - -bool NoBeepersInBag() { - karel::Robot& r = karel::Robot::GetInstance(); - return r.NoBeepersInBag(); -} - -bool BeepersPresent() { - karel::Robot& r = karel::Robot::GetInstance(); - return r.BeepersPresent(); -} - -bool NoBeepersPresent() { - karel::Robot& r = karel::Robot::GetInstance(); - return r.NoBeepersPresent(); -} +bool RightIsBlocked() { return !RightIsClear(); } bool FacingNorth() { karel::Robot& r = karel::Robot::GetInstance(); return r.FacingNorth(); } -bool NotFacingNorth() { - karel::Robot& r = karel::Robot::GetInstance(); - return r.NotFacingNorth(); -} +bool NotFacingNorth() { return !FacingNorth(); } bool FacingEast() { karel::Robot& r = karel::Robot::GetInstance(); return r.FacingEast(); } -bool NotFacingEast() { - karel::Robot& r = karel::Robot::GetInstance(); - return r.NotFacingEast(); -} +bool NotFacingEast() { return !FacingEast(); } bool FacingSouth() { karel::Robot& r = karel::Robot::GetInstance(); return r.FacingSouth(); } -bool NotFacingSouth() { - karel::Robot& r = karel::Robot::GetInstance(); - return r.NotFacingSouth(); -} +bool NotFacingSouth() { return !FacingSouth(); } bool FacingWest() { karel::Robot& r = karel::Robot::GetInstance(); return r.FacingWest(); } -bool NotFacingWest() { +bool NotFacingWest() { return !FacingWest(); } + +void Finish() { karel::Robot& r = karel::Robot::GetInstance(); - return r.NotFacingWest(); + r.Finish(); } diff --git a/karel/karel.h b/karel/karel.h index dc7405e..d53d5f3 100644 --- a/karel/karel.h +++ b/karel/karel.h @@ -6,50 +6,146 @@ #include +///////////////////////////////////////////////////////// +// Methods for core Karel functionality // +// These methods allow interaction with Karel. // +///////////////////////////////////////////////////////// + +/** + * Move Karel forward one step. Results in an error if Karel cannot move + * forward because of a wall or an edge. + */ void Move(); +/** + * Turns Karel to the left. + */ void TurnLeft(); +/** + * Places a beeper from Karel's beeper bag onto the current cell where Karel + * is. Results in an error if Karel has no beepers left in their bag. + */ void PutBeeper(); +/** + * Picks a beeper from the cell where Karel is standing and places it in + * their beeper bag. Results in an error if there are no beepers in Karel's + * current cell. + */ void PickBeeper(); +/** + * Returns true if Karel has beepers in their bag, or false otherwise. + */ +bool HasBeepersInBag(); + +/** + * Returns true if Karel has no beepers in their bag, or true otherwise. + */ +bool NoBeepersInBag(); + +/** + * Returns true if Karel is standing on a cell with at least one beeper, or + * false otherwise. + */ +bool BeepersPresent(); + +/** + * Returns true if Karel is standing on a cell no beepers at all, or + * false otherwise. + */ +bool NoBeepersPresent(); + +/** + * Returns true if there is no wall nor edge in front of Karel and they could + * move forward, or false otherwise. + */ bool FrontIsClear(); +/** + * Returns true if there is a wall or edge in front of Karel or false otherwise. + */ bool FrontIsBlocked(); +/** + * Returns true if there is no wall nor edge directly to Karel's left, or false + * otherwise. + */ bool LeftIsClear(); +/** + * Returns true if there is a wall or edge directly to Karel's left, or false + * otherwise. + */ bool LeftIsBlocked(); +/** + * Returns true if there is no wall nor edge directly to Karel's right, or false + * otherwise. + */ bool RightIsClear(); +/** + * Returns true if there is a wall or edge directly to Karel's right or false + * otherwise. + */ bool RightIsBlocked(); -bool HasBeepersInBag(); - -bool NoBeepersInBag(); - -bool BeepersPresent(); - -bool NoBeepersPresent(); - +/** + * Returns true if Karel is facing north or false otherwise. + */ bool FacingNorth(); +/** + * Returns true if Karel is not facing north or false otherwise. + */ bool NotFacingNorth(); +/** + * Returns true if Karel is facing east or false otherwise. + */ bool FacingEast(); +/** + * Returns true if Karel is not facing east or false otherwise. + */ bool NotFacingEast(); +/** + * Returns true if Karel is facing south or false otherwise. + */ bool FacingSouth(); +/** + * Returns true if Karel is facing south or false otherwise. + */ bool NotFacingSouth(); +/** + * Returns true if Karel is facing west or false otherwise. + */ bool FacingWest(); +/** + * Returns true if Karel is not facing west or false otherwise. + */ bool NotFacingWest(); -// For the instructor +///////////////////////////////////////////////////////////////////////////// +// Methods for setting up a Karel program. // +// Instructors may use these methods wrapping student's Karel commands. // +///////////////////////////////////////////////////////////////////////////// + +/** + * Loads a Karel world from a file. + * If this is not the first Karel function called a default world will be + * created instead and this will have no effect. + */ void LoadWorld(std::string filename); + +/** + * Completes a Karel program. Continues to show the image but will not + * do any more actions. + */ void Finish(); diff --git a/karel/src/robot.cc b/karel/src/robot.cc index 414e2a8..7bbc2a1 100644 --- a/karel/src/robot.cc +++ b/karel/src/robot.cc @@ -84,13 +84,15 @@ karel::Robot& Robot::GetInstance(bool enable_graphics, bool force_initialize) { // Get the Robot singleton and intialize it from a file. // static. karel::Robot& Robot::InitializeInstance(std::string filename, - bool enable_graphics, bool force_initialize) { + bool enable_graphics, + bool force_initialize) { karel::Robot& instance = PrivateGetInstance(); instance.Initialize(filename, enable_graphics, force_initialize); return instance; } -void Robot::Initialize(std::string filename, bool enable_graphics, bool force_initialize) { +void Robot::Initialize(std::string filename, bool enable_graphics, + bool force_initialize) { // Ensure only intitialized once unless |force_initialize| is true. if (initialized_ && !force_initialize) return; initialized_ = true; @@ -304,62 +306,38 @@ void Robot::PickBeeper() { bool Robot::HasBeepersInBag() const { return beeper_count_ > 0; } -bool Robot::NoBeepersInBag() const { return !HasBeepersInBag(); } - bool Robot::BeepersPresent() const { return world_[position_.x][position_.y].GetNumBeepers() > 0; } -bool Robot::NoBeepersPresent() const { return !BeepersPresent(); } - bool Robot::FrontIsClear() const { return DirectionIsClear(position_.orientation); } -bool Robot::FrontIsBlocked() const { - return !DirectionIsClear(position_.orientation); -} - bool Robot::LeftIsClear() const { return DirectionIsClear((Orientation)(((int)position_.orientation + 1) % 4)); } -bool Robot::LeftIsBlocked() const { - return !DirectionIsClear((Orientation)(((int)position_.orientation + 1) % 4)); -} - bool Robot::RightIsClear() const { return DirectionIsClear((Orientation)(((int)position_.orientation - 1) % 4)); } -bool Robot::RightIsBlocked() const { - return !DirectionIsClear((Orientation)(((int)position_.orientation - 1) % 4)); -} - bool Robot::FacingNorth() const { return position_.orientation == Orientation::kNorth; } -bool Robot::NotFacingNorth() const { return !FacingNorth(); } - bool Robot::FacingEast() const { return position_.orientation == Orientation::kEast; } -bool Robot::NotFacingEast() const { return !FacingEast(); } - bool Robot::FacingSouth() const { return position_.orientation == Orientation::kSouth; } -bool Robot::NotFacingSouth() const { return !FacingSouth(); } - bool Robot::FacingWest() const { return position_.orientation == Orientation::kWest; } -bool Robot::NotFacingWest() const { return !FacingWest(); } - void Robot::Finish() { if (finished_) return; finished_ = true; @@ -423,16 +401,11 @@ void Robot::Error(RobotError error) { int approx_width = 25 * kErrorFontSize / 4; int text_x = std::max(2, image_.GetWidth() / 2 - approx_width); int text_y = image_.GetHeight() / 2 - kErrorFontSize / 2; - image_.DrawText(text_x - 2, text_y - 2, message, - kErrorFontSize, kWhite); - image_.DrawText(text_x + 2, text_y - 2, message, - kErrorFontSize, kWhite); - image_.DrawText(text_x - 2, text_y + 2, message, - kErrorFontSize, kWhite); - image_.DrawText(text_x + 2, text_y + 2, message, - kErrorFontSize, kWhite); - image_.DrawText(text_x, text_y, message, kErrorFontSize, - kErrorColor); + image_.DrawText(text_x - 2, text_y - 2, message, kErrorFontSize, kWhite); + image_.DrawText(text_x + 2, text_y - 2, message, kErrorFontSize, kWhite); + image_.DrawText(text_x - 2, text_y + 2, message, kErrorFontSize, kWhite); + image_.DrawText(text_x + 2, text_y + 2, message, kErrorFontSize, kWhite); + image_.DrawText(text_x, text_y, message, kErrorFontSize, kErrorColor); Finish(); } diff --git a/karel/src/robot.h b/karel/src/robot.h index 4011c4a..a6c7e6d 100644 --- a/karel/src/robot.h +++ b/karel/src/robot.h @@ -29,74 +29,110 @@ class Robot { * will disable animations. Use |force_initialize| for testing which resets * the singleton state. */ - static karel::Robot& GetInstance(bool enable_graphics = true, bool force_initialize = false); + static karel::Robot& GetInstance(bool enable_graphics = true, + bool force_initialize = false); /** * Get the Robot singleton and intialize it from a file. Set |enable_graphics| - * to false for testing, which will disable animations. Use |force_initialize| for testing which resets - * the singleton state. + * to false for testing, which will disable animations. Use |force_initialize| + * for testing which resets the singleton state. */ static karel::Robot& InitializeInstance(std::string filename, - bool enable_graphics = true, bool force_initialize = false); + bool enable_graphics = true, + bool force_initialize = false); - // Disallow copy and assign. + // Disallow copy and assignment. Robot(const Robot&) = delete; karel::Robot& operator=(const Robot&) = delete; + ///////////////////////////////////////////////////////// + // Methods for core Karel functionality // + // These methods allow interaction with Karel. // + ///////////////////////////////////////////////////////// + /** * Move Karel forward one step. Results in an error if Karel cannot move - * forward. + * forward because of a wall or an edge. */ void Move(); + /** + * Turns Karel to the left. + */ void TurnLeft(); + /** + * Places a beeper from Karel's beeper bag onto the current cell where Karel + * is. Results in an error if Karel has no beepers left in their bag. + */ void PutBeeper(); + /** + * Picks a beeper from the cell where Karel is standing and places it in + * their beeper bag. Results in an error if there are no beepers in Karel's + * current cell. + */ void PickBeeper(); + /** + * Returns true if Karel has beepers in their bag, or false otherwise. + */ bool HasBeepersInBag() const; - bool NoBeepersInBag() const; - + /** + * Returns true if Karel is standing on a cell with at least one beeper, or + * false otherwise. + */ bool BeepersPresent() const; - bool NoBeepersPresent() const; - + /** + * Returns true if there is no wall nor edge in front of Karel and they could + * move forward, or false otherwise. + */ bool FrontIsClear() const; - bool FrontIsBlocked() const; - + /** + * Returns true if there is no wall nor edge directly to Karel's left, or + * false otherwise. + */ bool LeftIsClear() const; - bool LeftIsBlocked() const; - + /** + * Returns true if there is no wall nor edge directly to Karel's right, or + * false otherwise. + */ bool RightIsClear() const; - bool RightIsBlocked() const; - + /** + * Returns true if Karel is facing north or false otherwise. + */ bool FacingNorth() const; - bool NotFacingNorth() const; - + /** + * Returns true if Karel is facing east or false otherwise. + */ bool FacingEast() const; - bool NotFacingEast() const; - + /** + * Returns true if Karel is facing south or false otherwise. + */ bool FacingSouth() const; - bool NotFacingSouth() const; - + /** + * Returns true if Karel is facing west or false otherwise. + */ bool FacingWest() const; - bool NotFacingWest() const; - + /** + * Completes a Karel program. Continues to show the image but will not + * do any more actions. + */ void Finish(); - // - // Methods for tests. Tests should access Robot with GetInstance - // and may inspect its state with the following methods. - // + ///////////////////////////////////////////////////////////////////// + // Methods for tests. Tests should access Robot with GetInstance // + // and may inspect its state with the following methods. // + ///////////////////////////////////////////////////////////////////// /** * Gets the orientation that Karel is facing. May be simpler to use this in @@ -153,12 +189,22 @@ class Robot { * Loads a Karel world from a file, or if |filename| is the empty string loads * a default world with Karel in a default position. */ - void Initialize(std::string filename, bool enable_graphics, bool force_initialize); + void Initialize(std::string filename, bool enable_graphics, + bool force_initialize); + /** + * Shows karel's world, blocking for the given |duration| in milliseconds. + */ void Show(int duration); + /** + * Displays an error and finishes the program. + */ void Error(RobotError error); + /** + * Helper method to see if a compass direction is clear. + */ bool DirectionIsClear(Orientation orientation) const; void DrawWorld(); @@ -173,14 +219,19 @@ class Robot { void AnimateMove(int next_x, int next_y); - // Note that the orientation is not populated. This is just a helper to - // get the x and y position from a file with the next items in the stream - // being (x, y) + /** + * Helper method to parse position from the next item in a file stream. + * Note that the orientation is not populated. This is just a helper to + * get the x and y position from a file with the next items in the stream + * being (x, y) + */ PositionAndOrientation ParsePosition(std::fstream& file) const; - // Helper to get orientation of the form, `(x, y) direction`, for example, - // (3, 7) East - // Direction may be lower-case or have an uppercase first letter. + /** + * Helper to get orientation of the form, `(x, y) direction`, for example, + * (3, 7) East + * Direction may be lower-case or have an uppercase first letter. + */ PositionAndOrientation ParsePositionAndOrientation(std::fstream& file) const; // Whether animations are enabled. They should probably be disabled for diff --git a/karel/src/test/karel_unittest.cc b/karel/src/test/karel_unittest.cc index c02de63..3e86487 100644 --- a/karel/src/test/karel_unittest.cc +++ b/karel/src/test/karel_unittest.cc @@ -23,6 +23,7 @@ using karel::RobotError; // Test TODOs: // Test walls, loading maps with walls, not walking through walls // Test error states +// Test stops taking action after reaching an error state. // Test loading beepers // Test putting/picking beepers not at (1, 1) From 2f49bc5be7f04d16134ef29a04fdd5dc01235b7e Mon Sep 17 00:00:00 2001 From: Katie Dektar Date: Mon, 7 Dec 2020 20:30:26 -0800 Subject: [PATCH 26/40] Add Karel branch to workflow --- .github/workflows/c-cpp.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/c-cpp.yml b/.github/workflows/c-cpp.yml index 7b1bc32..3eceffa 100644 --- a/.github/workflows/c-cpp.yml +++ b/.github/workflows/c-cpp.yml @@ -2,7 +2,7 @@ name: C/C++ CI on: push: - branches: [ master, v1, v2, animation ] + branches: [ master, v1, v2, karel ] pull_request: branches: [ master ] From 0cc50bf04f6c69dd1ca430868439753c09cf15f4 Mon Sep 17 00:00:00 2001 From: Katie Dektar Date: Mon, 7 Dec 2020 20:50:35 -0800 Subject: [PATCH 27/40] Clean up demo code, update README --- README.md | 2 + karel/README.md | 68 +++++++++++++++--- karel/src/test/karel.png | Bin 0 -> 18851 bytes karel/src/test/worlds/CollectNewspaperKarel.w | 15 ---- karel/src/test/worlds/MidpointFindingKarel.w | 4 -- karel/src/test/worlds/SampleQuad2.w | 35 --------- karel/src/test/worlds/StoneMasonKarel.w | 39 ---------- karel/test.cc | 31 -------- 8 files changed, 61 insertions(+), 133 deletions(-) create mode 100644 karel/src/test/karel.png delete mode 100644 karel/src/test/worlds/CollectNewspaperKarel.w delete mode 100644 karel/src/test/worlds/MidpointFindingKarel.w delete mode 100644 karel/src/test/worlds/SampleQuad2.w delete mode 100644 karel/src/test/worlds/StoneMasonKarel.w delete mode 100644 karel/test.cc diff --git a/README.md b/README.md index 0f8426a..a52c4d6 100644 --- a/README.md +++ b/README.md @@ -18,6 +18,8 @@ Learn more about how to use the C++ Utils graphics class in this [interactive tu Karel the Robot is a gentle introductory programming language created by [Dr. Richard Pattis](https://www.ics.uci.edu/~pattis/) in [*Karel the Robot: A Gentle Introduction to The Art of Programming*](https://www.google.com/books/edition/_/ghcZAQAAIAAJ?hl=en&gbpv=1). The Karel language emphasizes logic while hiding tricky syntax, allowing anyone to begin making exciting graphical programs with very little background. +![karel the robot screenshot](karel/src/test/karel.png) + To create graphical Karel the Robot programs in C++, include ``karel/karel.h``. ### Usage diff --git a/karel/README.md b/karel/README.md index 436ceae..dec24ac 100644 --- a/karel/README.md +++ b/karel/README.md @@ -2,14 +2,6 @@ TODO: Port README to a ILXL guide and the CPPUtils wiki. -## History - -Karel the Robot is a gentle introductory programming language created by [Dr. Richard Pattis](https://www.ics.uci.edu/~pattis/) in [*Karel the Robot: A Gentle Introduction to The Art of Programming*](https://www.google.com/books/edition/_/ghcZAQAAIAAJ?hl=en&gbpv=1). The Karel language emphasizes logic while hiding tricky syntax, allowing students to begin making exciting graphical programs with very little background. - -Karel is named "after the Czech playwright Karel Čapek, whose 1923 play R.U.R. (Rossum’s Universal Robots) gave the word robot to the English language." ([Karel Reader](https://web.stanford.edu/class/archive/cs/cs106a/cs106a.1194/karelReader/en/chapter1.html)) - -This C++ version of Karel the Robot was created with permission from Dr. Pattis. - ## Overview Karel lives in a two-dimensional grid where (1, 1) is at the bottom left corner. Karel has a position and an orientation in the grid (north, east, south or west). @@ -53,11 +45,49 @@ bool NotFacingWest(); ``robot.h`` provides a Karel the Robot implementation in C++. This is functional programming: simply ``#include "cpputils/karel/karel.h"`` and call the Karel functions in the global namespace. +### Example program + +```cpp +#include "cpputils/karel/karel.h" + +void TurnRight() { + TurnLeft(); + TurnLeft(); + TurnLeft(); +} + +void KarelProgram() { + while(FrontIsClear()) { + Move(); + } + TurnRight(); + Move(); + TurnLeft(); + Move(); + PickBeeper(); + TurnLeft(); + TurnLeft(); + while(FrontIsClear()) { + Move(); + } + TurnRight(); + Move(); + TurnRight(); +} + +int main() { + LoadWorld("src/test/worlds/CollectNewspaperKarel.w"); + KarelProgram(); + Finish(); + return 0; +} +``` + ### Building Compile (from the directory containing cpputils) with: -``clang++ -std=c++17 main.cc cpputils/karel/karel.cc cpputils/karel/src/robot.cc cpputils/graphics/image.cc -o main -lm -lX11 -lpthread`` +``clang++ -std=c++17 test.cc cpputils/karel/karel.cc cpputils/karel/src/robot.cc cpputils/graphics/image.cc -o main -lm -lX11 -lpthread`` A few more flags are needed in Mac. @@ -74,6 +104,26 @@ void Finish(); Same as Stanford 106A. Dimension must be the first line. +`CollectNewspaperKarel.w`: + +``` +Dimension: (7, 5) +Wall: (3, 2) west +Wall: (3, 2) south +Wall: (3, 3) west +Wall: (3, 4) west +Wall: (3, 5) south +Wall: (4, 2) south +Wall: (4, 5) south +Wall: (5, 2) south +Wall: (5, 5) south +Wall: (6, 2) west +Wall: (6, 4) west +Beeper: (6, 3) 1 +Karel: (3, 4) east +Speed: 1.00 +``` + ### Unit testing See ``src/test/karel_unittest.cc`` diff --git a/karel/src/test/karel.png b/karel/src/test/karel.png new file mode 100644 index 0000000000000000000000000000000000000000..f0b9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=k z{3t0C3Z_2h>0_a)FZ>n|q9;;H{sRa<6SYOTfuES+yARU0MZ1q9r2F(VUIhqyk3xCI zEa_%5g@H*^#QE{1I3J}f;Rfmu>xNl8ad$o-N_xE5vNW=DVM{NBo6{AZ8=CAyT$E(h zc&HraK^`XFKphrvs*4JqT;ksKO*Uy`;=$LU=`&s1@Z+CaicO)+;N2e*1fg}7*OPZa zx;)9K5r&-OvR`H@Vi}_1y;(3X>0fMx^C)=_e;)Ys&SLaeQRYyRF!%uWivr~l&C>F+1Z-G8{gVVT zSd%FT-kSp6&O=60jb z+F1O-?X2;^MCzW7-IG0nir{uX{zHeoP~H6^8$|f^CqwrI3H$Wvw!PJv-FV&FXY;1R z8b14pq4F4|nAF3cZ>@5k@S^IMY4g0FO49>POjUx>#4FD@VfVxewq&Y*%C&sHEz7xB zqh~9-1{J!2v$6fqZZA~$-sjn|36=_}*BJGA$z_*NQ1=IJ+04x7b_jR Nqo{VPNFMJ0e*pTS%2)sZ literal 0 HcmV?d00001 diff --git a/karel/src/test/worlds/CollectNewspaperKarel.w b/karel/src/test/worlds/CollectNewspaperKarel.w deleted file mode 100644 index 98805d7..0000000 --- a/karel/src/test/worlds/CollectNewspaperKarel.w +++ /dev/null @@ -1,15 +0,0 @@ -Dimension: (7, 5) -Wall: (3, 2) west -Wall: (3, 2) south -Wall: (3, 3) west -Wall: (3, 4) west -Wall: (3, 5) south -Wall: (4, 2) south -Wall: (4, 5) south -Wall: (5, 2) south -Wall: (5, 5) south -Wall: (6, 2) west -Wall: (6, 4) west -Beeper: (6, 3) 1 -Karel: (3, 4) east -Speed: 1.00 diff --git a/karel/src/test/worlds/MidpointFindingKarel.w b/karel/src/test/worlds/MidpointFindingKarel.w deleted file mode 100644 index 914d87e..0000000 --- a/karel/src/test/worlds/MidpointFindingKarel.w +++ /dev/null @@ -1,4 +0,0 @@ -Dimension: (9, 9) -BeeperBag: INFINITE -Karel: (1, 1) East -Speed: 0.50 diff --git a/karel/src/test/worlds/SampleQuad2.w b/karel/src/test/worlds/SampleQuad2.w deleted file mode 100644 index 3382e46..0000000 --- a/karel/src/test/worlds/SampleQuad2.w +++ /dev/null @@ -1,35 +0,0 @@ -Dimension: (13, 9) -Beeper: (1, 1) 1 -Beeper: (1, 2) 1 -Wall: (1, 4) South -Wall: (2, 4) West -Wall: (2, 5) South -Wall: (3, 4) West -Wall: (3, 4) South -Wall: (4, 4) West -Wall: (4, 5) South -Beeper: (5, 1) 1 -Wall: (5, 5) West -Beeper: (5, 5) 1 -Wall: (5, 6) South -Wall: (6, 5) West -Wall: (6, 5) South -Wall: (7, 4) West -Wall: (7, 4) South -Wall: (8, 3) West -Wall: (8, 3) South -Wall: (9, 2) West -Wall: (9, 2) South -Wall: (10, 2) West -Wall: (10, 3) South -Wall: (11, 3) West -Wall: (11, 4) South -Wall: (12, 4) West -Wall: (12, 5) South -Beeper: (13, 1) 1 -Beeper: (13, 3) 1 -Wall: (13, 4) West -Wall: (13, 4) South -BeeperBag: INFINITE -Karel: (1, 1) East -Speed: 0.5 diff --git a/karel/src/test/worlds/StoneMasonKarel.w b/karel/src/test/worlds/StoneMasonKarel.w deleted file mode 100644 index 6def864..0000000 --- a/karel/src/test/worlds/StoneMasonKarel.w +++ /dev/null @@ -1,39 +0,0 @@ -Dimension: (13, 13) -Beeper: (1, 4) 1 -Beeper: (1, 5) 1 -Wall: (1, 6) South -Wall: (2, 6) West -Wall: (2, 7) South -Wall: (3, 7) West -Wall: (3, 8) South -Wall: (4, 7) West -Wall: (4, 7) South -Beeper: (5, 1) 1 -Beeper: (5, 2) 1 -Beeper: (5, 4) 1 -Wall: (5, 6) West -Wall: (5, 6) South -Wall: (6, 6) West -Wall: (6, 7) South -Wall: (7, 7) West -Wall: (7, 8) South -Wall: (8, 7) West -Wall: (8, 7) South -Beeper: (9, 3) 1 -Beeper: (9, 5) 1 -Wall: (9, 6) West -Wall: (9, 6) South -Wall: (10, 6) West -Wall: (10, 7) South -Wall: (11, 7) West -Wall: (11, 8) South -Wall: (12, 7) West -Wall: (12, 7) South -Beeper: (13, 1) 1 -Beeper: (13, 3) 1 -Beeper: (13, 5) 1 -Wall: (13, 6) West -Wall: (13, 6) South -BeeperBag: INFINITE -Karel: (1, 1) East -Speed: 0.5 diff --git a/karel/test.cc b/karel/test.cc deleted file mode 100644 index 4b7f555..0000000 --- a/karel/test.cc +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright 2020 Paul Salvador Inventado and Google LLC -// -// Use of this source code is governed by an MIT-style -// license that can be found in the LICENSE file or at -// https://opensource.org/licenses/MIT. - -#include "karel.h" - -void KarelProgram() { - Move(); - Move(); - Move(); - Move(); - Move(); - PutBeeper(); - PickBeeper(); - TurnLeft(); - Move(); - PutBeeper(); - TurnLeft(); - Move(); - TurnLeft(); - TurnLeft(); -} - -int main() { - LoadWorld("src/test/worlds/1x8.w"); - KarelProgram(); - Finish(); - return 0; -} From 4c602f300f5351cc35ef01a717ce266426a6b4f7 Mon Sep 17 00:00:00 2001 From: Katie Dektar Date: Tue, 8 Dec 2020 15:04:21 -0800 Subject: [PATCH 28/40] Improve unittest and fix robot left/right clear bug --- karel/README.md | 2 +- karel/src/orientation.h | 8 +- karel/src/robot.cc | 26 +++--- karel/src/test/karel_unittest.cc | 137 +++++++++++++++++++++++++++- karel/src/test/worlds/8x8.w | 4 + karel/src/test/worlds/inner_walls.w | 8 ++ karel/src/test/worlds/outer_walls.w | 8 ++ 7 files changed, 174 insertions(+), 19 deletions(-) create mode 100644 karel/src/test/worlds/inner_walls.w create mode 100644 karel/src/test/worlds/outer_walls.w diff --git a/karel/README.md b/karel/README.md index dec24ac..e2c3557 100644 --- a/karel/README.md +++ b/karel/README.md @@ -76,7 +76,7 @@ void KarelProgram() { } int main() { - LoadWorld("src/test/worlds/CollectNewspaperKarel.w"); + LoadWorld("worlds/CollectNewspaperKarel.w"); KarelProgram(); Finish(); return 0; diff --git a/karel/src/orientation.h b/karel/src/orientation.h index c12b784..a7cbd29 100644 --- a/karel/src/orientation.h +++ b/karel/src/orientation.h @@ -10,10 +10,10 @@ namespace karel { enum Orientation { - kNorth = 1, - kEast = 2, - kSouth = 3, - kWest = 4, + kNorth = 0, + kEast = 1, + kSouth = 2, + kWest = 3, }; struct PositionAndOrientation { diff --git a/karel/src/robot.cc b/karel/src/robot.cc index 7bbc2a1..0133cb8 100644 --- a/karel/src/robot.cc +++ b/karel/src/robot.cc @@ -315,11 +315,13 @@ bool Robot::FrontIsClear() const { } bool Robot::LeftIsClear() const { - return DirectionIsClear((Orientation)(((int)position_.orientation + 1) % 4)); + return DirectionIsClear(static_cast( + (static_cast(position_.orientation) + 1) % 4)); } bool Robot::RightIsClear() const { - return DirectionIsClear((Orientation)(((int)position_.orientation - 1) % 4)); + return DirectionIsClear(static_cast( + (static_cast(position_.orientation) - 1 + 4) % 4)); } bool Robot::FacingNorth() const { @@ -459,18 +461,18 @@ void Robot::DrawWorld() { kWhite); for (int i = 0; i <= y_dimen_; i++) { // Draw horizontal lines and indexes. - int x = pxPerCell * x_dimen_ - 1; + int x = pxPerCell * x_dimen_; int y = i * pxPerCell; image_.DrawLine(0, y, x, y, kGridColor, kWallThickness); if (i < y_dimen_) { image_.DrawText(x + fontSize / 2, y + (pxPerCell - fontSize) / 2, - std::to_string(i + 1), fontSize, kWallColor); + std::to_string(y_dimen_ - i), fontSize, kWallColor); } } for (int i = 0; i <= x_dimen_; i++) { // Draw vertical lines and indexes. int x = i * pxPerCell; - int y = pxPerCell * y_dimen_ - 1; + int y = pxPerCell * y_dimen_; image_.DrawLine(x, 0, x, y, kGridColor, kWallThickness); if (i < x_dimen_) { image_.DrawText(x + (pxPerCell - fontSize) / 2, y + fontSize / 2, @@ -505,22 +507,20 @@ void Robot::DrawWorld() { } // Draw the walls. if (cell.HasNorthWall()) { - image_.DrawLine(i * pxPerCell, j * pxPerCell, (i + 1) * pxPerCell - 1, + image_.DrawLine(i * pxPerCell, j * pxPerCell, (i + 1) * pxPerCell, j * pxPerCell, kWallColor, kWallThickness); } if (cell.HasSouthWall()) { - image_.DrawLine(i * pxPerCell, (j + 1) * pxPerCell - 1, - (i + 1) * pxPerCell - 1, (j + 1) * pxPerCell - 1, - kWallColor, kWallThickness); + image_.DrawLine(i * pxPerCell, (j + 1) * pxPerCell, (i + 1) * pxPerCell, + (j + 1) * pxPerCell, kWallColor, kWallThickness); } if (cell.HasWestWall()) { image_.DrawLine(i * pxPerCell, j * pxPerCell, i * pxPerCell, - (j + 1) * pxPerCell - 1, kWallColor, kWallThickness); + (j + 1) * pxPerCell, kWallColor, kWallThickness); } if (cell.HasEastWall()) { - image_.DrawLine((i + 1) * pxPerCell - 1, j * pxPerCell, - (i + 1) * pxPerCell - 1, (j + 1) * pxPerCell - 1, - kWallColor, kWallThickness); + image_.DrawLine((i + 1) * pxPerCell, j * pxPerCell, (i + 1) * pxPerCell, + (j + 1) * pxPerCell, kWallColor, kWallThickness); } } } diff --git a/karel/src/test/karel_unittest.cc b/karel/src/test/karel_unittest.cc index 3e86487..a257fc6 100644 --- a/karel/src/test/karel_unittest.cc +++ b/karel/src/test/karel_unittest.cc @@ -21,8 +21,10 @@ using karel::Robot; using karel::RobotError; // Test TODOs: -// Test walls, loading maps with walls, not walking through walls +// Test loading 1 and many beepers. +// Test loading world where karel has finite beepers. // Test error states +// Test loading bad files and helpful output // Test stops taking action after reaching an error state. // Test loading beepers // Test putting/picking beepers not at (1, 1) @@ -88,6 +90,139 @@ TEST_F(KarelTest, LoadsWorld) { ASSERT_TRUE(IsBasicallyInfinite(r.GetNumBeepersInBag())); } +TEST_F(KarelTest, LoadsWorldWithOuterWalls) { + Robot& r = + Robot::InitializeInstance("worlds/outer_walls.w", /* enable animations */ false, + /* force initialize */ true); + ASSERT_EQ(8, r.GetWorldWidth()); + ASSERT_EQ(8, r.GetWorldHeight()); + + // Cell at (3, 5) has only north wall. + EXPECT_TRUE(r.GetCell(3, 5).HasNorthWall()); + // Cell at (2, 6) has only east wall. + EXPECT_TRUE(r.GetCell(2, 6).HasEastWall()); + // Cell at (3, 7) has only south wall + EXPECT_TRUE(r.GetCell(3, 7).HasSouthWall()); + // Cell at (4, 6) has only west wall. + EXPECT_TRUE(r.GetCell(4, 6).HasWestWall()); + + ASSERT_EQ(Orientation::kEast, r.GetOrientation()); + ASSERT_EQ(3, r.GetXPosition()); + ASSERT_EQ(6, r.GetYPosition()); +} + +TEST_F(KarelTest, LoadsWorldWithInnerWalls) { + Robot& r = + Robot::InitializeInstance("worlds/inner_walls.w", /* enable animations */ false, + /* force initialize */ true); + // Cell at (3, 2) has all four walls. + const Cell& c = r.GetCell(3, 2); + EXPECT_TRUE(c.HasNorthWall()); + EXPECT_TRUE(c.HasEastWall()); + EXPECT_TRUE(c.HasSouthWall()); + EXPECT_TRUE(c.HasWestWall()); + + ASSERT_EQ(Orientation::kEast, r.GetOrientation()); + ASSERT_EQ(3, r.GetXPosition()); + ASSERT_EQ(2, r.GetYPosition()); +} + +TEST_F(KarelTest, CannotMoveThroughOuterWalls) { + for (int i = 0; i < 4; i++) { + Robot& r = + Robot::InitializeInstance("worlds/outer_walls.w", + /* enable animations */ false, + /* force initialize */ true); + ASSERT_EQ(RobotError::kNoError, r.GetError()); + for (int j = 0; j < i; j++) { + TurnLeft(); + } + EXPECT_FALSE(FrontIsClear()); + EXPECT_TRUE(FrontIsBlocked()); + EXPECT_FALSE(RightIsClear()); + EXPECT_TRUE(RightIsBlocked()); + EXPECT_FALSE(LeftIsClear()); + EXPECT_TRUE(LeftIsBlocked()); + Move(); + if (i == 0) { + ASSERT_TRUE(FacingEast()); + EXPECT_EQ(RobotError::kCannotMoveEast, r.GetError()); + } else if (i == 1) { + ASSERT_TRUE(FacingNorth()); + EXPECT_EQ(RobotError::kCannotMoveNorth, r.GetError()); + } else if (i == 2) { + ASSERT_TRUE(FacingWest()); + EXPECT_EQ(RobotError::kCannotMoveWest, r.GetError()); + } else { + ASSERT_TRUE(FacingSouth()); + EXPECT_EQ(RobotError::kCannotMoveSouth, r.GetError()); + } + } +} + +TEST_F(KarelTest, CannotMoveThroughInnerWalls) { + for (int i = 0; i < 4; i++) { + Robot& r = + Robot::InitializeInstance("worlds/inner_walls.w", + /* enable animations */ false, + /* force initialize */ true); + ASSERT_EQ(RobotError::kNoError, r.GetError()); + for (int j = 0; j < i; j++) { + TurnLeft(); + } + Move(); + EXPECT_FALSE(FrontIsClear()); + EXPECT_TRUE(FrontIsBlocked()); + EXPECT_FALSE(RightIsClear()); + EXPECT_TRUE(RightIsBlocked()); + EXPECT_FALSE(LeftIsClear()); + EXPECT_TRUE(LeftIsBlocked()); + if (i == 0) { + ASSERT_TRUE(FacingEast()); + EXPECT_EQ(RobotError::kCannotMoveEast, r.GetError()); + } else if (i == 1) { + ASSERT_TRUE(FacingNorth()); + EXPECT_EQ(RobotError::kCannotMoveNorth, r.GetError()); + } else if (i == 2) { + ASSERT_TRUE(FacingWest()); + EXPECT_EQ(RobotError::kCannotMoveWest, r.GetError()); + } else { + ASSERT_TRUE(FacingSouth()); + EXPECT_EQ(RobotError::kCannotMoveSouth, r.GetError()); + } + } +} + +TEST_F(KarelTest, CannotMoveThroughWorldEdges) { + for (int i = 0; i < 4; i++) { + Robot& r = + Robot::InitializeInstance("worlds/2x1.w", + /* enable animations */ false, + /* force initialize */ true); + ASSERT_EQ(RobotError::kNoError, r.GetError()); + for (int j = 0; j < i; j++) { + TurnLeft(); + } + if (FacingEast()) { + Move(); + Move(); + EXPECT_EQ(RobotError::kCannotMoveEast, r.GetError()); + EXPECT_EQ(2, r.GetXPosition()); + EXPECT_EQ(1, r.GetYPosition()); + } else if (FacingNorth()) { + Move(); + EXPECT_EQ(RobotError::kCannotMoveNorth, r.GetError()); + } else if (FacingWest()) { + Move(); + EXPECT_EQ(RobotError::kCannotMoveWest, r.GetError()); + } else if (FacingSouth()) { + Move(); + EXPECT_EQ(RobotError::kCannotMoveSouth, r.GetError()); + } + } + +} + TEST_F(KarelTest, PutsAndPicksBeeper) { // Default world has no beepers, and Karel has infinite. Robot& r = Robot::GetInstance(/* enable animations */ false, diff --git a/karel/src/test/worlds/8x8.w b/karel/src/test/worlds/8x8.w index 4a48dbe..2452d23 100644 --- a/karel/src/test/worlds/8x8.w +++ b/karel/src/test/worlds/8x8.w @@ -3,6 +3,10 @@ Wall: (3, 2) west Wall: (3, 2) south Wall: (3, 2) north Wall: (3, 2) east +Wall: (3, 5) north +Wall: (4, 6) west +Wall: (3, 7) south +Wall: (2, 6) east BeeperBag: INFINITY Karel: (1, 1) East Speed: 0.75 diff --git a/karel/src/test/worlds/inner_walls.w b/karel/src/test/worlds/inner_walls.w new file mode 100644 index 0000000..56ada4f --- /dev/null +++ b/karel/src/test/worlds/inner_walls.w @@ -0,0 +1,8 @@ +Dimension: (8, 8) +Wall: (3, 2) west +Wall: (3, 2) south +Wall: (3, 2) north +Wall: (3, 2) east +BeeperBag: 0 +Karel: (3, 2) East +Speed: 0.75 diff --git a/karel/src/test/worlds/outer_walls.w b/karel/src/test/worlds/outer_walls.w new file mode 100644 index 0000000..f6d408e --- /dev/null +++ b/karel/src/test/worlds/outer_walls.w @@ -0,0 +1,8 @@ +Dimension: (8, 8) +Wall: (3, 5) north +Wall: (4, 6) west +Wall: (3, 7) south +Wall: (2, 6) east +BeeperBag: 3 +Karel: (3, 6) East +Speed: 0.75 From 7cb1e50236bc0824336e4583b834fbfa83016cea Mon Sep 17 00:00:00 2001 From: Katie Dektar Date: Tue, 8 Dec 2020 15:04:21 -0800 Subject: [PATCH 29/40] Improve unittest and fix robot left/right clear bug --- karel/README.md | 2 +- karel/src/orientation.h | 8 +- karel/src/robot.cc | 31 +- karel/src/robot.h | 6 +- karel/src/test/karel_unittest.cc | 285 +++++++++++++++++- karel/src/test/worlds/beepers.w | 8 + .../src/test/worlds/{8x8.w => inner_walls.w} | 4 +- karel/src/test/worlds/outer_walls.w | 8 + 8 files changed, 322 insertions(+), 30 deletions(-) create mode 100644 karel/src/test/worlds/beepers.w rename karel/src/test/worlds/{8x8.w => inner_walls.w} (72%) create mode 100644 karel/src/test/worlds/outer_walls.w diff --git a/karel/README.md b/karel/README.md index dec24ac..e2c3557 100644 --- a/karel/README.md +++ b/karel/README.md @@ -76,7 +76,7 @@ void KarelProgram() { } int main() { - LoadWorld("src/test/worlds/CollectNewspaperKarel.w"); + LoadWorld("worlds/CollectNewspaperKarel.w"); KarelProgram(); Finish(); return 0; diff --git a/karel/src/orientation.h b/karel/src/orientation.h index c12b784..a7cbd29 100644 --- a/karel/src/orientation.h +++ b/karel/src/orientation.h @@ -10,10 +10,10 @@ namespace karel { enum Orientation { - kNorth = 1, - kEast = 2, - kSouth = 3, - kWest = 4, + kNorth = 0, + kEast = 1, + kSouth = 2, + kWest = 3, }; struct PositionAndOrientation { diff --git a/karel/src/robot.cc b/karel/src/robot.cc index 7bbc2a1..efd47ae 100644 --- a/karel/src/robot.cc +++ b/karel/src/robot.cc @@ -19,7 +19,8 @@ #include "orientation.h" // TODO: Save to image file (maybe for testing) -// document +// documentation +// file error states namespace karel { @@ -98,7 +99,7 @@ void Robot::Initialize(std::string filename, bool enable_graphics, initialized_ = true; error_ = RobotError::kNoError; finished_ = false; - + world_.clear(); enable_animations_ = enable_graphics; if (!filename.size()) { @@ -315,11 +316,13 @@ bool Robot::FrontIsClear() const { } bool Robot::LeftIsClear() const { - return DirectionIsClear((Orientation)(((int)position_.orientation + 1) % 4)); + return DirectionIsClear(static_cast( + (static_cast(position_.orientation) + 1) % 4)); } bool Robot::RightIsClear() const { - return DirectionIsClear((Orientation)(((int)position_.orientation - 1) % 4)); + return DirectionIsClear(static_cast( + (static_cast(position_.orientation) - 1 + 4) % 4)); } bool Robot::FacingNorth() const { @@ -459,18 +462,18 @@ void Robot::DrawWorld() { kWhite); for (int i = 0; i <= y_dimen_; i++) { // Draw horizontal lines and indexes. - int x = pxPerCell * x_dimen_ - 1; + int x = pxPerCell * x_dimen_; int y = i * pxPerCell; image_.DrawLine(0, y, x, y, kGridColor, kWallThickness); if (i < y_dimen_) { image_.DrawText(x + fontSize / 2, y + (pxPerCell - fontSize) / 2, - std::to_string(i + 1), fontSize, kWallColor); + std::to_string(y_dimen_ - i), fontSize, kWallColor); } } for (int i = 0; i <= x_dimen_; i++) { // Draw vertical lines and indexes. int x = i * pxPerCell; - int y = pxPerCell * y_dimen_ - 1; + int y = pxPerCell * y_dimen_; image_.DrawLine(x, 0, x, y, kGridColor, kWallThickness); if (i < x_dimen_) { image_.DrawText(x + (pxPerCell - fontSize) / 2, y + fontSize / 2, @@ -505,22 +508,20 @@ void Robot::DrawWorld() { } // Draw the walls. if (cell.HasNorthWall()) { - image_.DrawLine(i * pxPerCell, j * pxPerCell, (i + 1) * pxPerCell - 1, + image_.DrawLine(i * pxPerCell, j * pxPerCell, (i + 1) * pxPerCell, j * pxPerCell, kWallColor, kWallThickness); } if (cell.HasSouthWall()) { - image_.DrawLine(i * pxPerCell, (j + 1) * pxPerCell - 1, - (i + 1) * pxPerCell - 1, (j + 1) * pxPerCell - 1, - kWallColor, kWallThickness); + image_.DrawLine(i * pxPerCell, (j + 1) * pxPerCell, (i + 1) * pxPerCell, + (j + 1) * pxPerCell, kWallColor, kWallThickness); } if (cell.HasWestWall()) { image_.DrawLine(i * pxPerCell, j * pxPerCell, i * pxPerCell, - (j + 1) * pxPerCell - 1, kWallColor, kWallThickness); + (j + 1) * pxPerCell, kWallColor, kWallThickness); } if (cell.HasEastWall()) { - image_.DrawLine((i + 1) * pxPerCell - 1, j * pxPerCell, - (i + 1) * pxPerCell - 1, (j + 1) * pxPerCell - 1, - kWallColor, kWallThickness); + image_.DrawLine((i + 1) * pxPerCell, j * pxPerCell, (i + 1) * pxPerCell, + (j + 1) * pxPerCell, kWallColor, kWallThickness); } } } diff --git a/karel/src/robot.h b/karel/src/robot.h index a6c7e6d..7b552e7 100644 --- a/karel/src/robot.h +++ b/karel/src/robot.h @@ -26,8 +26,8 @@ class Robot { /** * Get the Robot singleton. Initializes it with default values if it isn't * already initialized. Set |enable_graphics| to false for testing, which - * will disable animations. Use |force_initialize| for testing which resets - * the singleton state. + * will disable animations. Use |force_initialize| only for testing which + * resets the singleton state. */ static karel::Robot& GetInstance(bool enable_graphics = true, bool force_initialize = false); @@ -35,7 +35,7 @@ class Robot { /** * Get the Robot singleton and intialize it from a file. Set |enable_graphics| * to false for testing, which will disable animations. Use |force_initialize| - * for testing which resets the singleton state. + * only for testing which resets the singleton state. */ static karel::Robot& InitializeInstance(std::string filename, bool enable_graphics = true, diff --git a/karel/src/test/karel_unittest.cc b/karel/src/test/karel_unittest.cc index 3e86487..65b128f 100644 --- a/karel/src/test/karel_unittest.cc +++ b/karel/src/test/karel_unittest.cc @@ -21,11 +21,7 @@ using karel::Robot; using karel::RobotError; // Test TODOs: -// Test walls, loading maps with walls, not walking through walls -// Test error states -// Test stops taking action after reaching an error state. -// Test loading beepers -// Test putting/picking beepers not at (1, 1) +// Test loading bad files and helpful output bool IsBasicallyInfinite(int number) { return number > std::numeric_limits::max() / 2; @@ -88,6 +84,167 @@ TEST_F(KarelTest, LoadsWorld) { ASSERT_TRUE(IsBasicallyInfinite(r.GetNumBeepersInBag())); } +TEST_F(KarelTest, LoadsWorldWithInfinityBeepers) { + // INFINITY vs INFINITE + Robot& r = Robot::InitializeInstance("worlds/8x1.w", + /* enable animations */ false, + /* force initialize */ true); + ASSERT_TRUE(IsBasicallyInfinite(r.GetNumBeepersInBag())); +} + +TEST_F(KarelTest, LoadsWorldWithNoBeepersInBag) { + Robot& r = Robot::InitializeInstance("worlds/beepers.w", + /* enable animations */ false, + /* force initialize */ true); + EXPECT_EQ(0, r.GetNumBeepersInBag()); +} + +TEST_F(KarelTest, LoadsWorldWithFiniteBeepers) { + Robot& r = Robot::InitializeInstance("worlds/inner_walls.w", + /* enable animations */ false, + /* force initialize */ true); + EXPECT_EQ(42, r.GetNumBeepersInBag()); +} + +TEST_F(KarelTest, LoadsWorldWithBeepersInCells) { + Robot& r = Robot::InitializeInstance("worlds/beepers.w", + /* enable animations */ false, + /* force initialize */ true); + EXPECT_EQ(1, r.GetCell(2, 1).GetNumBeepers()); + EXPECT_EQ(2, r.GetCell(3, 1).GetNumBeepers()); + EXPECT_EQ(3, r.GetCell(3, 2).GetNumBeepers()); + EXPECT_EQ(4, r.GetCell(4, 4).GetNumBeepers()); +} + +TEST_F(KarelTest, LoadsWorldWithOuterWalls) { + Robot& r = Robot::InitializeInstance("worlds/outer_walls.w", + /* enable animations */ false, + /* force initialize */ true); + ASSERT_EQ(8, r.GetWorldWidth()); + ASSERT_EQ(8, r.GetWorldHeight()); + + // Cell at (3, 5) has only north wall. + EXPECT_TRUE(r.GetCell(3, 5).HasNorthWall()); + // Cell at (2, 6) has only east wall. + EXPECT_TRUE(r.GetCell(2, 6).HasEastWall()); + // Cell at (3, 7) has only south wall + EXPECT_TRUE(r.GetCell(3, 7).HasSouthWall()); + // Cell at (4, 6) has only west wall. + EXPECT_TRUE(r.GetCell(4, 6).HasWestWall()); + + ASSERT_EQ(Orientation::kEast, r.GetOrientation()); + ASSERT_EQ(3, r.GetXPosition()); + ASSERT_EQ(6, r.GetYPosition()); +} + +TEST_F(KarelTest, LoadsWorldWithInnerWalls) { + Robot& r = Robot::InitializeInstance("worlds/inner_walls.w", + /* enable animations */ false, + /* force initialize */ true); + // Cell at (3, 2) has all four walls. + const Cell& c = r.GetCell(3, 2); + EXPECT_TRUE(c.HasNorthWall()); + EXPECT_TRUE(c.HasEastWall()); + EXPECT_TRUE(c.HasSouthWall()); + EXPECT_TRUE(c.HasWestWall()); + + ASSERT_EQ(Orientation::kEast, r.GetOrientation()); + ASSERT_EQ(3, r.GetXPosition()); + ASSERT_EQ(2, r.GetYPosition()); +} + +TEST_F(KarelTest, CannotMoveThroughOuterWalls) { + for (int i = 0; i < 4; i++) { + Robot& r = Robot::InitializeInstance("worlds/outer_walls.w", + /* enable animations */ false, + /* force initialize */ true); + ASSERT_EQ(RobotError::kNoError, r.GetError()); + for (int j = 0; j < i; j++) { + TurnLeft(); + } + EXPECT_FALSE(FrontIsClear()); + EXPECT_TRUE(FrontIsBlocked()); + EXPECT_FALSE(RightIsClear()); + EXPECT_TRUE(RightIsBlocked()); + EXPECT_FALSE(LeftIsClear()); + EXPECT_TRUE(LeftIsBlocked()); + Move(); + if (i == 0) { + ASSERT_TRUE(FacingEast()); + EXPECT_EQ(RobotError::kCannotMoveEast, r.GetError()); + } else if (i == 1) { + ASSERT_TRUE(FacingNorth()); + EXPECT_EQ(RobotError::kCannotMoveNorth, r.GetError()); + } else if (i == 2) { + ASSERT_TRUE(FacingWest()); + EXPECT_EQ(RobotError::kCannotMoveWest, r.GetError()); + } else { + ASSERT_TRUE(FacingSouth()); + EXPECT_EQ(RobotError::kCannotMoveSouth, r.GetError()); + } + } +} + +TEST_F(KarelTest, CannotMoveThroughInnerWalls) { + for (int i = 0; i < 4; i++) { + Robot& r = Robot::InitializeInstance("worlds/inner_walls.w", + /* enable animations */ false, + /* force initialize */ true); + ASSERT_EQ(RobotError::kNoError, r.GetError()); + for (int j = 0; j < i; j++) { + TurnLeft(); + } + Move(); + EXPECT_FALSE(FrontIsClear()); + EXPECT_TRUE(FrontIsBlocked()); + EXPECT_FALSE(RightIsClear()); + EXPECT_TRUE(RightIsBlocked()); + EXPECT_FALSE(LeftIsClear()); + EXPECT_TRUE(LeftIsBlocked()); + if (i == 0) { + ASSERT_TRUE(FacingEast()); + EXPECT_EQ(RobotError::kCannotMoveEast, r.GetError()); + } else if (i == 1) { + ASSERT_TRUE(FacingNorth()); + EXPECT_EQ(RobotError::kCannotMoveNorth, r.GetError()); + } else if (i == 2) { + ASSERT_TRUE(FacingWest()); + EXPECT_EQ(RobotError::kCannotMoveWest, r.GetError()); + } else { + ASSERT_TRUE(FacingSouth()); + EXPECT_EQ(RobotError::kCannotMoveSouth, r.GetError()); + } + } +} + +TEST_F(KarelTest, CannotMoveThroughWorldEdges) { + for (int i = 0; i < 4; i++) { + Robot& r = Robot::InitializeInstance("worlds/2x1.w", + /* enable animations */ false, + /* force initialize */ true); + ASSERT_EQ(RobotError::kNoError, r.GetError()); + for (int j = 0; j < i; j++) { + TurnLeft(); + } + if (FacingEast()) { + Move(); + Move(); + EXPECT_EQ(RobotError::kCannotMoveEast, r.GetError()); + EXPECT_EQ(2, r.GetXPosition()); + EXPECT_EQ(1, r.GetYPosition()); + } else if (FacingNorth()) { + Move(); + EXPECT_EQ(RobotError::kCannotMoveNorth, r.GetError()); + } else if (FacingWest()) { + Move(); + EXPECT_EQ(RobotError::kCannotMoveWest, r.GetError()); + } else if (FacingSouth()) { + Move(); + EXPECT_EQ(RobotError::kCannotMoveSouth, r.GetError()); + } + } +} + TEST_F(KarelTest, PutsAndPicksBeeper) { // Default world has no beepers, and Karel has infinite. Robot& r = Robot::GetInstance(/* enable animations */ false, @@ -111,6 +268,84 @@ TEST_F(KarelTest, PutsAndPicksBeeper) { } } +TEST_F(KarelTest, PicksManyBeepers) { + Robot& r = Robot::InitializeInstance("worlds/beepers.w", + /* enable animations */ false, + /* force initialize */ true); + EXPECT_FALSE(BeepersPresent()); + EXPECT_TRUE(NoBeepersInBag()); + EXPECT_EQ(0, r.GetNumBeepersInBag()); + + Move(); + // One beeper. + EXPECT_TRUE(BeepersPresent()); + EXPECT_FALSE(NoBeepersPresent()); + + PickBeeper(); + ASSERT_EQ(RobotError::kNoError, r.GetError()); + EXPECT_TRUE(HasBeepersInBag()); + EXPECT_FALSE(NoBeepersInBag()); + EXPECT_EQ(1, r.GetNumBeepersInBag()); + EXPECT_FALSE(BeepersPresent()); + EXPECT_TRUE(NoBeepersPresent()); + + Move(); + // Two beepers. + EXPECT_TRUE(BeepersPresent()); + EXPECT_FALSE(NoBeepersPresent()); + + PickBeeper(); + EXPECT_TRUE(BeepersPresent()); + EXPECT_FALSE(NoBeepersPresent()); + + PickBeeper(); + ASSERT_EQ(RobotError::kNoError, r.GetError()); + EXPECT_TRUE(HasBeepersInBag()); + EXPECT_FALSE(NoBeepersInBag()); + EXPECT_EQ(3, r.GetNumBeepersInBag()); + EXPECT_FALSE(BeepersPresent()); + EXPECT_TRUE(NoBeepersPresent()); + + TurnLeft(); + Move(); + // Three beepers. + EXPECT_TRUE(BeepersPresent()); + EXPECT_FALSE(NoBeepersPresent()); + + PickBeeper(); + EXPECT_TRUE(BeepersPresent()); + EXPECT_FALSE(NoBeepersPresent()); + + PickBeeper(); + EXPECT_TRUE(BeepersPresent()); + EXPECT_FALSE(NoBeepersPresent()); + + PickBeeper(); + ASSERT_EQ(RobotError::kNoError, r.GetError()); + EXPECT_TRUE(HasBeepersInBag()); + EXPECT_FALSE(NoBeepersInBag()); + EXPECT_EQ(6, r.GetNumBeepersInBag()); + EXPECT_FALSE(BeepersPresent()); + EXPECT_TRUE(NoBeepersPresent()); +} + +TEST_F(KarelTest, CannotPickMissingBeeper) { + Robot& r = Robot::GetInstance(/* enable animations */ false, + /* force initialize */ true); + ASSERT_EQ(RobotError::kNoError, r.GetError()); + PickBeeper(); + ASSERT_EQ(RobotError::kCannotPickBeeper, r.GetError()); +} + +TEST_F(KarelTest, CannotPutWhenBeeperBagEmpty) { + Robot& r = Robot::InitializeInstance("worlds/beepers.w", + /* enable animations */ false, + /* force initialize */ true); + ASSERT_EQ(RobotError::kNoError, r.GetError()); + PutBeeper(); + ASSERT_EQ(RobotError::kCannotPutBeeper, r.GetError()); +} + TEST_F(KarelTest, TurnsLeft) { Robot& r = Robot::GetInstance(/* enable animations */ false, /* force initialize */ true); @@ -211,6 +446,46 @@ TEST_F(KarelTest, MovesNorthAndSouth) { } } +TEST_F(KarelTest, DoesNotTakeActionAfterErrorState) { + Robot& r = + Robot::InitializeInstance("worlds/beepers.w", /* enable graphics */ false, + /* force initialize */ true); + EXPECT_EQ(Orientation::kEast, r.GetOrientation()); + EXPECT_EQ(1, r.GetXPosition()); + EXPECT_EQ(1, r.GetYPosition()); + EXPECT_FALSE(BeepersPresent()); + EXPECT_EQ(0, r.GetNumBeepersInBag()); + EXPECT_EQ(RobotError::kNoError, r.GetError()); + + // Create an error by picking a non-existant beeper. + PickBeeper(); + EXPECT_EQ(RobotError::kCannotPickBeeper, r.GetError()); + EXPECT_EQ(Orientation::kEast, r.GetOrientation()); + EXPECT_EQ(1, r.GetXPosition()); + EXPECT_EQ(1, r.GetYPosition()); + EXPECT_FALSE(BeepersPresent()); + // Didn't pick either. + EXPECT_EQ(0, r.GetNumBeepersInBag()); + + // Now it cannot move or turn and the error state stays as it was before. + Move(); + EXPECT_EQ(RobotError::kCannotPickBeeper, r.GetError()); + EXPECT_EQ(Orientation::kEast, r.GetOrientation()); + EXPECT_EQ(1, r.GetXPosition()); + EXPECT_EQ(1, r.GetYPosition()); + + TurnLeft(); + EXPECT_EQ(RobotError::kCannotPickBeeper, r.GetError()); + EXPECT_EQ(Orientation::kEast, r.GetOrientation()); + EXPECT_EQ(1, r.GetXPosition()); + EXPECT_EQ(1, r.GetYPosition()); + + PutBeeper(); + EXPECT_EQ(RobotError::kCannotPickBeeper, r.GetError()); + EXPECT_FALSE(BeepersPresent()); + EXPECT_EQ(0, r.GetNumBeepersInBag()); +} + int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); diff --git a/karel/src/test/worlds/beepers.w b/karel/src/test/worlds/beepers.w new file mode 100644 index 0000000..f2acc30 --- /dev/null +++ b/karel/src/test/worlds/beepers.w @@ -0,0 +1,8 @@ +Dimension: (8, 8) +Beeper: (2, 1) 1 +Beeper: (3, 1) 2 +Beeper: (3, 2) 3 +Beeper: (4, 4) 4 +BeeperBag: 0 +Karel: (1, 1) East +Speed: 0.75 diff --git a/karel/src/test/worlds/8x8.w b/karel/src/test/worlds/inner_walls.w similarity index 72% rename from karel/src/test/worlds/8x8.w rename to karel/src/test/worlds/inner_walls.w index 4a48dbe..64ce4a2 100644 --- a/karel/src/test/worlds/8x8.w +++ b/karel/src/test/worlds/inner_walls.w @@ -3,6 +3,6 @@ Wall: (3, 2) west Wall: (3, 2) south Wall: (3, 2) north Wall: (3, 2) east -BeeperBag: INFINITY -Karel: (1, 1) East +BeeperBag: 42 +Karel: (3, 2) East Speed: 0.75 diff --git a/karel/src/test/worlds/outer_walls.w b/karel/src/test/worlds/outer_walls.w new file mode 100644 index 0000000..f6d408e --- /dev/null +++ b/karel/src/test/worlds/outer_walls.w @@ -0,0 +1,8 @@ +Dimension: (8, 8) +Wall: (3, 5) north +Wall: (4, 6) west +Wall: (3, 7) south +Wall: (2, 6) east +BeeperBag: 3 +Karel: (3, 6) East +Speed: 0.75 From 8c0e6665000befa2a4373cbacddbde311de5f8b2 Mon Sep 17 00:00:00 2001 From: Katie Dektar Date: Thu, 10 Dec 2020 11:57:41 -0800 Subject: [PATCH 30/40] Add a11y features --- README.md | 8 ++- karel/karel.cc | 10 ++++ karel/karel.h | 18 ++++++ karel/src/cell.h | 13 +++- karel/src/error.h | 3 + karel/src/orientation.h | 7 +++ karel/src/robot.cc | 126 ++++++++++++++++++++++++++++++++++----- karel/src/robot.h | 58 +++++++++++++----- karel/src/test/karel.csv | 13 ++++ karel/src/test/karel.png | Bin 18851 -> 19361 bytes 10 files changed, 223 insertions(+), 33 deletions(-) create mode 100644 karel/src/test/karel.csv diff --git a/README.md b/README.md index a52c4d6..02a210e 100644 --- a/README.md +++ b/README.md @@ -20,10 +20,16 @@ Karel the Robot is a gentle introductory programming language created by [Dr. Ri ![karel the robot screenshot](karel/src/test/karel.png) -To create graphical Karel the Robot programs in C++, include ``karel/karel.h``. +### Accessibility + +Karel programs may export the world to CSV after each action. This may be helpful to screen-reader users. + +Karel programs may prompt before each robot action. This may be helpful for users who need to control the speed of execution. ### Usage +To create Karel the Robot programs in C++, include ``karel/karel.h``. + (TODO): Learn more about how to use the C++ Utils Karel the Robot functions in this [interactive tutorial](https://github.com/ILXL-guides/intro-to-karel) ## For developers and instructors diff --git a/karel/karel.cc b/karel/karel.cc index 2cbd515..17f6636 100644 --- a/karel/karel.cc +++ b/karel/karel.cc @@ -105,3 +105,13 @@ void Finish() { karel::Robot& r = karel::Robot::GetInstance(); r.Finish(); } + +void EnableCSVOutput() { + karel::Robot& r = karel::Robot::GetInstance(); + r.EnableCSVOutput(); +} + +void EnablePromptBeforeAction() { + karel::Robot& r = karel::Robot::GetInstance(); + r.EnablePromptBeforeAction(); +} diff --git a/karel/karel.h b/karel/karel.h index d53d5f3..9970266 100644 --- a/karel/karel.h +++ b/karel/karel.h @@ -149,3 +149,21 @@ void LoadWorld(std::string filename); * do any more actions. */ void Finish(); + +///////////////////////////////////////////////////////////////////////////// +// Methods for improving the accessibility of Karel // +///////////////////////////////////////////////////////////////////////////// + +/** + * Enables Karel CSV output. This will print Karel's world to a CSV between + * each action, and prompt to continue to the next action. May be used by + * screen-reader users to inspect Karel's world. + */ +void EnableCSVOutput(); + +/** + * Causes Karel to wait between each action function (Move, TurnLeft, + * PutBeeper, PickBeeper) until the user enters input into the terminal to + * proceed. + */ +void EnablePromptBeforeAction(); diff --git a/karel/src/cell.h b/karel/src/cell.h index 976dd89..faa14ba 100644 --- a/karel/src/cell.h +++ b/karel/src/cell.h @@ -11,16 +11,25 @@ namespace karel { -// Class representing a cell in Karel's world, including a count of beepers -// and whether or not there are walls. +/** + * Class representing a cell in Karel's world, including a count of beepers + * and whether or not there are walls. + */ class Cell { public: int GetNumBeepers() const { return num_beepers_; } void SetNumBeepers(int beepers) { num_beepers_ = beepers; } + bool HasNorthWall() const { return north_wall_; } bool HasEastWall() const { return east_wall_; } bool HasSouthWall() const { return south_wall_; } bool HasWestWall() const { return west_wall_; } + + /** + * Adds a wall on the given side of the cell. For example, a north wall would + * be at the top of the cell, and an east wall would be on the right of the + * cell. + */ void AddWall(Orientation wall_orientation) { switch (wall_orientation) { case kNorth: diff --git a/karel/src/error.h b/karel/src/error.h index e5df255..d8de672 100644 --- a/karel/src/error.h +++ b/karel/src/error.h @@ -11,6 +11,9 @@ namespace karel { +/** + * Defines an error state for Karel. kNoError means that there is no error. + */ enum RobotError { kNoError = 0, kCannotMoveNorth, diff --git a/karel/src/orientation.h b/karel/src/orientation.h index a7cbd29..3c12530 100644 --- a/karel/src/orientation.h +++ b/karel/src/orientation.h @@ -9,6 +9,10 @@ namespace karel { +/** + * Defines an orientation in the grid using compass directions: north is + * up, east is right, west is down, and south is left. + */ enum Orientation { kNorth = 0, kEast = 1, @@ -16,6 +20,9 @@ enum Orientation { kWest = 3, }; +/** + * Defines a position and orientation in the world grid. + */ struct PositionAndOrientation { int x = 0; int y = 0; diff --git a/karel/src/robot.cc b/karel/src/robot.cc index efd47ae..406fe62 100644 --- a/karel/src/robot.cc +++ b/karel/src/robot.cc @@ -99,8 +99,12 @@ void Robot::Initialize(std::string filename, bool enable_graphics, initialized_ = true; error_ = RobotError::kNoError; finished_ = false; + if (force_initialize) { + prompt_between_actions_ = false; + enable_csv_output_ = false; + } world_.clear(); - enable_animations_ = enable_graphics; + enable_graphics_ = enable_graphics; if (!filename.size()) { // No file. Default 10x10 blank world with no walls and no beepers. @@ -205,13 +209,13 @@ void Robot::Initialize(std::string filename, bool enable_graphics, y_dimen_ * pxPerCell + margin); DrawWorld(); - DrawRobot(position_.x * pxPerCell + pxPerCell / 2, - position_.y * pxPerCell + pxPerCell / 2); - Show(kLongDuration); + DrawRobot(); + Show(/* long duration */ true); } void Robot::Move() { if (finished_) return; + PromptBeforeActionIfNeeded(); switch (position_.orientation) { case Orientation::kNorth: if (position_.y == 0) { @@ -258,6 +262,7 @@ void Robot::Move() { void Robot::TurnLeft() { if (finished_) return; + PromptBeforeActionIfNeeded(); switch (position_.orientation) { case Orientation::kNorth: position_.orientation = Orientation::kWest; @@ -274,11 +279,12 @@ void Robot::TurnLeft() { } DrawWorld(); DrawRobot(); - Show(kLongDuration); + Show(/* long duration */ true); } void Robot::PutBeeper() { if (finished_) return; + PromptBeforeActionIfNeeded(); if (!HasBeepersInBag()) { Error(RobotError::kCannotPutBeeper); return; @@ -288,11 +294,12 @@ void Robot::PutBeeper() { cell.SetNumBeepers(cell.GetNumBeepers() + 1); DrawWorld(); DrawRobot(); - Show(kLongDuration); + Show(/* long duration */ true); } void Robot::PickBeeper() { if (finished_) return; + PromptBeforeActionIfNeeded(); if (!BeepersPresent()) { Error(RobotError::kCannotPickBeeper); return; @@ -302,7 +309,7 @@ void Robot::PickBeeper() { beeper_count_++; DrawWorld(); DrawRobot(); - Show(kLongDuration); + Show(/* long duration */ true); } bool Robot::HasBeepersInBag() const { return beeper_count_ > 0; } @@ -344,11 +351,27 @@ bool Robot::FacingWest() const { void Robot::Finish() { if (finished_) return; finished_ = true; - if (enable_animations_) { + if (enable_csv_output_) { + WriteWorldCSV(); + std::cout << "Finished. ctrl+c to exit." << std::endl << std::flush; + } + if (enable_graphics_) { image_.ShowUntilClosed("Karel's World"); } } +void Robot::EnablePromptBeforeAction() { prompt_between_actions_ = true; } + +void Robot::EnableCSVOutput() { + enable_csv_output_ = true; + prompt_between_actions_ = true; + if (initialized_) { + // If we are already initialized write the world CSV. The initial image + // has already been shown. + WriteWorldCSV(); + } +} + Orientation Robot::GetOrientation() const { return position_.orientation; } int Robot::GetXPosition() const { return position_.x + 1; } @@ -367,11 +390,79 @@ int Robot::GetWorldHeight() const { return y_dimen_; } RobotError Robot::GetError() const { return error_; } -void Robot::Show(int duration) { +void Robot::Show(bool long_duration) { if (finished_) return; - if (enable_animations_) { - image_.ShowForMs(duration * speed_, "Karel's World"); + if (long_duration && enable_csv_output_) { + WriteWorldCSV(); + } + if (enable_graphics_) { + image_.ShowForMs((long_duration ? kLongDuration : kShortDuration) * speed_, + "Karel's World"); + } +} + +void Robot::WriteWorldCSV() { + const std::string filename = "karel.csv"; + std::ofstream csv; + csv.open(filename); + if (!csv.is_open()) { + std::cout << "Error: Could not open " << filename + << " to write Karel's world. Perhaps it is opened by another " + "application?" + << std::endl + << std::flush; + return; + } + for (int y = 0; y < y_dimen_; y++) { + for (int x = 0; x < x_dimen_; x++) { + // print contents walls. + Cell& cell = world_[x][y]; + csv << "\""; + if (x == position_.x && y == position_.y) { + if (position_.orientation == Orientation::kNorth) { + csv << "kn "; + } else if (position_.orientation == Orientation::kEast) { + csv << "ke "; + } else if (position_.orientation == Orientation::kSouth) { + csv << "ks "; + } else { + csv << "kw "; + } + } + if (cell.GetNumBeepers() > 0) { + csv << "b "; + } else { + csv << "o "; + } + csv << "(" << x + 1 << "," << y_dimen_ - y << ")\","; + if (x < x_dimen_ - 1 && + (cell.HasEastWall() || world_[x + 1][y].HasWestWall())) { + csv << "w,"; + } else { + csv << ","; + } + } + csv << std::endl; + if (y < y_dimen_ - 1) { + for (int x = 0; x < x_dimen_; x++) { + // print bottom walls and next top walls + if (world_[x][y].HasSouthWall() || world_[x][y + 1].HasNorthWall()) { + csv << "w,,"; + } else { + csv << ",,"; + } + } + } + csv << std::endl; } + csv << std::endl; + csv << "symbol,kn,ke,ks,kw,o,b,w,\"(x,y)\"\n"; + csv << "meaning,Karel facing north,Karel facing east, Karel facing south, " + "Karel facing west,empty cell,cell with at least one beeper,wall " + "between cells,cell coordinates\n"; + // TODO: Write error state and a key. + csv.close(); + std::cout << "World state written to " << filename << std::endl << std::flush; } void Robot::Error(RobotError error) { @@ -597,18 +688,25 @@ void Robot::DrawRobot(int pixel_x, int pixel_y) { } void Robot::AnimateMove(int next_x, int next_y) { - int steps = enable_animations_ ? kNumAnimationSteps : 0; + int steps = enable_graphics_ ? kNumAnimationSteps : 0; for (int i = 1; i <= steps; i++) { DrawWorld(); double fraction = i * 1.0 / steps; double x = position_.x * (1 - fraction) + next_x * fraction; double y = position_.y * (1 - fraction) + next_y * fraction; DrawRobot(x * pxPerCell + pxPerCell / 2, y * pxPerCell + pxPerCell / 2); - Show(kShortDuration); + Show(/* short duration */ false); } position_.x = next_x; position_.y = next_y; - Show(kLongDuration); + Show(/* long duration */ true); +} + +void Robot::PromptBeforeActionIfNeeded() { + if (!prompt_between_actions_) return; + std::cout << "Paused. Enter any character to continue: " << std::flush; + std::string value; + std::cin >> value; } // Note that the orientation is not populated. This is just a helper to diff --git a/karel/src/robot.h b/karel/src/robot.h index 7b552e7..a9aab52 100644 --- a/karel/src/robot.h +++ b/karel/src/robot.h @@ -4,11 +4,7 @@ // license that can be found in the LICENSE file or at // https://opensource.org/licenses/MIT. -#include - #include -#include -#include #include #include "../../graphics/image.h" @@ -45,10 +41,10 @@ class Robot { Robot(const Robot&) = delete; karel::Robot& operator=(const Robot&) = delete; - ///////////////////////////////////////////////////////// - // Methods for core Karel functionality // - // These methods allow interaction with Karel. // - ///////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////// + // Methods for core Karel functionality // + // These methods allow interaction with Karel. // + /////////////////////////////////////////////////////////// /** * Move Karel forward one step. Results in an error if Karel cannot move @@ -129,10 +125,24 @@ class Robot { */ void Finish(); - ///////////////////////////////////////////////////////////////////// - // Methods for tests. Tests should access Robot with GetInstance // - // and may inspect its state with the following methods. // - ///////////////////////////////////////////////////////////////////// + /** + * Causes Robot to wait between each action function (Move, TurnLeft, + * PutBeeper, PickBeeper) until the user enters input into the terminal to + * proceed. This may be used to improve the robot's accessibility. + */ + void EnablePromptBeforeAction(); + + /** + * Enables Robot CSV output. This will print Karel's world to a CSV between + * each action, and prompt to continue to the next action. May be used by + * screen-reader users to inspect Karel's world. + */ + void EnableCSVOutput(); + + /////////////////////////////////////////////////////////////////////// + // Methods for tests. Tests should access Robot with GetInstance // + // and may inspect its state with the following methods. // + /////////////////////////////////////////////////////////////////////// /** * Gets the orientation that Karel is facing. May be simpler to use this in @@ -193,9 +203,16 @@ class Robot { bool force_initialize); /** - * Shows karel's world, blocking for the given |duration| in milliseconds. + * Shows karel's world, blocking for a long duration or a short duration. + * If long_duration, may also print to the terminal when EnableTerminalOutput + * was called. */ - void Show(int duration); + void Show(bool long_duration); + + /** + * Writes the world to a CSV file. + */ + void WriteWorldCSV(); /** * Displays an error and finishes the program. @@ -219,6 +236,8 @@ class Robot { void AnimateMove(int next_x, int next_y); + void PromptBeforeActionIfNeeded(); + /** * Helper method to parse position from the next item in a file stream. * Note that the orientation is not populated. This is just a helper to @@ -234,9 +253,16 @@ class Robot { */ PositionAndOrientation ParsePositionAndOrientation(std::fstream& file) const; - // Whether animations are enabled. They should probably be disabled for + // Whether graphics are enabled. They should probably be disabled for // testing. - bool enable_animations_ = true; + bool enable_graphics_ = true; + + // Whether to prompt the user to continue between actions. May be useful as + // an accessibility feature. + bool prompt_between_actions_ = false; + + // Whether to enable terminal output -- a text-based display of Karel's world. + bool enable_csv_output_ = false; // Speed multiplier for animation. double speed_ = 1.0; diff --git a/karel/src/test/karel.csv b/karel/src/test/karel.csv new file mode 100644 index 0000000..d14b508 --- /dev/null +++ b/karel/src/test/karel.csv @@ -0,0 +1,13 @@ +"o (1,5)",,"o (2,5)",,"o (3,5)",,"o (4,5)",,"o (5,5)",,"o (6,5)",,"o (7,5)",, +,,,,w,,w,,w,,,,,, +"o (1,4)",,"o (2,4)",w,"o (3,4)",,"ke o (4,4)",,"o (5,4)",w,"o (6,4)",,"o (7,4)",, +,,,,,,,,,,,,,, +"o (1,3)",,"o (2,3)",w,"o (3,3)",,"o (4,3)",,"o (5,3)",,"b (6,3)",,"o (7,3)",, +,,,,,,,,,,,,,, +"o (1,2)",,"o (2,2)",w,"o (3,2)",,"o (4,2)",,"o (5,2)",w,"o (6,2)",,"o (7,2)",, +,,,,w,,w,,w,,,,,, +"o (1,1)",,"o (2,1)",,"o (3,1)",,"o (4,1)",,"o (5,1)",,"o (6,1)",,"o (7,1)",, + + +key,Karel facing north,Karel facing east, Karel facing south, Karel facing west,empty cell,cell with at least one beeper,wall between cells,cell coordinates +,kn,ke,ks,kw,o,b,w,"(x,y)" diff --git a/karel/src/test/karel.png b/karel/src/test/karel.png index f0b9a5e6f014ac73c975f701c56cf2bd7ccdd154..ef274d5d52deeca7becfd32f33da73596a9d6df0 100644 GIT binary patch literal 19361 zcmeIaby!qe|32)Dj5J6nNU8{kD4}!;N=XSww{*uy*MNw6B&0i(k}l~QKmh?kx=TtJ zx|?^+aL#i)&-q?&U+?w%4wNcja0|}1J?TE2S4A=wRgb1;oV;wISl82%CZ?z1{iu4Vaeg#@W1T! z6zP9iTpH{D{Nb54a%=v3I5wT@!>SjH&*yeW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~QW&WJyXl$Pz!kZCu-A>FOUuE8PRUnk~lnuU$({2I6byM@ozz*0mklO=k z{3t0C3Z_2h>0_a)FZ>n|q9;;H{sRa<6SYOTfuES+yARU0MZ1q9r2F(VUIhqyk3xCI zEa_%5g@H*^#QE{1I3J}f;Rfmu>xNl8ad$o-N_xE5vNW=DVM{NBo6{AZ8=CAyT$E(h zc&HraK^`XFKphrvs*4JqT;ksKO*Uy`;=$LU=`&s1@Z+CaicO)+;N2e*1fg}7*OPZa zx;)9K5r&-OvR`H@Vi}_1y;(3X>0fMx^C)=_e;)Ys&SLaeQRYyRF!%uWivr~l&C>F+1Z-G8{gVVT zSd%FT-kSp6&O=60jb z+F1O-?X2;^MCzW7-IG0nir{uX{zHeoP~H6^8$|f^CqwrI3H$Wvw!PJv-FV&FXY;1R z8b14pq4F4|nAF3cZ>@5k@S^IMY4g0FO49>POjUx>#4FD@VfVxewq&Y*%C&sHEz7xB zqh~9-1{J!2v$6fqZZA~$-sjn|36=_}*BJGA$z_*NQ1=IJ+04x7b_jR Nqo{VPNFMJ0e*pTS%2)sZ From 8ddd55890d9857c3529c0f83962f9c7678f01065 Mon Sep 17 00:00:00 2001 From: Katie Dektar Date: Thu, 10 Dec 2020 16:26:47 -0800 Subject: [PATCH 31/40] Better error handling for files --- karel/src/robot.cc | 93 +++++++++++++++++++++++++++++++++------------- karel/src/robot.h | 4 +- 2 files changed, 70 insertions(+), 27 deletions(-) diff --git a/karel/src/robot.cc b/karel/src/robot.cc index 406fe62..6048813 100644 --- a/karel/src/robot.cc +++ b/karel/src/robot.cc @@ -65,6 +65,35 @@ const graphics::Color kWallColor(50, 50, 50); const graphics::Color kGridColor(220, 220, 220); const graphics::Color kErrorColor(173, 0, 35); +// Helper methods +void ParseWorldFileError(std::string error_text, int line_number) { + if (line_number > 0) { + error_text += " (line " + std::to_string(line_number) + ")"; + } + std::cout << error_text << std::endl << std::flush; + throw error_text; +} + +void CheckParsePosition(char open_paren, char comma, char closed_paren, + int line_number) { + if (open_paren != '(') { + ParseWorldFileError("Invalid syntax: expected open parenthesis but found " + + std::string(1, open_paren), + line_number); + } + if (comma != ',') { + ParseWorldFileError( + "Invalid syntax: expected a comma but found " + std::string(1, comma), + line_number); + } + if (closed_paren != ')') { + ParseWorldFileError( + "Invalid syntax: expected closed parenthesis but found " + + std::string(1, closed_paren), + line_number); + } +} + } // namespace Robot::Robot() {} @@ -96,8 +125,6 @@ void Robot::Initialize(std::string filename, bool enable_graphics, bool force_initialize) { // Ensure only intitialized once unless |force_initialize| is true. if (initialized_ && !force_initialize) return; - initialized_ = true; - error_ = RobotError::kNoError; finished_ = false; if (force_initialize) { prompt_between_actions_ = false; @@ -124,13 +151,13 @@ void Robot::Initialize(std::string filename, bool enable_graphics, try { world_file.open(filename); } catch (std::ifstream::failure e) { - throw std::string("Error opening file"); + ParseWorldFileError("Error opening file " + filename, -1); } if (!world_file.is_open()) { - // TODO: Replace throwables with better error codes? - throw std::string("Error opening file"); + ParseWorldFileError("Error opening file " + filename, -1); } std::string line; + int line_number = 1; const std::string dimension_prefix = "Dimension:"; const std::string beeper_prefix = "Beeper:"; @@ -143,15 +170,19 @@ void Robot::Initialize(std::string filename, bool enable_graphics, char open_paren, comma, closed_paren; if (!(world_file >> line_prefix >> open_paren >> x_dimen_ >> comma >> y_dimen_ >> closed_paren)) { - throw std::string("Could not find Dimension in first line"); + ParseWorldFileError( + "Could not parse world dimensions from the first line", line_number); } if (line_prefix != dimension_prefix) { - throw std::string("Could not find Dimension in first line"); + ParseWorldFileError("Could not find \"Dimension:\" in first line", + line_number); } + CheckParsePosition(open_paren, comma, closed_paren, line_number); if (x_dimen_ < 1 || y_dimen_ < 1) { - throw std::string( + ParseWorldFileError( "Cannot load a world less than 1 cell wide or less than 1 cell " - "tall"); + "tall", + line_number); } for (int i = 0; i < x_dimen_; i++) { world_.push_back(std::vector()); @@ -163,20 +194,23 @@ void Robot::Initialize(std::string filename, bool enable_graphics, // Read the rest of the file to get beepers and walls. // TODO: May need better error checking. while (world_file >> line_prefix) { + line_number++; if (line_prefix == wall_prefix) { - PositionAndOrientation wall = ParsePositionAndOrientation(world_file); + PositionAndOrientation wall = + ParsePositionAndOrientation(world_file, line_number); world_[wall.x][wall.y].AddWall(wall.orientation); } else if (line_prefix == beeper_prefix) { - PositionAndOrientation beeper = ParsePosition(world_file); + PositionAndOrientation beeper = ParsePosition(world_file, line_number); int count; if (!(world_file >> count)) { - throw std::string("Error reading Beeper count"); + ParseWorldFileError("Error reading Beeper count", line_number); } world_[beeper.x][beeper.y].SetNumBeepers(count); } else if (line_prefix == bag_prefix) { std::string beepers; if (!(world_file >> beepers)) { - throw std::string("Error reading quantity for BeeperBag"); + ParseWorldFileError("Error reading quantity for BeeperBag", + line_number); } if (beepers == "INFINITY" || beepers == "INFINITE") { beeper_count_ = std::numeric_limits::max(); @@ -184,21 +218,22 @@ void Robot::Initialize(std::string filename, bool enable_graphics, try { beeper_count_ = stoi(beepers); } catch (std::invalid_argument& e) { - throw std::string("Unknown BeeperBag quanity, " + beepers); + ParseWorldFileError("Unknown BeeperBag quanity, " + beepers, + line_number); } } } else if (line_prefix == karel_prefix) { - position_ = ParsePositionAndOrientation(world_file); + position_ = ParsePositionAndOrientation(world_file, line_number); } else if (line_prefix == speed_prefix) { if (!(world_file >> speed_)) { - throw std::string("Error reading Speed"); + ParseWorldFileError("Error reading Speed", line_number); } if (speed_ < 0) { - throw std::string("Speed must be greater than 0"); + ParseWorldFileError("Speed must be greater than 0", line_number); } } else { - std::cout << "unexpected token in file: " << line_prefix << std::endl - << std::flush; + ParseWorldFileError("Unexpected token in file: " + line_prefix, + line_number); break; } } @@ -208,6 +243,9 @@ void Robot::Initialize(std::string filename, bool enable_graphics, image_.Initialize(std::max(x_dimen_ * pxPerCell + margin, min_width), y_dimen_ * pxPerCell + margin); + initialized_ = true; + error_ = RobotError::kNoError; + DrawWorld(); DrawRobot(); Show(/* long duration */ true); @@ -354,6 +392,9 @@ void Robot::Finish() { if (enable_csv_output_) { WriteWorldCSV(); std::cout << "Finished. ctrl+c to exit." << std::endl << std::flush; + } else { + std::cout << "Finished. Close the image or ctrl+c to exit." << std::endl + << std::flush; } if (enable_graphics_) { image_.ShowUntilClosed("Karel's World"); @@ -712,12 +753,14 @@ void Robot::PromptBeforeActionIfNeeded() { // Note that the orientation is not populated. This is just a helper to // get the x and y position from a file with the next items in the stream // being (x, y) -PositionAndOrientation Robot::ParsePosition(std::fstream& file) const { +PositionAndOrientation Robot::ParsePosition(std::fstream& file, + int line_number) const { char open_paren, comma, closed_paren; int x, y; if (!(file >> open_paren >> x >> comma >> y >> closed_paren)) { - throw std::string("Error reading position"); + ParseWorldFileError("Error reading position", line_number); } + CheckParsePosition(open_paren, comma, closed_paren, line_number); PositionAndOrientation result; // Convert y in the file to y on-screen. In the file, (1, 1) is the // bottom left corner. @@ -731,11 +774,11 @@ PositionAndOrientation Robot::ParsePosition(std::fstream& file) const { // (3, 7) East // Direction may be lower-case or have an uppercase first letter. PositionAndOrientation Robot::ParsePositionAndOrientation( - std::fstream& file) const { - PositionAndOrientation result = ParsePosition(file); + std::fstream& file, int line_number) const { + PositionAndOrientation result = ParsePosition(file, line_number); std::string direction; if (!(file >> direction)) { - throw std::string("Error reading orientation"); + ParseWorldFileError("Error reading orientation", line_number); } // Ensure the first character is lower cased. direction[0] = tolower(direction[0]); @@ -748,7 +791,7 @@ PositionAndOrientation Robot::ParsePositionAndOrientation( } else if (direction == "west") { result.orientation = Orientation::kWest; } else { - throw std::string("Unknown orientation " + direction); + ParseWorldFileError("Unknown orientation " + direction, line_number); } return result; } diff --git a/karel/src/robot.h b/karel/src/robot.h index a9aab52..8261fbd 100644 --- a/karel/src/robot.h +++ b/karel/src/robot.h @@ -244,14 +244,14 @@ class Robot { * get the x and y position from a file with the next items in the stream * being (x, y) */ - PositionAndOrientation ParsePosition(std::fstream& file) const; + PositionAndOrientation ParsePosition(std::fstream& file, int line_number) const; /** * Helper to get orientation of the form, `(x, y) direction`, for example, * (3, 7) East * Direction may be lower-case or have an uppercase first letter. */ - PositionAndOrientation ParsePositionAndOrientation(std::fstream& file) const; + PositionAndOrientation ParsePositionAndOrientation(std::fstream& file, int line_number) const; // Whether graphics are enabled. They should probably be disabled for // testing. From 80447512fa1c4a6d3b21163152a48c6a3d96f179 Mon Sep 17 00:00:00 2001 From: Katie Dektar Date: Fri, 11 Dec 2020 10:21:09 -0800 Subject: [PATCH 32/40] Add to README, saving to BMP, and unittests for CSV and prompts --- README.md | 10 +- karel/README.md | 147 ----------------------------- karel/src/robot.cc | 34 ++++--- karel/src/robot.h | 5 + karel/src/test/karel.csv | 13 --- karel/src/test/karel_unittest.cc | 154 +++++++++++++++++++++++++------ 6 files changed, 159 insertions(+), 204 deletions(-) delete mode 100644 karel/README.md delete mode 100644 karel/src/test/karel.csv diff --git a/README.md b/README.md index 02a210e..014bd1b 100644 --- a/README.md +++ b/README.md @@ -16,10 +16,14 @@ Learn more about how to use the C++ Utils graphics class in this [interactive tu ## Karel the Robot in C++ -Karel the Robot is a gentle introductory programming language created by [Dr. Richard Pattis](https://www.ics.uci.edu/~pattis/) in [*Karel the Robot: A Gentle Introduction to The Art of Programming*](https://www.google.com/books/edition/_/ghcZAQAAIAAJ?hl=en&gbpv=1). The Karel language emphasizes logic while hiding tricky syntax, allowing anyone to begin making exciting graphical programs with very little background. +Karel the Robot is a gentle introductory programming language created by [Dr. Richard Pattis](https://www.ics.uci.edu/~pattis/) in [*Karel the Robot: A Gentle Introduction to The Art of Programming*](https://www.google.com/books/edition/_/ghcZAQAAIAAJ?hl=en&gbpv=1) and implemented in C++ here with his permission. The Karel language emphasizes logic while hiding tricky syntax, allowing anyone to begin making exciting graphical programs with very little background. ![karel the robot screenshot](karel/src/test/karel.png) +Karel lives in a two-dimensional grid and has a position and an orientation (north, east, south or west). Each cell of the grid may contain one or more beepers, or no beepers at all. Karel has a bag of beepers (which may be empty). Cells may be separated by walls. + +Karel has four actions: they can can move forward, turn left, put down a beeper or pick up a beeper. In addition, Karel is able to check state of the area around themselves. Karel cannot move through walls or off the edge of the world. + ### Accessibility Karel programs may export the world to CSV after each action. This may be helpful to screen-reader users. @@ -30,8 +34,8 @@ Karel programs may prompt before each robot action. This may be helpful for user To create Karel the Robot programs in C++, include ``karel/karel.h``. -(TODO): Learn more about how to use the C++ Utils Karel the Robot functions in this [interactive tutorial](https://github.com/ILXL-guides/intro-to-karel) +Learn more about how to use the C++ Utils Karel the Robot functions in this [interactive tutorial](https://lab.cs50.io/ILXL-guides/intro-to-karel) ## For developers and instructors -Read more about developing and including C++ Utils in the [wiki](https://github.com/ILXL/cpputils/wiki). +Read more about developing and including C++ Utils and unittesting assignments in the [wiki](https://github.com/ILXL/cpputils/wiki). diff --git a/karel/README.md b/karel/README.md deleted file mode 100644 index e2c3557..0000000 --- a/karel/README.md +++ /dev/null @@ -1,147 +0,0 @@ -# Karel the Robot in C++ - -TODO: Port README to a ILXL guide and the CPPUtils wiki. - -## Overview - -Karel lives in a two-dimensional grid where (1, 1) is at the bottom left corner. Karel has a position and an orientation in the grid (north, east, south or west). - -Each square of the grid may contain one or more beepers, or no beepers at all. Karel has a bag of beepers which may be empty or may contain many or even infinite beepers. - -Karel can move one cell and turn left. Karel can put down a beeper or pick up a beeper. In addition, Karel is able to check state of the area around themselves. - -Cells may be separated by walls. Karel cannot move through walls or off the edge of the world. - -Karel has four actions: - -```cpp -void Move(); -void TurnLeft(); -void PutBeeper(); -void PickBeeper(); -``` - -Karel has several booleans for getting robot state: -```cpp -bool FrontIsClear(); -bool FrontIsBlocked(); -bool LeftIsClear(); -bool LeftIsBlocked(); -bool RightIsClear(); -bool RightIsBlocked(); -bool HasBeepersInBag(); -bool NoBeepersInBag(); -bool BeepersPresent(); -bool NoBeepersPresent(); -bool FacingNorth(); -bool NotFacingNorth(); -bool FacingEast(); -bool NotFacingEast(); -bool FacingSouth(); -bool NotFacingSouth(); -bool FacingWest(); -bool NotFacingWest(); -``` - -``robot.h`` provides a Karel the Robot implementation in C++. This is functional programming: simply ``#include "cpputils/karel/karel.h"`` and call the Karel functions in the global namespace. - -### Example program - -```cpp -#include "cpputils/karel/karel.h" - -void TurnRight() { - TurnLeft(); - TurnLeft(); - TurnLeft(); -} - -void KarelProgram() { - while(FrontIsClear()) { - Move(); - } - TurnRight(); - Move(); - TurnLeft(); - Move(); - PickBeeper(); - TurnLeft(); - TurnLeft(); - while(FrontIsClear()) { - Move(); - } - TurnRight(); - Move(); - TurnRight(); -} - -int main() { - LoadWorld("worlds/CollectNewspaperKarel.w"); - KarelProgram(); - Finish(); - return 0; -} -``` - -### Building - -Compile (from the directory containing cpputils) with: - -``clang++ -std=c++17 test.cc cpputils/karel/karel.cc cpputils/karel/src/robot.cc cpputils/graphics/image.cc -o main -lm -lX11 -lpthread`` - -A few more flags are needed in Mac. - -## For instructors - -Instructors should call ``LoadWorld`` before student code and ``Finish`` after. - -```cpp -void LoadWorld(std::string filename); -void Finish(); -``` - -### World files - -Same as Stanford 106A. Dimension must be the first line. - -`CollectNewspaperKarel.w`: - -``` -Dimension: (7, 5) -Wall: (3, 2) west -Wall: (3, 2) south -Wall: (3, 3) west -Wall: (3, 4) west -Wall: (3, 5) south -Wall: (4, 2) south -Wall: (4, 5) south -Wall: (5, 2) south -Wall: (5, 5) south -Wall: (6, 2) west -Wall: (6, 4) west -Beeper: (6, 3) 1 -Karel: (3, 4) east -Speed: 1.00 -``` - -### Unit testing - -See ``src/test/karel_unittest.cc`` - -Must get robot instance with enable animations set to false -- so unittest shouldn't run over code that does Setup (and maybe not Finish either). Should just run over student functions. - -### Example CS1 course structure with Karel - -first weeks: -`make build` -karel: - logic - vars (ints) - loops & ifs - functions --> TurnRight() { TurnLeft(); TurnLeft(); TurnLeft(); } - -later weeks: -clang++ main.cc -o main -doubles -vectors -strings diff --git a/karel/src/robot.cc b/karel/src/robot.cc index 6048813..59dd6d6 100644 --- a/karel/src/robot.cc +++ b/karel/src/robot.cc @@ -18,10 +18,6 @@ #include "error.h" #include "orientation.h" -// TODO: Save to image file (maybe for testing) -// documentation -// file error states - namespace karel { namespace { @@ -65,6 +61,8 @@ const graphics::Color kWallColor(50, 50, 50); const graphics::Color kGridColor(220, 220, 220); const graphics::Color kErrorColor(173, 0, 35); +const std::string kCSVFilename = "karel.csv"; + // Helper methods void ParseWorldFileError(std::string error_text, int line_number) { if (line_number > 0) { @@ -431,6 +429,13 @@ int Robot::GetWorldHeight() const { return y_dimen_; } RobotError Robot::GetError() const { return error_; } +void Robot::SaveWorldBmp(std::string filename) const { + if (!image_.SaveImageBmp(filename)) { + std::cout << "Failed to save image to " << filename << std::endl + << std::flush; + } +} + void Robot::Show(bool long_duration) { if (finished_) return; if (long_duration && enable_csv_output_) { @@ -443,11 +448,10 @@ void Robot::Show(bool long_duration) { } void Robot::WriteWorldCSV() { - const std::string filename = "karel.csv"; std::ofstream csv; - csv.open(filename); + csv.open(kCSVFilename); if (!csv.is_open()) { - std::cout << "Error: Could not open " << filename + std::cout << "Error: Could not open " << kCSVFilename << " to write Karel's world. Perhaps it is opened by another " "application?" << std::endl @@ -476,16 +480,17 @@ void Robot::WriteWorldCSV() { csv << "o "; } csv << "(" << x + 1 << "," << y_dimen_ - y << ")\","; - if (x < x_dimen_ - 1 && - (cell.HasEastWall() || world_[x + 1][y].HasWestWall())) { - csv << "w,"; - } else { - csv << ","; + if (x < x_dimen_ - 1) { + if (cell.HasEastWall() || world_[x + 1][y].HasWestWall()) { + csv << "w,"; + } else { + csv << ","; + } } } csv << std::endl; if (y < y_dimen_ - 1) { - for (int x = 0; x < x_dimen_; x++) { + for (int x = 0; x < x_dimen_ - 1; x++) { // print bottom walls and next top walls if (world_[x][y].HasSouthWall() || world_[x][y + 1].HasNorthWall()) { csv << "w,,"; @@ -503,7 +508,8 @@ void Robot::WriteWorldCSV() { "between cells,cell coordinates\n"; // TODO: Write error state and a key. csv.close(); - std::cout << "World state written to " << filename << std::endl << std::flush; + std::cout << "World state written to " << kCSVFilename << std::endl + << std::flush; } void Robot::Error(RobotError error) { diff --git a/karel/src/robot.h b/karel/src/robot.h index 8261fbd..0012932 100644 --- a/karel/src/robot.h +++ b/karel/src/robot.h @@ -188,6 +188,11 @@ class Robot { */ RobotError GetError() const; + /** + * Saves an image of Karel's world with the given filename in .bmp format. + */ + void SaveWorldBmp(std::string filename) const; + private: // Private constructor: Robot can only be accessed with GetInstance. Robot(); diff --git a/karel/src/test/karel.csv b/karel/src/test/karel.csv deleted file mode 100644 index d14b508..0000000 --- a/karel/src/test/karel.csv +++ /dev/null @@ -1,13 +0,0 @@ -"o (1,5)",,"o (2,5)",,"o (3,5)",,"o (4,5)",,"o (5,5)",,"o (6,5)",,"o (7,5)",, -,,,,w,,w,,w,,,,,, -"o (1,4)",,"o (2,4)",w,"o (3,4)",,"ke o (4,4)",,"o (5,4)",w,"o (6,4)",,"o (7,4)",, -,,,,,,,,,,,,,, -"o (1,3)",,"o (2,3)",w,"o (3,3)",,"o (4,3)",,"o (5,3)",,"b (6,3)",,"o (7,3)",, -,,,,,,,,,,,,,, -"o (1,2)",,"o (2,2)",w,"o (3,2)",,"o (4,2)",,"o (5,2)",w,"o (6,2)",,"o (7,2)",, -,,,,w,,w,,w,,,,,, -"o (1,1)",,"o (2,1)",,"o (3,1)",,"o (4,1)",,"o (5,1)",,"o (6,1)",,"o (7,1)",, - - -key,Karel facing north,Karel facing east, Karel facing south, Karel facing west,empty cell,cell with at least one beeper,wall between cells,cell coordinates -,kn,ke,ks,kw,o,b,w,"(x,y)" diff --git a/karel/src/test/karel_unittest.cc b/karel/src/test/karel_unittest.cc index 65b128f..2d8406c 100644 --- a/karel/src/test/karel_unittest.cc +++ b/karel/src/test/karel_unittest.cc @@ -22,6 +22,7 @@ using karel::RobotError; // Test TODOs: // Test loading bad files and helpful output +// Test CSV output: walls and beepers bool IsBasicallyInfinite(int number) { return number > std::numeric_limits::max() / 2; @@ -35,19 +36,12 @@ void CellIsEmptyWithNoWalls(const Cell& cell) { ASSERT_FALSE(cell.HasWestWall()); } -class KarelTest : public testing::Test { - public: - void SetUp() override { - // TODO. - } -}; - -TEST_F(KarelTest, GetsKarelInstance) { +TEST(KarelTest, GetsKarelInstance) { Robot& r = Robot::GetInstance(/* enable animations */ false, /* force initialize */ true); } -TEST_F(KarelTest, DefaultWorld) { +TEST(KarelTest, DefaultWorld) { Robot& r = Robot::GetInstance(/* enable animations */ false, /* force initialize */ true); @@ -69,7 +63,7 @@ TEST_F(KarelTest, DefaultWorld) { ASSERT_TRUE(IsBasicallyInfinite(r.GetNumBeepersInBag())); } -TEST_F(KarelTest, LoadsWorld) { +TEST(KarelTest, LoadsWorld) { Robot& r = Robot::InitializeInstance("worlds/2x1.w", /* enable animations */ false, /* force initialize */ true); @@ -84,7 +78,7 @@ TEST_F(KarelTest, LoadsWorld) { ASSERT_TRUE(IsBasicallyInfinite(r.GetNumBeepersInBag())); } -TEST_F(KarelTest, LoadsWorldWithInfinityBeepers) { +TEST(KarelTest, LoadsWorldWithInfinityBeepers) { // INFINITY vs INFINITE Robot& r = Robot::InitializeInstance("worlds/8x1.w", /* enable animations */ false, @@ -92,21 +86,21 @@ TEST_F(KarelTest, LoadsWorldWithInfinityBeepers) { ASSERT_TRUE(IsBasicallyInfinite(r.GetNumBeepersInBag())); } -TEST_F(KarelTest, LoadsWorldWithNoBeepersInBag) { +TEST(KarelTest, LoadsWorldWithNoBeepersInBag) { Robot& r = Robot::InitializeInstance("worlds/beepers.w", /* enable animations */ false, /* force initialize */ true); EXPECT_EQ(0, r.GetNumBeepersInBag()); } -TEST_F(KarelTest, LoadsWorldWithFiniteBeepers) { +TEST(KarelTest, LoadsWorldWithFiniteBeepers) { Robot& r = Robot::InitializeInstance("worlds/inner_walls.w", /* enable animations */ false, /* force initialize */ true); EXPECT_EQ(42, r.GetNumBeepersInBag()); } -TEST_F(KarelTest, LoadsWorldWithBeepersInCells) { +TEST(KarelTest, LoadsWorldWithBeepersInCells) { Robot& r = Robot::InitializeInstance("worlds/beepers.w", /* enable animations */ false, /* force initialize */ true); @@ -116,7 +110,7 @@ TEST_F(KarelTest, LoadsWorldWithBeepersInCells) { EXPECT_EQ(4, r.GetCell(4, 4).GetNumBeepers()); } -TEST_F(KarelTest, LoadsWorldWithOuterWalls) { +TEST(KarelTest, LoadsWorldWithOuterWalls) { Robot& r = Robot::InitializeInstance("worlds/outer_walls.w", /* enable animations */ false, /* force initialize */ true); @@ -137,7 +131,7 @@ TEST_F(KarelTest, LoadsWorldWithOuterWalls) { ASSERT_EQ(6, r.GetYPosition()); } -TEST_F(KarelTest, LoadsWorldWithInnerWalls) { +TEST(KarelTest, LoadsWorldWithInnerWalls) { Robot& r = Robot::InitializeInstance("worlds/inner_walls.w", /* enable animations */ false, /* force initialize */ true); @@ -153,7 +147,7 @@ TEST_F(KarelTest, LoadsWorldWithInnerWalls) { ASSERT_EQ(2, r.GetYPosition()); } -TEST_F(KarelTest, CannotMoveThroughOuterWalls) { +TEST(KarelTest, CannotMoveThroughOuterWalls) { for (int i = 0; i < 4; i++) { Robot& r = Robot::InitializeInstance("worlds/outer_walls.w", /* enable animations */ false, @@ -185,7 +179,7 @@ TEST_F(KarelTest, CannotMoveThroughOuterWalls) { } } -TEST_F(KarelTest, CannotMoveThroughInnerWalls) { +TEST(KarelTest, CannotMoveThroughInnerWalls) { for (int i = 0; i < 4; i++) { Robot& r = Robot::InitializeInstance("worlds/inner_walls.w", /* enable animations */ false, @@ -217,7 +211,7 @@ TEST_F(KarelTest, CannotMoveThroughInnerWalls) { } } -TEST_F(KarelTest, CannotMoveThroughWorldEdges) { +TEST(KarelTest, CannotMoveThroughWorldEdges) { for (int i = 0; i < 4; i++) { Robot& r = Robot::InitializeInstance("worlds/2x1.w", /* enable animations */ false, @@ -245,7 +239,7 @@ TEST_F(KarelTest, CannotMoveThroughWorldEdges) { } } -TEST_F(KarelTest, PutsAndPicksBeeper) { +TEST(KarelTest, PutsAndPicksBeeper) { // Default world has no beepers, and Karel has infinite. Robot& r = Robot::GetInstance(/* enable animations */ false, /* force initialize */ true); @@ -268,7 +262,7 @@ TEST_F(KarelTest, PutsAndPicksBeeper) { } } -TEST_F(KarelTest, PicksManyBeepers) { +TEST(KarelTest, PicksManyBeepers) { Robot& r = Robot::InitializeInstance("worlds/beepers.w", /* enable animations */ false, /* force initialize */ true); @@ -329,7 +323,7 @@ TEST_F(KarelTest, PicksManyBeepers) { EXPECT_TRUE(NoBeepersPresent()); } -TEST_F(KarelTest, CannotPickMissingBeeper) { +TEST(KarelTest, CannotPickMissingBeeper) { Robot& r = Robot::GetInstance(/* enable animations */ false, /* force initialize */ true); ASSERT_EQ(RobotError::kNoError, r.GetError()); @@ -337,7 +331,7 @@ TEST_F(KarelTest, CannotPickMissingBeeper) { ASSERT_EQ(RobotError::kCannotPickBeeper, r.GetError()); } -TEST_F(KarelTest, CannotPutWhenBeeperBagEmpty) { +TEST(KarelTest, CannotPutWhenBeeperBagEmpty) { Robot& r = Robot::InitializeInstance("worlds/beepers.w", /* enable animations */ false, /* force initialize */ true); @@ -346,7 +340,7 @@ TEST_F(KarelTest, CannotPutWhenBeeperBagEmpty) { ASSERT_EQ(RobotError::kCannotPutBeeper, r.GetError()); } -TEST_F(KarelTest, TurnsLeft) { +TEST(KarelTest, TurnsLeft) { Robot& r = Robot::GetInstance(/* enable animations */ false, /* force initialize */ true); int count = 10; @@ -401,7 +395,7 @@ TEST_F(KarelTest, TurnsLeft) { } } -TEST_F(KarelTest, MovesEastAndWest) { +TEST(KarelTest, MovesEastAndWest) { Robot& r = Robot::InitializeInstance("worlds/8x1.w", /* enable animations */ false, /* force initialize */ true); @@ -423,7 +417,7 @@ TEST_F(KarelTest, MovesEastAndWest) { } } -TEST_F(KarelTest, MovesNorthAndSouth) { +TEST(KarelTest, MovesNorthAndSouth) { Robot& r = Robot::InitializeInstance("worlds/1x8.w", /* enable animations */ false, /* force initialize */ true); @@ -446,7 +440,7 @@ TEST_F(KarelTest, MovesNorthAndSouth) { } } -TEST_F(KarelTest, DoesNotTakeActionAfterErrorState) { +TEST(KarelTest, DoesNotTakeActionAfterErrorState) { Robot& r = Robot::InitializeInstance("worlds/beepers.w", /* enable graphics */ false, /* force initialize */ true); @@ -486,6 +480,112 @@ TEST_F(KarelTest, DoesNotTakeActionAfterErrorState) { EXPECT_EQ(0, r.GetNumBeepersInBag()); } +TEST(KarelTest, SavesWorldBmp) { + Robot& r = Robot::GetInstance(/* enable graphics */ false, + /* force initialize */ true); + std::string name = "test_world.bmp"; + std::ifstream stream(name.c_str()); + ASSERT_FALSE(stream.good()); + r.SaveWorldBmp(name); + graphics::Image image; + image.Load(name); + ASSERT_TRUE(image.GetWidth() > 0); + ASSERT_TRUE(image.GetHeight() > 0); + remove(name.c_str()); +} + +TEST(KarelTest, PromptsBetweenActionsWhenSet) { + std::streambuf* original = std::cin.rdbuf(); + std::istringstream stream("c\nc\n"); + std::cin.rdbuf(stream.rdbuf()); + + std::streambuf* original_out = std::cout.rdbuf(); + std::stringstream stream_out; + std::cout.rdbuf(stream_out.rdbuf()); + + Robot& r = Robot::InitializeInstance("worlds/2x1.w", + /* enable graphics */ false, + /* force initialize */ true); + Move(); + TurnLeft(); + TurnLeft(); + EXPECT_EQ(2, r.GetXPosition()); + EXPECT_EQ(Orientation::kWest, r.GetOrientation()); + EXPECT_THAT( + stream_out.str(), + Not(testing::MatchesRegex(".*Enter any character to continue.*Enter any " + "character to continue.*"))); + + EnablePromptBeforeAction(); + Move(); + TurnLeft(); + EXPECT_EQ(1, r.GetXPosition()); + EXPECT_EQ(Orientation::kSouth, r.GetOrientation()); + EXPECT_THAT(stream_out.str(), + testing::MatchesRegex(".*Enter any character to continue.*Enter " + "any character to continue.*")); + + std::cin.rdbuf(original); + std::cout.rdbuf(original_out); +} + +TEST(KarelTest, PromptsBetweenActionsWhenCSVOutputSet) { + std::streambuf* original = std::cin.rdbuf(); + std::istringstream stream("ada\nlovelace\n"); + std::cin.rdbuf(stream.rdbuf()); + + std::streambuf* original_out = std::cout.rdbuf(); + std::stringstream stream_out; + std::cout.rdbuf(stream_out.rdbuf()); + + Robot& r = Robot::InitializeInstance("worlds/2x1.w", + /* enable graphics */ false, + /* force initialize */ true); + Move(); + TurnLeft(); + TurnLeft(); + EXPECT_EQ(2, r.GetXPosition()); + EXPECT_EQ(Orientation::kWest, r.GetOrientation()); + EXPECT_THAT( + stream_out.str(), + Not(testing::MatchesRegex(".*Enter any character to continue.*Enter any " + "character to continue.*"))); + + EnableCSVOutput(); + Move(); + TurnLeft(); + EXPECT_EQ(1, r.GetXPosition()); + EXPECT_EQ(Orientation::kSouth, r.GetOrientation()); + EXPECT_THAT(stream_out.str(), + testing::MatchesRegex(".*Enter any character to continue.*Enter " + "any character to continue.*")); + + std::cin.rdbuf(original); + std::cout.rdbuf(original_out); + remove("karel.csv"); +} + +TEST(KarelTest, GeneratesCSVOutput) { + Robot& r = Robot::InitializeInstance("worlds/2x1.w", + /* enable graphics */ false, + /* force initialize */ true); + std::ifstream stream("karel.csv"); + ASSERT_FALSE(stream.good()); + + EnableCSVOutput(); + // Should immediately write the world to a CSV file. + stream = std::ifstream("karel.csv"); + ASSERT_TRUE(stream.good()); + + // The first line of the CSV is the world with karel in the first cell. + std::string line; + ASSERT_TRUE(std::getline(stream, line)); + ASSERT_TRUE(line.size() > 0); + ASSERT_EQ(line, "\"ke o (1,1)\",,\"o (2,1)\""); + + remove("karel.csv"); +} + int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); From cf4ec66159fe5793093cba46c74ab644935789b9 Mon Sep 17 00:00:00 2001 From: Katie Dektar Date: Fri, 11 Dec 2020 10:27:28 -0800 Subject: [PATCH 33/40] Fix karel unittest by adding trailing comma back --- karel/src/test/karel_unittest.cc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/karel/src/test/karel_unittest.cc b/karel/src/test/karel_unittest.cc index 2d8406c..e4e262a 100644 --- a/karel/src/test/karel_unittest.cc +++ b/karel/src/test/karel_unittest.cc @@ -581,7 +581,7 @@ TEST(KarelTest, GeneratesCSVOutput) { std::string line; ASSERT_TRUE(std::getline(stream, line)); ASSERT_TRUE(line.size() > 0); - ASSERT_EQ(line, "\"ke o (1,1)\",,\"o (2,1)\""); + ASSERT_EQ(line, "\"ke o (1,1)\",,\"o (2,1)\","); remove("karel.csv"); } From 883024fd9840b6be39c9254dd92c53bf3908b72f Mon Sep 17 00:00:00 2001 From: Katie Dektar Date: Fri, 11 Dec 2020 10:29:39 -0800 Subject: [PATCH 34/40] remove karel branch from github actions --- .github/workflows/c-cpp.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/c-cpp.yml b/.github/workflows/c-cpp.yml index 3eceffa..7db8138 100644 --- a/.github/workflows/c-cpp.yml +++ b/.github/workflows/c-cpp.yml @@ -2,7 +2,7 @@ name: C/C++ CI on: push: - branches: [ master, v1, v2, karel ] + branches: [ master, v1, v2 ] pull_request: branches: [ master ] From 4d60363d3a6901a858057ec114d6123e64f55155 Mon Sep 17 00:00:00 2001 From: Katie Dektar Date: Fri, 11 Dec 2020 16:39:02 -0800 Subject: [PATCH 35/40] Add error message to csv --- README.md | 2 +- karel/src/robot.cc | 64 ++++++++++++++++++++++++++-------------------- 2 files changed, 37 insertions(+), 29 deletions(-) diff --git a/README.md b/README.md index 014bd1b..92a87a8 100644 --- a/README.md +++ b/README.md @@ -22,7 +22,7 @@ Karel the Robot is a gentle introductory programming language created by [Dr. Ri Karel lives in a two-dimensional grid and has a position and an orientation (north, east, south or west). Each cell of the grid may contain one or more beepers, or no beepers at all. Karel has a bag of beepers (which may be empty). Cells may be separated by walls. -Karel has four actions: they can can move forward, turn left, put down a beeper or pick up a beeper. In addition, Karel is able to check state of the area around themselves. Karel cannot move through walls or off the edge of the world. +Karel has four actions: they can move forward, turn left, put down a beeper or pick up a beeper. In addition, Karel is able to check state of the area around themselves. Karel cannot move through walls or off the edge of the world. ### Accessibility diff --git a/karel/src/robot.cc b/karel/src/robot.cc index 59dd6d6..be8a5b3 100644 --- a/karel/src/robot.cc +++ b/karel/src/robot.cc @@ -92,6 +92,34 @@ void CheckParsePosition(char open_paren, char comma, char closed_paren, } } +std::string GetErrorMessage(RobotError error) { + std::string message = "Error: "; + switch (error) { + case kNoError: + // This shouldn't happen. + return ""; + case kCannotMoveNorth: + message += " Cannot move north"; + break; + case kCannotMoveEast: + message += " Cannot move east"; + break; + case kCannotMoveSouth: + message += " Cannot move south"; + break; + case kCannotMoveWest: + message += " Cannot move west"; + break; + case kCannotPickBeeper: + message += "Cannot pick beeper\n(No beepers present)"; + break; + case kCannotPutBeeper: + message += " Cannot put beeper\n(No beepers in bag)"; + break; + } + return message; +} + } // namespace Robot::Robot() {} @@ -128,6 +156,10 @@ void Robot::Initialize(std::string filename, bool enable_graphics, prompt_between_actions_ = false; enable_csv_output_ = false; } + // Reset default speed and beeper count. + speed_ = 1; + // Nearly infinite beepers. + beeper_count_ = std::numeric_limits::max(); world_.clear(); enable_graphics_ = enable_graphics; @@ -141,8 +173,6 @@ void Robot::Initialize(std::string filename, bool enable_graphics, world_[i].push_back(Cell()); } } - // Nearly infinite beepers. - beeper_count_ = std::numeric_limits::max(); position_ = {0, kDefaultDimen - 1, Orientation::kEast}; } else { std::fstream world_file; @@ -190,7 +220,6 @@ void Robot::Initialize(std::string filename, bool enable_graphics, } // Read the rest of the file to get beepers and walls. - // TODO: May need better error checking. while (world_file >> line_prefix) { line_number++; if (line_prefix == wall_prefix) { @@ -501,12 +530,11 @@ void Robot::WriteWorldCSV() { } csv << std::endl; } - csv << std::endl; + csv << GetErrorMessage(error_) << std::endl; csv << "symbol,kn,ke,ks,kw,o,b,w,\"(x,y)\"\n"; csv << "meaning,Karel facing north,Karel facing east, Karel facing south, " "Karel facing west,empty cell,cell with at least one beeper,wall " "between cells,cell coordinates\n"; - // TODO: Write error state and a key. csv.close(); std::cout << "World state written to " << kCSVFilename << std::endl << std::flush; @@ -514,30 +542,10 @@ void Robot::WriteWorldCSV() { void Robot::Error(RobotError error) { error_ = error; - std::string message = "Error: "; - switch (error) { - case kNoError: - // This shouldn't happen. - return; - case kCannotMoveNorth: - message += " Cannot move north"; - break; - case kCannotMoveEast: - message += " Cannot move east"; - break; - case kCannotMoveSouth: - message += " Cannot move south"; - break; - case kCannotMoveWest: - message += " Cannot move west"; - break; - case kCannotPickBeeper: - message += "Cannot pick beeper\n(No beepers present)"; - break; - case kCannotPutBeeper: - message += " Cannot put beeper\n(No beepers in bag)"; - break; + if (error_ == RobotError::kNoError) { + return; } + std::string message = GetErrorMessage(error); std::cout << message << std::endl << std::flush; int approx_width = 25 * kErrorFontSize / 4; int text_x = std::max(2, image_.GetWidth() / 2 - approx_width); From 7e1965da5175177b8a72122f9d59a27bafb62b2d Mon Sep 17 00:00:00 2001 From: Katie Dektar Date: Sun, 13 Dec 2020 20:24:49 -0800 Subject: [PATCH 36/40] Fix overflow beepers bug --- karel/src/robot.cc | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/karel/src/robot.cc b/karel/src/robot.cc index be8a5b3..e0a6a73 100644 --- a/karel/src/robot.cc +++ b/karel/src/robot.cc @@ -354,7 +354,9 @@ void Robot::PutBeeper() { Error(RobotError::kCannotPutBeeper); return; } - beeper_count_--; + if (beeper_count_ != std::numeric_limits::max()) { + beeper_count_--; + } Cell& cell = world_[position_.x][position_.y]; cell.SetNumBeepers(cell.GetNumBeepers() + 1); DrawWorld(); @@ -371,7 +373,9 @@ void Robot::PickBeeper() { } Cell& cell = world_[position_.x][position_.y]; cell.SetNumBeepers(cell.GetNumBeepers() - 1); - beeper_count_++; + if (beeper_count_ != std::numeric_limits::max()) { + beeper_count_++; + } DrawWorld(); DrawRobot(); Show(/* long duration */ true); From 8f2ab4442421395ecad8b173d03c8e663f410589 Mon Sep 17 00:00:00 2001 From: Katie Dektar Date: Mon, 14 Dec 2020 09:22:10 -0800 Subject: [PATCH 37/40] Fix left vs right bug --- karel/src/robot.cc | 4 ++-- karel/src/test/karel_unittest.cc | 12 ++++++++++++ 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/karel/src/robot.cc b/karel/src/robot.cc index e0a6a73..7380247 100644 --- a/karel/src/robot.cc +++ b/karel/src/robot.cc @@ -393,12 +393,12 @@ bool Robot::FrontIsClear() const { bool Robot::LeftIsClear() const { return DirectionIsClear(static_cast( - (static_cast(position_.orientation) + 1) % 4)); + (static_cast(position_.orientation) - 1 + 4) % 4)); } bool Robot::RightIsClear() const { return DirectionIsClear(static_cast( - (static_cast(position_.orientation) - 1 + 4) % 4)); + (static_cast(position_.orientation) + 1) % 4)); } bool Robot::FacingNorth() const { diff --git a/karel/src/test/karel_unittest.cc b/karel/src/test/karel_unittest.cc index e4e262a..7b4cd5a 100644 --- a/karel/src/test/karel_unittest.cc +++ b/karel/src/test/karel_unittest.cc @@ -61,6 +61,11 @@ TEST(KarelTest, DefaultWorld) { ASSERT_EQ(1, r.GetYPosition()); ASSERT_EQ(Orientation::kEast, r.GetOrientation()); ASSERT_TRUE(IsBasicallyInfinite(r.GetNumBeepersInBag())); + // Facing east, so the right is blocked. + EXPECT_FALSE(RightIsClear()); + EXPECT_TRUE(RightIsBlocked()); + EXPECT_TRUE(LeftIsClear()); + EXPECT_FALSE(LeftIsBlocked()); } TEST(KarelTest, LoadsWorld) { @@ -76,6 +81,13 @@ TEST(KarelTest, LoadsWorld) { ASSERT_EQ(1, r.GetYPosition()); ASSERT_EQ(Orientation::kEast, r.GetOrientation()); ASSERT_TRUE(IsBasicallyInfinite(r.GetNumBeepersInBag())); + + ASSERT_TRUE(FrontIsClear()); + ASSERT_FALSE(FrontIsBlocked()); + EXPECT_FALSE(RightIsClear()); + EXPECT_TRUE(RightIsBlocked()); + EXPECT_FALSE(LeftIsClear()); + EXPECT_TRUE(LeftIsBlocked()); } TEST(KarelTest, LoadsWorldWithInfinityBeepers) { From 61e36deef2685eba76c98fcc27c5b67dcdc99e3a Mon Sep 17 00:00:00 2001 From: Katie Dektar Date: Mon, 14 Dec 2020 12:34:02 -0800 Subject: [PATCH 38/40] Lower speeds are slower instead of lower speeds faster --- karel/src/robot.cc | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/karel/src/robot.cc b/karel/src/robot.cc index 7380247..0689310 100644 --- a/karel/src/robot.cc +++ b/karel/src/robot.cc @@ -257,6 +257,9 @@ void Robot::Initialize(std::string filename, bool enable_graphics, } if (speed_ < 0) { ParseWorldFileError("Speed must be greater than 0", line_number); + } else if (speed_ < 0.1) { + // Minimum speed. + speed_ = 0.1; } } else { ParseWorldFileError("Unexpected token in file: " + line_prefix, @@ -475,7 +478,7 @@ void Robot::Show(bool long_duration) { WriteWorldCSV(); } if (enable_graphics_) { - image_.ShowForMs((long_duration ? kLongDuration : kShortDuration) * speed_, + image_.ShowForMs((long_duration ? kLongDuration : kShortDuration) / speed_, "Karel's World"); } } @@ -523,7 +526,7 @@ void Robot::WriteWorldCSV() { } csv << std::endl; if (y < y_dimen_ - 1) { - for (int x = 0; x < x_dimen_ - 1; x++) { + for (int x = 0; x < x_dimen_; x++) { // print bottom walls and next top walls if (world_[x][y].HasSouthWall() || world_[x][y + 1].HasNorthWall()) { csv << "w,,"; From 033f1ae92a355f27bd807bfa09eb11e216777314 Mon Sep 17 00:00:00 2001 From: Katie Dektar Date: Mon, 14 Dec 2020 13:59:15 -0800 Subject: [PATCH 39/40] Replace "dr" with "professor" --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 92a87a8..6a2b289 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ Learn more about how to use the C++ Utils graphics class in this [interactive tu ## Karel the Robot in C++ -Karel the Robot is a gentle introductory programming language created by [Dr. Richard Pattis](https://www.ics.uci.edu/~pattis/) in [*Karel the Robot: A Gentle Introduction to The Art of Programming*](https://www.google.com/books/edition/_/ghcZAQAAIAAJ?hl=en&gbpv=1) and implemented in C++ here with his permission. The Karel language emphasizes logic while hiding tricky syntax, allowing anyone to begin making exciting graphical programs with very little background. +Karel the Robot is a gentle introductory programming language created by [Professor Richard Pattis](https://www.ics.uci.edu/~pattis/) in [*Karel the Robot: A Gentle Introduction to The Art of Programming*](https://www.google.com/books/edition/_/ghcZAQAAIAAJ?hl=en&gbpv=1) and implemented in C++ here with his permission. The Karel language emphasizes logic while hiding tricky syntax, allowing anyone to begin making exciting graphical programs with very little background. ![karel the robot screenshot](karel/src/test/karel.png) From 3c05d3345321e9c477c7299afe7202262fbc0cfc Mon Sep 17 00:00:00 2001 From: Katie Dektar Date: Mon, 11 Jan 2021 20:05:50 -0800 Subject: [PATCH 40/40] Adds beeper count when beepers > 1 (fixes #7) --- karel/src/robot.cc | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/karel/src/robot.cc b/karel/src/robot.cc index 0689310..adbbda6 100644 --- a/karel/src/robot.cc +++ b/karel/src/robot.cc @@ -511,7 +511,7 @@ void Robot::WriteWorldCSV() { } } if (cell.GetNumBeepers() > 0) { - csv << "b "; + csv << "b" << cell.GetNumBeepers() << " "; } else { csv << "o "; } @@ -540,7 +540,7 @@ void Robot::WriteWorldCSV() { csv << GetErrorMessage(error_) << std::endl; csv << "symbol,kn,ke,ks,kw,o,b,w,\"(x,y)\"\n"; csv << "meaning,Karel facing north,Karel facing east, Karel facing south, " - "Karel facing west,empty cell,cell with at least one beeper,wall " + "Karel facing west,empty cell,cell with beepers and count,wall " "between cells,cell coordinates\n"; csv.close(); std::cout << "World state written to " << kCSVFilename << std::endl @@ -644,7 +644,8 @@ void Robot::DrawWorld() { image_.DrawLine(x_center, y_center - markSize / 2, x_center, y_center + markSize / 2, markColor, kWallThickness); Cell& cell = world_[i][j]; - if (cell.GetNumBeepers() > 0) { + int beeper_count = cell.GetNumBeepers(); + if (beeper_count > 0) { // Draw the beepers. Beepers are stacked so you can't tell if there's // more than one in a stack. // trig to get diamonds from thick lines! @@ -658,6 +659,11 @@ void Robot::DrawWorld() { image_.DrawLine(x_center - inner_line_size, y_center - inner_line_size, x_center + inner_line_size, y_center + inner_line_size, innerBeeperColor, inner_beeper_size); + if (beeper_count > 1) { + // Draw the beeper count in the cell if it's biger than 1. + image_.DrawText(x_center - fontSize / 4, y_center - fontSize / 2, + std::to_string(beeper_count), fontSize, kWallColor); + } } // Draw the walls. if (cell.HasNorthWall()) {