Hot answers tagged

32

Repetitions All your elif share the same structure. You just need to ensure that the inserted pattern is always 3 wide and you can drop your offsets adjustments. The logical next step is to use a dictionary to store the pattern and the row for each attempt: _GOWN_MODIFIER = { 1: (' O ', 2), 2: (' | ', 3), 3: ('/| ', 3), 4: ('/|\\', 3), ...


29

You define a clear_screen function, but then at the top you have #opening statement os.system('cls') # Here print ('Welcome to the Hangman!\n') You might as well use the function there. A little further down you have: while game_on is True: The is check is only necessary if game_on could be some truthy value other than True, and you wanted to check if ...


25

Some initial comments: I started by running the game without reading the code, to see what would happen. $ python hangman.py ++++++++++++++++++Hangman++++++++++++++++++++++ =============================================== |-- Level --|-- Tries --|-- Hints Given --| |-- Easy --|-- 10 --|-- 2 --| |-- Medium --|-- 8 --|-- 1 ...


23

Welcome to Python, and welcome to Code Review! Here are some basic tips to help you along. 0.5. EDIT: I think you also have an unused import. import string is not needed. Consider using a style guideline like PEP8. This is more of a general suggestion and will make your future code much more readable and maintainable. Consider defining all your constants ...


15

Prefer '\n' to std::endl The only difference is that std::endl will flush the stream after putting the '\n' character on it. Flushing the stream manually is almost always a waste of time as the stream will auto flush when required and any attempt by a human is ultimately at the wrong time. Data Driven programming. Rather than have a big set of if else ...


14

You may group your STL #includes either alphabetically, or by groups (credit to @Loki Astari in a different answer): // This is Class.cpp #include "Class.h" #include "OtherMyClassIdependon1.h" #include "OtherMyClassIdependon1.h" // Now C++ header files // Lots of people order these alphabetically #include <string> // Personally I group them ...


14

I will proceed from a high level to a low level perspective. Starting with main.cpp: Game pass; pass.onOffSwitch("close"); The meaning of these two lines are not clear without reading the contents of the class Game. That means that not only do I need other pieces of code, but different files, to understand these two lines. Having looked into the Game ...


13

Single Responsibility Principle The class Game does too much directly, this could be an aggregation of classes instead. One of the points of the Single Responsibility Principle is that a class or function has limited tasks to perform so that it is easier to write, read and debug. The file input should have it's own class that game might evoke. The single ...


13

It's not that great of an optimization but if you're new to programming it can be interesting to consider something along the line of : hangman_part = ['O','|','/','\\','/','\\'] hangman_base =''' +---+ | | 0 | 213 | 4 5 | | =========''' and def get_current_figure(): """Print current state of Hangman.""" hangman_pic = ...


12

Exiting The code is pretty long and I've just complained on meta that there's no way to view it properly. So I restrict myself to a few comments and let others to comment on other aspects. default: System.exit(0); I'd never do that. It's like placing a bomb in the code. One day someone will want to reuse a part of it and there's no easy way to find ...


11

A few thoughts: Instead of do { std::getline(words_file, word); words.push_back(word); } while (!words_file.eof()); You should do while(std::getline(words_file, word)) words.push_back(word); } Otherwise, the read which causes the stream to go into an invalid state will still be pushed. Also, why not include the filename that cannot be ...


11

Overview I can see that you are a beginner and that is totally fine! Some of the points I will be making might, sound a bit harsh and go over your head. If they do try to improve the parts of the code you do understand, and instead post a follow up question. LMGTFY / RTFM Asking a question on a SE, site is a great way to learn. However another is ...


11

Welcome to code review... Import statements from random_words import RandomWords from colorama import Fore, Back, Style Assuming that someone wants to run your program, how would he run it without having this random_words thing? You should include it with the rest of your code unless it's an official Python module. Back in the second import statement is ...


10

I'll get a few trivial comments out of the way before addressing some serious concerns about the flow of control in your program. User experience Overall, the application feels like it's nicely put together. I enjoyed playing it while writing this review. The past participle of the verb "to hang" is "hung", but when talking about executions, it should be ...


10

Nice improvement from the initial version. Good job! Here are a couple of brief notes. I'm very wary of having any method named run() outside of classes which implement the Runnable interface. This isn't something you'd know about as a beginner, but basically run() has a very specific connotation which regards using multiple threads. I might rename this ...


