473,799 Members | 2,711 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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

7 New Member
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
16 2044
jlm699
314 Contributor
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
wokeup2sleep
7 New Member
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 Contributor
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
wokeup2sleep
7 New Member
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 Contributor
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
wokeup2sleep
7 New Member
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 Contributor
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
1899
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 ( +2) / 131 closed ( +0) / 281 total ( +2) New / Reopened Patches ______________________
13
11798
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 files A, and B each containing say 100,000 lines (each line=one string without any space) I want to do
10
3697
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. Andrew dalke@dalkescientific.com
34
4132
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? Any modern block cipher will do: AES, Blowfish, etc. I'm not looking for public key stuff; I just want to provide a pass-phrase. I found a few modules out there, but they seem to be all but abandoned. Most seem to have died several years ago. ...
10
1505
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 tutorials I can find, and have read through Andre Lessa's Developers Handbook.) I am trying to learn the Python way of thinking as well as the syntax. I popped this bit of code together for fun, based on a previous post
8
3042
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 what I really should do. I've had a look through Programming Python and the Python Cookbook, which have given me ideas, but nothing has gelled yet, so I thought I'd put the question to the community. But first, let me be a little more detailed...
3
1927
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 taking pseudocode and turning it into code. Since I am in a beginners class, we have only learned so much to date, so what I am presenting will be really rough, so please pardon my ignorance. Here are my instructions, with my code to follow: ...
5
6782
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 cause. If I could create a large file that could be encrypted, and maybe add files to it by appending them and putting in some kind of delimiter between files, maybe a homemade version of truecrypt could be constructed. Any idea what it...
10
2098
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: http://esnips.com/webfolder/b71bfe95-d363-4dd3-bfad-39999a9e36d0 What i have the biggest problems with now is between line 8 and 23. How i can move the character trough the game. Other parts of the game that have with the movement to do is between line 83-114 and...
0
9689
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9550
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10495
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10248
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9085
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6811
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5469
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4148
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2942
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.