Python Game Challenge #1 [Beginner]

Hello everyone! Today I bring you a very simple game/challenge perfect for those that are new to Python! It’s called Guess The Number. You can play two it ways:

  1. Multi player - Player One picks the number and Player Two tries to guess it.

  2. Single Player - The program generates a random number and you try to guess it.

The statements above pretty much explain what you’ll be doing.
Don’t think to big, 15 / 20 lines of code should do it and it should take about 5 mins, 10 tops.

I’ll post my own code below. I chose to do it as a Multi Player. Feel free to post your code in any other language on the comments!


import random
print "#------------------#"
print "| GUESS THE NUMBER |"
print "#------------------#"
print '\n'
number = raw_input('Pick your number > ')
for i in range(0,15):
    print '\n'
while True:
    guess = raw_input('Guess the number > ')
    if guess > number:
        print '\nHmmm, try a lower number...\n'

    elif guess < number:
        print '\nGo a little higher\n'

    else:
        print "Right on! Well done!"
        break
1 Like

Did I go overboard? Yes. Pastebin This is Ruby, btw.

def check_for_answer(ans)
    guess = ans+1
    while true
        print "[*] Enter a guess... "
        guess = gets.chomp.to_i
 
        if guess < ans
            puts "  [*] Higher..."
        elsif guess > ans
            puts "  [*] Lower..."
        else
            puts "  [*] Correct!"
            break
        end
    end
end
 
def singleplayer
    puts "[*] You have entered Single Player"
    puts "\n[*] Now please enter the guessing range (i.e., from x to y [inclusive])"
    print "separated by a comma. "
    x,y = gets.chomp.split(',').map(&:to_i)
   
    check_for_answer(rand(x..y))   
end
 
def multiplayer
    puts "[*] You have entered Multiplayer."
    puts "[*] One player should enter a number while the other looks away."
    puts "[*] Enter answer: "
   
    answer = gets.chomp.to_i
   
    system("clear")
   
    puts "[*] Now bring in the guesser..."
    puts "[*] Hey, guesser. The range is #{answer - rand(0..answer)} to #{answer + rand(1..answer)}"
 
    check_for_answer(answer)
end
 
def main
    puts "#----------------#"
    puts "# Number Guesser #"
    puts "#   by oaktree   #"
    puts "#----------------#"
    print "\n"*2
 
    puts "[*] Here are your options:"
    puts "1. Single Player"
    puts "2. Two Players"
 
    print "[*] Choice? [1/2] "
    input = gets.chomp.to_i
 
    if input == 1
        singleplayer
    else
        multiplayer
    end
end
 
main()
2 Likes

Nice! What a perfect example of good code and great effort!
I didn’t want to go to technical to be more beginner friendly, but really well done!

I went in with the goal of making a functional, DRY implementation.

1 Like

Props to you and @n3xUs for the great code! I’m actually attempting to learn low level coding languages like Assembly.

1 Like

Thought I’d bash it out in C. It’s not elegant, or short, but then, neither am I…ahahahahahhahaha! (Wow, I really had to re-edit all the indentation, since the backticked c code was all over the place)

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void game(int mode);

int main(void)
{
    // seed the random number generator
    srand(time(NULL));

    int mode = 0;
        while (1) {  // infinite loop
            printf("==========================\n");
            printf("==== Guess the Number! ===\n");
            printf("==========================\n\n\n");
            printf("Choose game type(1/2):\n");
            printf("1) Single-player\n");
            printf("2) Multi-player\n");
            printf("3) Quit (any key)\n\n");
            printf("> ");
            scanf("%d", &mode);

            if (mode == 1 || mode == 2) {
                game(mode);
            } else {
                exit(EXIT_SUCCESS);
            }
        }
        return 0;
}

void game(int mode) {
    int guess = 0;
    int num = (rand() % 100) + 1; // pseudo-random integer twixt 0 and 100

    if (mode == 2) {
            printf("\nPlayer 1, enter your number(1-100): ");
            scanf("%d", &num);
            printf("\nPlayer 2, guess the number!\n");
        }

        for (int i = 0; i < 5; i++) {  // 5 chances
            printf("\nGuess(1-100): ");
            scanf("%d", &guess);
            if (guess > num) {
                printf("Too high!\n");
            } else if (guess < num) {
                printf("Too low!\n");
            } else {
                printf("\n\n*** YOU GOT THAT NUMBER! ***\n\n");
                break;
            }
        }
    
        if (guess != num)
            printf("\n%s!\n", (mode==2)?"Player 2 fails!\n":"You Failed!\n");

}

2 Likes

I didn’t have an internet connection till today, but at least I had time to to work on polishing up the program and make it more complex… (thanks @oaktree…)


import random
import os

def multiplayer():
    print "\n[*] You have chosen Multiplayer."
    number = int(raw_input('[*] Player One, pick your number > '))
    for i in range(0,13):
        print '\n'
    while True:
        guess_1 = raw_input('[*] Player Two, guess the number > ')
        if int(guess_1) > number:
            print '\n[*] Hmmm, try a lower number...\n'

        elif int(guess_1) < number:
            print '\n[*] Go a little higher\n'

        else:
            print '\nRight on! Well done!\n'
            os.system('clear')
            break

def single_player():
    generated_number = random.randint(0,100)
    print '\n[*] You have chosen to play Single Player.'
    print '[*] A random number from 0 to 100 has been generated\n'
    while True:
        guess_2 = raw_input("Make your guess > ")
        if int(guess_2) > generated_number:
            print '\n[*] Lower\n'

        elif int(guess_2) < generated_number:
            print '\n[*] Higher\n'

        else:
            print "\n[*] Nice! You're correct.\n"
            os.system('clear')
            break

def main():
    print "#------------------#"
    print "| GUESS THE NUMBER |"
    print "|     by n3xUs_    |"
    print "#------------------#"
    print "\n[*] You are playing Guess The Number. Please choose an option:"
    while True:
        print '\n1. Single Player'
        print '2. Multiplayer\n'
        print '[*] To EXIT type "quit".\n'
        option = raw_input ('Option > ')
        if option == str(1):
            single_player()
        elif option == str(2):
            multiplayer()
        elif option == 'quit':
            print '\n[!] Thanks for playing!\n'
            break
        else:
            print '\n[!] Please chose 1 or 2\n'

main()
1 Like

With a OOP twist

import random

class Game:
  def __init__(self):
      print "SinglePlayer Mode!\n"
    
  def chose_number (self):
      self.number = int(random.randint (0,100))

  def play (self):
      while True:
          guess = int(raw_input ('Guess the number > '))
          if guess > self.number:
              print 'Lower\n'
          elif guess < self.number:
              print 'Higher\n'
          else:
              print "You win!\n"
              break

class MultiPlayer(Game):
    def __init__(self):
        print "Multiplayer Mode Activated\n"

    def chose_number(self):
        self.number = int(raw_input ('Player 1, pick a number (0, 100)> '))


print "1. Single Player\n2. Two Players\n";
sel = raw_input ('Your choice > ');

types = {'1': Game, '2': MultiPlayer}
g = types[sel]()

g.chose_number();
g.play();
    
2 Likes

This topic was automatically closed after 30 days. New replies are no longer allowed.