473,378 Members | 1,495 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,378 software developers and data experts.

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
Mar 4 '08 #1
16 2015
anyone willing to help?
Mar 4 '08 #2
anyone? please help, will be greatly appriciated
Mar 5 '08 #3
jlm699
314 100+
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...

Expand|Select|Wrap|Line Numbers
  1. >>> st = ''
  2. >>> st += 'test'
  3. >>> st += '4ex'
  4. >>> st
  5. 'test4ex'
  6. >>> len(st)
  7. 7
  8. >>> 
  9.  
Mar 5 '08 #4
jlm699
314 100+
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.

Expand|Select|Wrap|Line Numbers
  1. >>> import random
  2. >>> colors = ['red', 'blue', 'green']
  3. >>> random.shuffle(colors)
  4. >>> colors
  5. ['green', 'red', 'blue']
  6. >>> random.shuffle(colors)
  7. >>> colors
  8. ['green', 'blue', 'red']
  9. >>> 
  10.  
Mar 5 '08 #5
bvdet
2,851 Expert Mod 2GB
I think this might get you started:
Expand|Select|Wrap|Line Numbers
  1. def boardStr(cols, rows, empty=1):
  2.     numList = [str(i) for i in range(1, (cols*rows-empty)+1)]
  3.     random.shuffle(numList)
  4.     numList += ['_' for i in range(empty)]
  5.     return ''.join(['%2s%s' % (s, ['|', '\n'][not (i+1)%cols or 0]) for i, s in enumerate(numList)])
  6.  
  7. # Without the list comprehension
  8. def boardStr(cols, rows, empty=1):
  9.     numList = [str(i) for i in range(1, (cols*rows-empty)+1)]
  10.     random.shuffle(numList)
  11.     numList += ['_' for i in range(empty)]
  12.     outStr = ''
  13.     for i, s in enumerate(numList):
  14.         outStr += '%2s' % (s)
  15.         if not (i+1)%cols:
  16.             outStr += '\n'
  17.         else:
  18.             outStr += '|'
  19.     return outStr
  20.  
  21. print boardStr(3,3,1)
  22. print boardStr(4,4,1)
  23. print boardStr(4,4,2)
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| _| _

>>>
Mar 5 '08 #6
jlm699
314 100+
I think this might get you started:
Expand|Select|Wrap|Line Numbers
  1. def boardStr(cols, rows, empty=1):
  2.     numList = [str(i) for i in range(1, (cols*rows-empty)+1)]
  3.     random.shuffle(numList)
  4.     numList += ['_' for i in range(empty)]
  5.     return ''.join(['%2s%s' % (s, ['|', '\n'][not (i+1)%cols or 0]) for i, s in enumerate(numList)])

Oh bvdet... you and your list comprehensions never cease to amaze me
Mar 5 '08 #7
bvdet
2,851 Expert Mod 2GB
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.
Mar 5 '08 #8
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..
Mar 5 '08 #9
jlm699
314 100+
Expand|Select|Wrap|Line Numbers
  1. >>> n = range(1, 10)
  2. >>> random.shuffle(n)
  3. >>> 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)])
  4. |2|8|9|
  5. |3|7|4|
  6. |5|6|1|
  7.  
bvdet's List comprehension slightly modified for the output format specified in original post ;)
Mar 5 '08 #10
jlm699
314 100+
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
Expand|Select|Wrap|Line Numbers
  1. [ [1,2,3,...], # orig. board order ( 1-8 + _ ),
  2.   [2,1,3,...], # scrambled board,
  3.   [2,_,1....], # board after move 1,
  4.   [_,2,1....], # board after move 2,
  5.   [3,2,1....], # ... etc. 
  6. ]
  7.  
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.
Mar 5 '08 #11
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.
Mar 5 '08 #12
jlm699
314 100+
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:
Expand|Select|Wrap|Line Numbers
  1. >>> b = ['a', 'b', 'c']
  2. >>> idx = b.index('b')
  3. >>> b[b.index('a')] = 'b'
  4. >>> b[idx] = 'a'
  5. >>> b
  6. ['b', 'a', 'c']
  7. >>> b.sort()
  8. >>> b
  9. ['a', 'b', 'c']
  10. >>> 
  11.  
Try to do this step by step... just worry about getting your game board to display and accept user commands.
Mar 5 '08 #13
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
Mar 5 '08 #14
jlm699
314 100+
so how would i check the current board state...
You would compare if board == sorted board.

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.

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.
Mar 5 '08 #15
i dont know where to incorporate

Expand|Select|Wrap|Line Numbers
  1. idx = b.index(input("enter an adjacent number:"))
  2. numList[numList.index(empty)] = 'b'
  3. numList[idx] = 'a'
  4.  
in this code
Expand|Select|Wrap|Line Numbers
  1. def boardStr(cols, rows, empty=1):
  2.     numList = [str(i) for i in range(1, (cols*rows-empty)+1)]
  3.     random.shuffle(numList)
  4.     numList += ['_' for i in range(empty)]
  5.     outStr = ''
  6.  
  7.     for i, s in enumerate(numList):
  8.         outStr += '%2s' % (s)
  9.         if not (i+1)%cols:
  10.             outStr += '\n'
  11.         else:
  12.             outStr += '|'
  13.     return outStr
  14.  
  15. print boardStr(3,3,1)
  16.  
so that the number entered always replaces the empty value and where, the number that entered was turn in to the empty value.

