+# place a tile at current spot
+def put_tile (leveldata, row, col, tilerow, tilecol):
+ leveldata[row][col][0] = tilerow
+ leveldata[row][col][1] = tilecol
+
+# picking a tile from the tileset
+def pick_tile (screen, tileset, selrow, selcol):
+
+ # total number of rows and columns
+ totalrows = tileset.get_height () / 48
+ totalcols = tileset.get_width () / 48
+
+ # implement scrolling within the tileset image in a 480x480 viewport
+
+ # set the current page
+ curpage_cols = selrow / 10
+ curpage_rows = selcol / 10
+
+ # cursor row and column
+ cursor_row = selrow % 10
+ cursor_col = selcol % 10
+
+ # the code for scrolling through the tileset is slightly complicated here are the steps
+ # logic goes like this
+ # e.g. horizontal movement
+ # left arrow key movement:
+ # 1. reduce the absolute column by 1
+ # 2. if absolute column < 0 then set absolute column to last column as total columns - 1
+ # 3. calculate the current page based on absolute column as absolute column / 10
+ # 10 being the number of tile columns per page
+ # 4. calculate the relative column on screen as (abolute column modulo 10) giving a
+ # division remainder between 0 and 9.
+
+ # same logic is used for all other movements
+
+ while 1:
+ screen.fill (pygame.Color (0, 0, 0))
+ screen.blit (tileset, (0, 0), (curpage_cols * 480, curpage_rows * 480, 480, 480))
+ draw_cursor (screen, cursor_row, cursor_col)
+ utility.put_text (screen, 490, 10,10, (255, 255, 0), "<Space> or <Enter>")
+ utility.put_text (screen, 490, 30,10, (255, 255, 0), "to select tile")
+ utility.put_text (screen, 490, 70,10, (255, 255, 0), "<Escape> to return")
+ utility.put_text (screen, 10, 490,10, (255, 255, 0), "Selected: %d row, %d col" % (selrow, selcol))
+ pygame.display.update ()
+ for event in pygame.event.get ():
+ if event.type == pygame.KEYDOWN:
+ if event.key == pygame.K_ESCAPE:
+ return None
+ elif event.key == pygame.K_SPACE or event.key == pygame.K_RETURN:
+ return selrow, selcol
+ elif event.key == pygame.K_UP:
+ # reduce the selected row by 1
+ selrow -= 1
+ if selrow < 0:
+ selrow = totalrows - 1
+
+ # calculate the current page
+ curpage_rows = selrow / 10
+
+ # calculate the current cursor row
+ cursor_row = selrow % 10
+
+ elif event.key == pygame.K_DOWN:
+ # increase the selected row by 1
+ selrow += 1
+ if selrow >= totalrows:
+ selrow = 0
+
+ # calculate the current row page
+ curpage_rows = selrow / 10
+
+ # calculate the cursor row
+ cursor_row = selrow % 10
+ elif event.key == pygame.K_LEFT:
+ # decrease the selected col by 1
+ selcol -= 1
+ if selcol < 0:
+ selcol = totalcols - 1
+
+ # calculate the current column page
+ curpage_cols = selcol / 10
+
+ # calculate the cursor column
+ cursor_col = selcol % 10
+ elif event.key == pygame.K_RIGHT:
+ # increase the selected column by 1
+ selcol += 1
+ if selcol >= totalcols:
+ selcol = 0
+
+ # calculate the current column page
+ curpage_cols = selcol / 10
+
+ # calculate the cursor column
+ cursor_col = selcol % 10
+