10

As I said in the comments, your code improved a lot, so that's really good. You should try out code analysis tools such as FindBugs, PMD, or Checkstyle. You don't have to listen to everything they say, but it's a good way to improve your code. They would for example warn you: to not use exit() (use an exception or setting a boolean to false instead) that ...


9

You have a bare except clause; i.e., try: some_code() except: clean_up() The problem with a bare except is that it will catch all exceptions, including ones you really don’t want to be ignoring (like KeyboardInterrupt and SystemExit). It would be much better if your except block only caught the specific exception you expect, and let all others ...


9

The solution would indeed be much simpler using regular expressions. The trick is to build the regular expression dynamically, using a negated character class like [^unwanted] to represent any character other than u, n, w, a, n, t, e, or d. I'd suggest writing this function to return a generator expression, such that it yields matching words from WORD_LIST ...


8

Here's my inline edits. The most conspicuous result is less manual work 20%-25% shorter (in lines, words, and characters). Less code means less bugs and less maintenance burden (if not obfuscating) Notes removed some not very valuable error handling don't pass filename as std::string for no reason (pass const char*const) added input checking (just alpha-...


8

Let's start with an alternative, more object oriented design. Then I'll make some comments about things you can improve in your code. You should try to clearly separate your game logic with what you need to do for handling input/output. Consider for instance the following class sketch to represent a game. public class Game { public Game(string word) ...


8

You are making a common beginner mistake of misusing functions as if they were goto labels. For example, from the last line of the program, you call guess(), which calls check(), which calls guess(), which calls check(), which calls guess(), …, which calls check(), which calls you_win(), which can call you_loose() (?!) At some point, you can hit ControlC ...


8

While your code might be working and written in a functional language, it also feels very procedural to me. Most idiomatic Haskell code I see has a very high signal to noise ratio. In your code I have to read every single line and figure out what it does in my head. You can achieve this by making a lot of tiny functions (after all, composition is key for a ...


8

For this, I am going to go through your program in the order it is written: Don't use if twoplayer == False:. You can simply say if not twoplayer: You don't even need that, though the first time because you do the same thing in the if and elseblocks`. You can use " ".join("_" * lengthword) instead of for i in range(1, lengthword): userguess.append("_ "). ...


8

That's so awesome you are learning Python! I love it and I am sure you will too. Your code looks pretty good! I played it and enjoyed doing so. It's harder than I expected though! So here are a few quick ideas for how you could improve your code. Fewer print statements with """ Instead of printing each line separately to create the hangman, you could use ...


8

I could come up with a laundry list of improvements. However, I would like to focus on just one issue, which makes your code an unforgivably bad example for your students: you are misusing functions as goto labels. Note that game() can call play_again(), which in turn may call game(). This mutual recursion is inappropriate. If you play many games, then ...


8

Clearing the screen os.system('cls') is a horrible way of clearing the screen. The cross-platform os.system('cls' if os.name == 'nt' else 'clear') alternative is just as bad. What this is doing is forking a child process, and in the child process (which is currently a copy of the current process's code and data memory): replace the current process image ...


7

I'd like to focus on the getPuz() function to make the work of codesparkle more manageable. :) Exceptions handling The first, high-level problem is the way you use try/catch blocks. Exceptions are not here to get into your way! They're great tools that let you write robust programs and focus on error conditions only where necessary. Writing "Problem ...


7

Thank you for sharing your code. Quite frankly, it's a bit of a mess, so let's try to clean it up. General Code Issues Here are a few examples of issues with your code that can easily be corrected. All these issues can be automatically detected by a good IDE such as the free, open-source and excellent IntelliJ IDEA Community Edition1 (Analyze->Inspect ...


7

You currently aren't following Java package naming standards. package com.Game; You need to keep a "tab" (bah dum tish) on your indenting. Right now it is somewhat hard to read your code because of that. You don't clear the text field once a letter is entered. This means the user had to clear out the field themselves and then enter a new letter. We can ...


7

Some comments: Make sure you have a consistent indentation style. It makes it difficult to follow the code flow, if there are multiple lines with different indentation. You should separate the view and the game logic. Having both the Swing design setup and the actual game logic mixed up—in a single method—makes the code very hard to navigate. Ideally, both ...


Only top voted, non community-wiki answers of a minimum length are eligible