also i dont no what to make the 'a' and 'b' into, i went through many trials and tribulations for the last few hours, and i still havent found anything that will replace the empty value with the number chosen, and the number chosen with the empty value.

also the grid shows up like this:
2|3|5
4|1|6
7|8|_

when i need it to look like

|2|3|5|
|4|1|6|
|7|8|_|
what did i mess up?

also , how would i do it so we play on the same board, instead of a new board printing everytime a player enters a number.
Mar 6 '08 #16
jlm699
314 100+
i dont know where to incorporate
...
in this code
...
so that the number entered always replaces the empty value and where, the number that entered was turn in to the empty value.
You don't. You shouldn't even be using that exact function. That was an example of how to generate and print a board "string". Your main function should be keeping track of the board string.

The way I did it:

Expand|Select|Wrap|Line Numbers
  1. ''' The sliders game
  2.     3/5/2008 '''
  3. import os, random, time
  4.  
  5. def dispBoard(brd):
  6.     # Prints the board in a 3x3 matrix
  7.  
  8. def replay(gm_list):
  9.     #Replays every move the player made using successive dispBoard calls
  10.  
  11. def slide(inp, brd_list, gm_list):
  12.     # Checks to see if player made a valid move
  13.     #  If the move was valid, swap the number they chose
  14.     #   with the blank tile and save the new board layout
  15.     #   otherwise do nothing
  16.  
  17. # This is the MAIN function... like main() in C++
  18. if __name__ == '__main__':
  19.     # here we'll initialize the 'game board'
  20.     brd_list = [str(i) for i in range(1,9)]
  21.     brd_list.append('_')
  22.     game_list = []
  23.     # We don't want shallow copies
  24.     game_list.append([item for item in brd_list])
  25.  
  26.     inp = 'i' # initialize the user-input variable 
  27.     while inp != 'q':
  28.         os.system("cls")
  29.         dispBoard(brd_list)
  30.         # copy board to temp list, sort and compare
  31.         # if temp_list == brd_list and not beginning of game, display 'You won!'
  32.             print 'You won!!!'
  33.             if raw_input('Replay? (y/n): ') == 'y':
  34.                 replay(game_list)
  35.             break
  36.         else:
  37.             print '\n', ['(1-8) moves number to blank spot, (P)ause,',
  38.                 '(S)huffle,'][inp == 'i'], '(Q)uit'
  39.  
  40.         # save the user's input w/ raw_input
  41.         # If shuffle and it is the beginning of game:
  42.             random.shuffle(brd_list)
  43.             # save new board layout to game_list
  44.         # elif a number between 1 and 8
  45.             slide(inp, brd_list, game_list)
  46.         # else:
  47.             # handle other inputs
  48.  
There's a basic skeleton for you, but it's up to you to figure out how to use it. You need to first worry about making your own function to print the game board. We've given you some major hints so you should be able to do it no problem.

Then start building the swap function, which was already given to you. All you have to do is build onto it by validating the user's moves... (hint: draw a 3x3 matrix and write the indices as they would appear in the list, then think about which moves are valid.)

also the grid shows up like this:
2|3|5
4|1|6
7|8|_

when i need it to look like

|2|3|5|
|4|1|6|
|7|8|_|
what did i mess up?

also , how would i do it so we play on the same board, instead of a new board printing everytime a player enters a number.
You messed up by using exactly what we gave you. You need to make it your own and build off of that. It was really only meant as a clue for you. You can't really do it without re-printing the board every time. It simply doesn't work like that. I gave you a major clue as to how to do it so that it "appears" to be the same board every time. I hope this helps.
Mar 6 '08 #17

Sign in to post your reply or Sign up for a free account.

Similar topics

0
by: Kurt B. Kaiser | last post by:
Patch / Bug Summary ___________________ Patches : 241 open ( -6) / 2622 closed (+26) / 2863 total (+20) Bugs : 764 open ( +6) / 4453 closed (+38) / 5217 total (+44) RFE : 150 open...
13
by: sf | last post by:
Just started thinking about learning python. Is there any place where I can get some free examples, especially for following kind of problem ( it must be trivial for those using python) I have...
10
by: Andrew Dalke | last post by:
Is there an author index for the new version of the Python cookbook? As a contributor I got my comp version delivered today and my ego wanted some gratification. I couldn't find my entries. ...
34
by: Blake T. Garretson | last post by:
I want to save some sensitive data (passwords, PIN numbers, etc.) to disk in a secure manner in one of my programs. What is the easiest/best way to accomplish strong file encryption in Python? ...
10
by: Grooooops | last post by:
Hi All, I've been lurking the list for a month and this is my first post. I am hoping this post is appropriate here, otherwise, my apologies. I'm somewhat new to Python, (I'm reading all the...
8
by: Paul Cochrane | last post by:
Hi all, I've got an application that I'm writing that autogenerates python code which I then execute with exec(). I know that this is not the best way to run things, and I'm not 100% sure as to...
3
by: bb91915 | last post by:
I am taking a beginners class in C and am attempting to write code for extra problems my instructor gave us. These are not for grade and are only used solely for practice. I have a hard time...
5
by: Michael Sperlle | last post by:
Is it possible? Bestcrypt can supposedly be set up on linux, but it seems to need changes to the kernel before it can be installed, and I have no intention of going through whatever hell that would...
10
by: connyledin | last post by:
Im trying to create a version of the game Wumpus. Mine is called Belzebub. But im STUCK! And its due tuesday 2 maj. Im panicing! Can some one help me?? here is the file:...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.