python help with taking in data, saving date, arrays, random.shuffle

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • wokeup2sleep
    New Member
    • Mar 2008
    • 7

    python help with taking in data, saving date, arrays, random.shuffle

    im a beginner at comp science, and my prof is using python, which is totally new tom me i had a few questions with the program im writing, im having a few problems.

    brief summary
    i have to do a project where there are nine boxes filled with number 1-8, and 1 space is empty, the game needs to be scrambled, also all the moves need to be saved. the game can be paused anytime during thegame. the object is to move the numbers into the black spot till they are all in order.

    the grid i have needs to contain variables so that can be moved by the players

    this what i have and i know it is far off

    def board():
    board = [1,2,3,4,5,6,7,8 ,9]

    for x in range(0, 9):
    print "|"

    if(board[x]==9):
    print "_"
    else:
    print board[x]



    if(x==8):
    print "|"
    board()




    when i run that it looks like this

    |
    1
    |
    2
    |
    3
    |
    4
    |
    5
    |
    6
    |
    7
    |
    8
    |
    _
    |


    and this is how i need it to look:

    |1|2|3|
    |4|5|6|
    |7|8|_|

    what am i doing wrong? also how do i use the random.shuffle( ) function so i can scramble the numbers?

    help would be greatly appriciated...

    also how would i save every move, also the random fuction isnt working so i can scramble the numbers.


    i am probably doing everything wrong to make a game board, cause i need everything to to be interchanglable when the players wants to move and adjecent number to the blank spot, any help anyone???

    thanks alot ahead of time

    also i can't seem to import array or random
    in addition my project is attached if anyone didnt understand what i needed to to do
  • wokeup2sleep
    New Member
    • Mar 2008
    • 7

    #2
    anyone willing to help?

    Comment

    • wokeup2sleep
      New Member
      • Mar 2008
      • 7

      #3
      anyone? please help, will be greatly appriciated

      Comment

      • jlm699
        Contributor
        • Jul 2007
        • 314

        #4
        Your problem is that every time you issue a print statement, Python automatically appends a newline character to the end.

        What you'll want to do is iterate through your loop and instead of printing outright, try storing the values to a string, which can be concatenated with the '+' operator.

        On each iteration you could try checking the string for a certain length, and if it is the length that you want for a particular line you could print it then, and clear the string to start over with a new line.

        example string concatenation and length check...

        [CODE=python]
        >>> st = ''
        >>> st += 'test'
        >>> st += '4ex'
        >>> st
        'test4ex'
        >>> len(st)
        7
        >>>
        [/CODE]

        Comment

        • jlm699
          Contributor
          • Jul 2007
          • 314

          #5
          Additionally, please try to use code tags when you post code (it saves room and makes your post friendlier to read...)

          random.shuffle( ) literally shuffles the order of number in a list.

          [CODE=python]
          >>> import random
          >>> colors = ['red', 'blue', 'green']
          >>> random.shuffle( colors)
          >>> colors
          ['green', 'red', 'blue']
          >>> random.shuffle( colors)
          >>> colors
          ['green', 'blue', 'red']
          >>>
          [/CODE]

          Comment

          • bvdet
            Recognized Expert Specialist
            • Oct 2006
            • 2851

            #6
            I think this might get you started:[code=Python]def boardStr(cols, rows, empty=1):
            numList = [str(i) for i in range(1, (cols*rows-empty)+1)]
            random.shuffle( numList)
            numList += ['_' for i in range(empty)]
            return ''.join(['%2s%s' % (s, ['|', '\n'][not (i+1)%cols or 0]) for i, s in enumerate(numLi st)])

            # Without the list comprehension
            def boardStr(cols, rows, empty=1):
            numList = [str(i) for i in range(1, (cols*rows-empty)+1)]
            random.shuffle( numList)
            numList += ['_' for i in range(empty)]
            outStr = ''
            for i, s in enumerate(numLi st):
            outStr += '%2s' % (s)
            if not (i+1)%cols:
            outStr += '\n'
            else:
            outStr += '|'
            return outStr

            print boardStr(3,3,1)
            print boardStr(4,4,1)
            print boardStr(4,4,2)[/code]The printed output looks like this:

            >>> 8| 2| 6
            1| 4| 7
            3| 5| _

            11| 9|14| 3
            8|10|15| 6
            4| 7| 2| 5
            12| 1|13| _

            7|13| 5|11
            1| 6|14| 2
            9|10| 4| 3
            8|12| _| _

            >>>

            Comment

            • jlm699
              Contributor
              • Jul 2007
              • 314

              #7
              Originally posted by bvdet
              I think this might get you started:[code=Python]def boardStr(cols, rows, empty=1):
              numList = [str(i) for i in range(1, (cols*rows-empty)+1)]
              random.shuffle( numList)
              numList += ['_' for i in range(empty)]
              return ''.join(['%2s%s' % (s, ['|', '\n'][not (i+1)%cols or 0]) for i, s in enumerate(numLi st)])[/CODE]

              Oh bvdet... you and your list comprehensions never cease to amaze me

              Comment

              • bvdet
                Recognized Expert Specialist
                • Oct 2006
                • 2851

                #8
                Originally posted by jlm699
                Oh bvdet... you and your list comprehensions never cease to amaze me
                I realize that sometimes a list comprehension may not the best way and can be difficult to read. That's why I included the second version of the function.

                Comment

                • wokeup2sleep
                  New Member
                  • Mar 2008
                  • 7

                  #9
                  The game is called the sliders game. The game starts a in a solved state, then the player types (s)scramble, to scramble the board. Then the player has to type a number that is adjacent to the empty box, to switch spot, they have to do this strategically to get all the number back in order 1-8.

                  Problems i have;

                  how to get a board so the number are interchangable when the player chooses. ie, if the board looks like
                  |1|2|3|
                  |4|5|6|
                  |7|8|_|
                  if the player types scramble i need board to look as if you handed it to some one and they made a thousand random moves. how do i do that;
                  so it look something like
                  |4|1|2|
                  |3|5|7|
                  |6|8|_|
                  then the player should be able to type in a number, the the empty slot if filled with that number, player continues to do this till the board is in order again. so say if the player typed 7 it should looked;
                  |4|1|2|
                  |3|5|_|
                  |6|8|7|
                  and if anytime the player types (p)pause the state of the board that it is in needs to be saved so it can be resumed

                  how to save every move in the system when a player makes it, so i can see a replay of the game if the game is won, also if the game is paused the game can be resumed.

                  so how would i make the numbers move, when a player types a number, and how do i save every move?

                  thanks alot guys..

                  Comment

                  • jlm699
                    Contributor
                    • Jul 2007
                    • 314

                    #10
                    [CODE=python]
                    >>> n = range(1, 10)
                    >>> random.shuffle( n)
                    >>> print ''.join(['%s%s' % (['|', '|' + s][not (i+1)%3 or 0], [s, '|\n'][not (i+1)%3 or 0]) for i, s in enumerate(n)])
                    |2|8|9|
                    |3|7|4|
                    |5|6|1|
                    [/CODE]

                    bvdet's List comprehension slightly modified for the output format specified in original post ;)

                    Comment

                    • jlm699
                      Contributor
                      • Jul 2007
                      • 314

                      #11
                      Originally posted by wokeup2sleep
                      how to save every move in the system when a player makes it, so i can see a replay of the game if the game is won, also if the game is paused the game can be resumed.
                      This can be achieved with a list of lists... you simply have to save the order, and let your "print board" function worry about displaying it correctly.

                      (ie, have a game list, which is a list containing 'board lists')

                      Game list would be
                      [CODE=python]
                      [ [1,2,3,...], # orig. board order ( 1-8 + _ ),
                      [2,1,3,...], # scrambled board,
                      [2,_,1....], # board after move 1,
                      [_,2,1....], # board after move 2,
                      [3,2,1....], # ... etc.
                      ]
                      [/CODE]

                      As far as swapping the numbers, you literally can use the list's index() function to find and switch the index of the '_' and the number that they typed, then just redisplay the board.

                      Comment

                      • wokeup2sleep
                        New Member
                        • Mar 2008
                        • 7

                        #12
                        sorry, im a bit confused, im totallty a beginner, and im ain a intro class

                        how i would i use the find(), to switch the position of the "_", with the selected number

                        also how would i use the list fuctions to save the moves, so when it replays it replays, so it shows that board every time, with the move made, or to resume, how would i create the function, so it copys the state ot the board.

                        also how will the game figure out that the player is won once it is back in it;s normal position

                        in addition, the revised board you sent me shows the 9 instead of having it shown as "_", what would it look like w/o the comprehension


                        if you would like i can show you the rules of the project i have the pdf file.

                        Comment

                        • jlm699
                          Contributor
                          • Jul 2007
                          • 314

                          #13
                          No I understand the rules... it is a very simple game.

                          A good way to check if they have won, would be to check the current board list with a sorted ( sort() ) version of itself. Sort will place the '_' at the end since it counts digits as being lower than characters.

                          I didn't mean find() ... rather index(). Basically, here's a small example:
                          [CODE=python]
                          >>> b = ['a', 'b', 'c']
                          >>> idx = b.index('b')
                          >>> b[b.index('a')] = 'b'
                          >>> b[idx] = 'a'
                          >>> b
                          ['b', 'a', 'c']
                          >>> b.sort()
                          >>> b
                          ['a', 'b', 'c']
                          >>>
                          [/CODE]
                          Try to do this step by step... just worry about getting your game board to display and accept user commands.

                          Comment

                          • wokeup2sleep
                            New Member
                            • Mar 2008
                            • 7

                            #14
                            so how would i check the current board state...

                            i dont understand how i would take the useres input to switch the selected nnumber with the empty spot

                            so i have the board being generated randomly but how do i get the board so , when a player chooses a number it will switch with the empty slot

                            Comment

                            • jlm699
                              Contributor
                              • Jul 2007
                              • 314

                              #15
                              Originally posted by wokeup2sleep
                              so how would i check the current board state...
                              You would compare if board == sorted board.

                              Originally posted by wokeup2sleep
                              i dont understand how i would take the useres input to switch the selected nnumber with the empty spot
                              By assigning the raw_input() return to a variable, you know the number that they want to move... then you use the index() function to find the index of that number in the list... which you then swap values with the index of the '_' . An example of swapping two values in a list is in my last post.

                              Originally posted by wokeup2sleep
                              so i have the board being generated randomly but how do i get the board so , when a player chooses a number it will switch with the empty slot
                              You're going to want a loop that will kick out when the user inputs 'q'... otherwise perform the selected operation and then update the board on-screen.

                              I hope you realize that we cannot simply give you the answer, as you need to learn for yourself how to work with Python. In the short time since my last post I have made a complete version of this game and even created an executable from it. This is not very complex, it's actually a great way to demonstrate some basic python programming elements to a student.

                              Comment

                              Working...