Page 3 of 15 FirstFirst 1234513 ... LastLast
Results 21 to 30 of 144

Thread: [Beginner] Programming Challenge: 5

  1. #21
    Join Date
    Nov 2006
    Location
    Spain
    Beans
    175
    Distro
    Ubuntu 9.04 Jaunty Jackalope

    Re: [Beginner] Programming Challenge: 5

    Here is my code, with score saving to a file
    PHP Code:
    # -*- coding: utf-8 -*-
    def juego():
        
    import random
        number
    =random.randint(1,100)
        
    bien=0
        fail
    =0
        
    print number
        
        

        
        
    while bien==0:
            try:
             
    adiv=input("Number: ")
             if 
    adiv number:
                print 
    "Higher"
                
    fail=fail+1
             elif adiv 
    number:
                print 
    "Lower"
                
    fail=fail+1
             elif adiv 
    == number:
                if 
    fail == 0:
                    print 
    "One shot one Kill"
                    
    bien=1
                    nom
    =raw_input("Your name: ")
                    
    archivo=open("test.txt","a")
                    
    dirty=[]
                    
    dirty2=[]
                    
    fail=str(fail)
                    
    dirty.append(nom)
                    
    dirty2.append(fail)
                    
    archivo.write("Name   Score"+"\n")
                    
    archivo.write(dirty[0]+" "+dirty2[0])
                    
    archivo.write("\n")
                    
    archivo.close() 
                
    elif fail 6:
                   print 
    "Correct!"
                   
    print "You've tried "fail"times"
                   
    bien=1
                   nom
    =raw_input("Your name: ")
                   
    archivo=open("test.txt","w")
                 
                   
    dirty=[]
                   
    dirty2=[]
                   
    fail=str(fail)
                   
    dirty.append(nom)
                   
    dirty2.append(fail)
                   
    archivo.write("Name   Score"+"\n")
                   
    archivo.write(dirty[0]+" "+dirty2[0])
                   
    archivo.write("\n")
                   
    archivo.close() 
                
    elif fail >= 10:
                    print 
    "Correct!"
                    
    print "You've tried "fail"times"
                    
    print "It was difficult, eh?"
                    
    bien=1
                    nom
    =raw_input("Your name: ")
                    
    archivo=open("test.txt","w")
                    
    dirty=[]
                    
    dirty2=[]
                    
    fail=str(fail)
                    
    dirty.append(nom)
                    
    dirty2.append(fail)
                    
    archivo.write("Name   Score"+"\n")
                    
    archivo.write(dirty[0]+" "+dirty2[0])
                    
    archivo.write("\n")
                    
    archivo.close() 
            
    except:
                print

    def menu():
       
    elegir=0
       
    while elegir != 2
        print 
    "1. Play"
        
    print "2. Exit"
        
    try:
         
    elegir=input("Choose: ")
        
    except:
            print
        if 
    elegir ==1:
            
            
    juego()

    menu() 

  2. #22
    Join Date
    Apr 2006
    Location
    Sheffield - England
    Beans
    Hidden!

    Re: [Beginner] Programming Challenge: 5

    Quote Originally Posted by Reiger View Post
    Have you tested that code? In proper Haskell main has to be of type main :: IO () !

    Also your code never returns the number of guesses it took to get the random number correct. (It just returns the random number you 'feed' to your game.)
    ...
    Thanks - GHC didn't complain so I thought it was ok, I'll remember to make sure main has type IO () in future. The requirement to return the number of guesses was added after I wrote it so that's why it doesn't do that.

  3. #23
    Join Date
    May 2006
    Location
    Bologna, Italy
    Beans
    32

    Re: [Beginner] Programming Challenge: 5

    Lisp newbie here.
    Not commented as it should be self-esplicative.
    Structured because it's lisp
    Code:
    (defun ask-number (message)
      (format *query-io* "~a: " message)
      (force-output *query-io*)
      (parse-integer (read-line *query-io*)))
    
    (do ((secret (+ 1 (random 100)))
         (tries 1 (incf tries))
         (guess (ask-number "Guess a number between 1 and 100")
                (if (< guess secret)
                  (ask-number "Too low, try again")
                  (ask-number "Too high, try again"))))
      ((= guess secret) (format *query-io* "You got it in ~d tries!" tries)))
    And the salad is frightful!

  4. #24
    Join Date
    Jul 2008
    Beans
    1,706

    Re: [Beginner] Programming Challenge: 5

    Quote Originally Posted by LaRoza View Post
    I forgot a part of the criteria, sorry. The program should also give the number of guesses it took at the end.
    does it have to be fool proof too...like if they enter "a" instead of a number do we have to catch it?

  5. #25
    Join Date
    Oct 2006
    Location
    Ireland
    Beans
    416
    Distro
    Kubuntu 8.04 Hardy Heron

    Re: [Beginner] Programming Challenge: 5

    Quote Originally Posted by Sinkingships7 View Post
    Then hacked it in C, for the sake of practice with something that's not quite as built-in. LaRoza, feel free to remove my C entry if you see fit, as it's not my 'beginner' entry. I'm new to Python, but certainly not to C.
    PHP Code:
    ...
        
    int random_number rand() % int random_number rand() % (100 1) + 1; + 1;
    ... 
    Any particular reason you use (100 - 1 + 1), since that just comes out as 100 anyway?

    Also I did this problem as a KDE app before but can't find the code, probably got deleted (Think I did it before installing Hardy), wasn't a great program but it was probably the first KDE app I wrote by myself (as in, not basing it off a tutorial)
    Last edited by happysmileman; August 29th, 2008 at 05:14 PM.

  6. #26
    Join Date
    Mar 2008
    Beans
    1,076
    Distro
    Ubuntu

    Re: [Beginner] Programming Challenge: 5

    here is my first game in c then. actually i only used c in a month so its kinda my first large application. i am very there will be bugs in it also i have had a long break from anything computer related for some time so i took the challenge as an opportunity to try write a little program.

    PHP Code:
    /*
     *      game.c
     *      
     *      Copyright 2008 cmay <ihaveno@emails>
     * 
     *      This program is free software; you can redistribute it and/or modify
     *      it under the terms of the GNU General Public License as published by
     *      the Free Software Foundation; either version 2 of the License, or
     *      (at your option) any later version.
     *      
     *      This program is distributed in the hope that it will be useful,
     *      but WITHOUT ANY WARRANTY; without even the implied warranty of
     *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     *      GNU General Public License for more details.
     *      
     *      You should have received a copy of the GNU General Public License
     *      along with this program; if not, write to the Free Software
     *      Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
     *      MA 02110-1301, USA.
     */

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

    char *progname;
    void play();
    void license();
    void help();
    void print_menu();

    /* main menu function*/
    void select_menu()
    {
        
    int in;
         
    print_menu();
        while((
    in=getchar()))
        {      
                switch(
    in)
               {
                case 
    'p':play();break;
                case 
    'h':help();break;
                case 
    'l':license();break;
                case 
    'q':abort();break;
               } 
        }
        
    }
        
    /* the game play*/
        
    void play()
        { 
             
    int count_guess=0;
             
    srand((unsigned)time(NULL));
             
    int correct=rand()%100;
    /* okay honest i cant understand a word of the manual rand should be max 100 ? */
             
    int input;
            
    puts("ok then !!! guess this :)");
            while(
    scanf("%d",&input)==1)
            {
                
    count_guess++;
                           
            if(
    input correct)
               
    printf("higher\n[guesses used[%d]\n",count_guess);
            if(
    input correct)
               
    printf("lower\n[guesses used[%d]",count_guess);
            if(
    input == correct)
               
    printf("you win \n[%d]guesses usesd\n",count_guess);
               
    printf("press [q] to quit any key to continue\n");
              }

        }
          
    /* my help menu*/
            
    void help()
            {
                
    printf("%s helpmenu\n",progname);
                
    printf("minimal version of the high low game\n");
                
    printf("[q] quit program\n");
                
    printf("[h]this menu\n");
                
    printf("[p] play game\n");
                
            }
            
    /* my license*/
            
    void license()
            {
                
    char notice[]="a free GPLed version of high-low game\n"
                "author:cmay\n2008\nhave fun\n"
    ;
                
    printf("%s",notice);
            }
            
    /* my menu */
            
    void print_menu()
            {
                
    char text[]="[p]play gamel\n"
                            "[l]license\n"
                           "[q] quit\n"
    ;
                
    printf("%s",text);
            }
                       
    int main(int argcchar** argv)
    {
        
            while(
    1)
            {     
            
    select_menu();
            }
           
        exit(
    0);

    please buy this online only compilation to support victims of japan. http://www.punk4japan.com/

  7. #27
    Join Date
    Apr 2006
    Location
    Hamilton, Scotland
    Beans
    186
    Distro
    Kubuntu Development Release

    Re: [Beginner] Programming Challenge: 5

    My quick attempt ...
    Code:
    #!/usr/bin/env python
    from sys import argv
    from random import randrange
    
    class RandomGame:
            
        def newGame(self):
            self.number = randrange(1, 100, 1)
            self.guessCount = 0
            
            print "Guess a number between 1 and 100 ..."
            
            success = False
            while success == False:
                playerInput = raw_input("Please enter your guess [1-100]: ")
                playerInput = playerInput.strip()
                if not playerInput.isdigit():
                    print "You did not enter a valid number, please try again"
                else:
                    success = self.guess(int(playerInput))
            
        def guess(self, number):
            self.guessCount  += 1
            if number == self.number:
                print "CONGRATULATIONS, you got the number in %i guesses! " % self.guessCount
                return True
            else:
                if number >self.number:
                    print "Sorry, thats not the number, try guessing lower"
                    return False
                else:
                    print "Sorry,thats not the number, try guessing higher"
                    return False
        
    game = RandomGame()
    game.newGame()

  8. #28
    Join Date
    Nov 2007
    Beans
    706
    Distro
    Ubuntu 9.04 Jaunty Jackalope

    Re: [Beginner] Programming Challenge: 5

    Quote Originally Posted by happysmileman View Post
    Any particular reason you use (100 - 1 + 1), since that just comes out as 100 anyway?
    Only to stick to the formula. It's usually
    Code:
    rand() % (HIGH - LOW + 1) + LOW
    If you're looking for a number between 1 and another number, inclusive, then yes, it could just be
    Code:
    rand() % HIGH + LOW   // just HIGH + 1
    But that can only be the case if it's a number from 1 to HIGH. Of course, in all cases, you could just figure out the number in the parenthesis before hand and just plug it in manually, though I don't think that's generally practiced...
    Programming is an art. Learn it. Live it. Love it.

  9. #29
    Join Date
    Jul 2008
    Beans
    1,706

    Re: [Beginner] Programming Challenge: 5

    Quote Originally Posted by cmay View Post
    h
    PHP Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>


             
    srand((unsigned)time(NULL)); 
    whats the time thing for...all online help for that code snippit is very bad

  10. #30
    Join Date
    Apr 2007
    Location
    (X,Y,Z) = (0,0,0)
    Beans
    3,715

    Re: [Beginner] Programming Challenge: 5

    Ok, here's a MIT/GNU Scheme implementation. It's quite extensible, I think, thanks to the "signals" that determine the output. So, we achieve a complete separation between interface and output.

    EDIT: Reviewed code. It was utterly broken. Now works.

    Code:
    ;; UF PT Beginners Challenge 5: Guess a number.
    ;; Written in MIT/GNU Scheme. This may not work in other Scheme implementations.
    ;;
    ;; Copyright (c) 2008 Eugenio M. Vigo (aka "nvteighen")
    ;;
    ;; This program is free software: you can redistribute it and/or modify it 
    ;; under the terms of the GNU General Public License as published by the Free 
    ;; Software Foundation, either version 3 of the License, or (at your option) 
    ;; any later version.
    ;;
    ;; This program is distributed in the hope that it will be useful, but WITHOUT 
    ;; ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
    ;; FOR A PARTICULAR PURPOSE. See the GNU General Public License for more 
    ;; details.
    ;;
    ;; You should have received a copy of the GNU General Public License along with 
    ;; this program. If not, see <http://www.gnu.org/licenses/>.
    
    (load-option 'format)
     
    (define make-signal cons)
    (define sig-name car)
    (define sig-cont cdr)
    
    (define (output signal)
      (display
       (cond ((eq? (sig-name signal) 'win) 
              (format #f "Win in ~S tries!" (sig-cont signal)))
             ((eq? (sig-name signal) 'low)
              "Too low!")
             ((eq? (sig-name signal) 'high)
              "Too high!")
             ((eq? (sig-name signal) 'ask)
              "Type a number between 1-100:")
             ((eq? (sig-name signal) 'nan)
              (format #f "~S not a number" (sig-cont signal)))
             (else
              "Some weird thing is happening...?"))))
    
    (define (game)
      (let loop ((i 1)
                 (secret (+ 1 (random 100))))
        (begin
          (output (make-signal 'ask '()))
          (let ((guess (read)))
            (cond ((not (number? guess))
                   (begin 
                     (output (make-signal 'nan guess))
                     (newline)
                     (loop i secret)))
                  ((= guess secret) 
                   (output (make-signal 'win i)))
                  (else
                   (begin
                     (cond ((< guess secret) 
                            (output (make-signal 'low '())))
                           ((> guess secret)
                            (output (make-signal 'high '()))))
                     (newline)
                     (loop (+ 1 i) secret))))))))
    
    (game)
    Last edited by nvteighen; March 21st, 2009 at 02:45 PM. Reason: formatting

Page 3 of 15 FirstFirst 1234513 ... LastLast

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •