Hi I have a postscript file that layouts an image from left to right.
%%% Temporary
/Fix_long 4.2 cm def
/Fix_short 3.2 cm def
%%% Set Image Scale
/SetFixScale { 2 copy gt { Fix_long Fix_short }{ Fix_short Fix_long }ifelse scale } bind def
%%% Set put coordinate
/SetXAdjust { 2 copy gt
{ X_Step Fix_long sub 2 div floor }
{ Fix_long Fix_short sub 2 div} ifelse /XAdjust exch def
} bind def
/YAdjust 1.0 cm def
%%% Temporary
/Row 4 def
/Column 5 def
/X_Step urx llx sub Row div floor def
/Y_Step ury lly sub Column div floor def
/Row_pos 0 def
/Column_pos 1 def
/SetPutPosition {
llx X_Step Row_pos mul add
ury Y_Step Column_pos mul sub translate
DrawFrame
DrawFileName
XAdjust YAdjust translate
Row 1 sub Row_pos eq { /Row_pos 0 def /Column_pos Column_pos 1 add def }{ /Row_pos Row_pos 1 add def } ifelse
Column_pos Column gt { /Column_pos 1 def } if
} bind def
I tried changing the postscript to layout the images from top to bottom. I can layout the image from top to bottom but I can only put it on the first column.
/SetPutPosition {
llx X_Step Row_pos mul add
ury Y_Step Column_pos mul sub translate
DrawFrame
DrawFileName
XAdjust YAdjust translate
Row 1 sub Row_pos eq { /Row_pos 0 def /Column_pos Column_pos 1 add def }{ /Column_pos Column_pos 1 add def } ifelse
Column_pos Column gt { /Row_pos 1 def } if
} bind def
Not all the program is given, for example llx, lly, urx and ury are not defined. SO its impossible to reproduce what you are doing.....
The definition of rows and columns seems odd to me too, since rows increment in the x direction and columns decrement in the y direction.
I'd assume that the program operates in a loop (also not shown). On each iteration of the loop it sets the position on the page to:
x = llx + (X_Step * Row_pos)
y = ury - (Y_Step * Column_pos)
Then program then subtracts 1 from Row and compares with Row_pos. If they are the same then we reset the row, otherwise we add 1 to Row_pos. In effect we increment Row_pos until we get to Row - 1.
Now, if we reset the row, then we set Row_pos back to 0, and add 1 to column_pos.
Finally, we compare Column_pos and Column, if Column_pos is greater than Column, then we reset Column_pos to 1. Since we would have also reset Row_pos in the preceding control block, this is effectively a complete page reset, and starts again from the initial values.
Your code starts by checking Row_pos against Row again (when you should be checking Column_pos against Column). If Row_pos hasn't reached Row then you add 1 to Column_pos. Then you check Column_pos against Column and if its greater you reset Row_pos.
Notice that the only way you can alter Row_pos is if Row_pos is equal to Row - 1
If it is, then you reset Row_pos to 0. After that its impossible to increment Row_pos unless Row is 1.
Basically your logic is broken.
You want to compare Column_pos against Column - 1. When they are equal you want to set Column_pos to 1 and increment Row_pos, otherwise you want to increment Column_pos. Finally, if Row_pos is greater than Row, you want to reset Row_pos top 0.
So, bearing in mind thaqt I can't test this, because not all the code is present, something like :
/SetPutPosition {
llx X_Step Row_pos mul add
ury Y_Step Column_pos mul sub translate
DrawFrame
DrawFileName
XAdjust YAdjust translate
Column 1 sub Column_pos eq { /Column_pos 1 def /Row_pos Row_pos 1 add def }{ /Column_pos Column_pos 1 add def } ifelse
Row_pos Row gt { /Row_pos 0 def } if
} bind def
Related
This works really well with diagonals and the third row or third column. For some reason, when someone wins, either X or O, on the first and second row or columns, no win is signaled. Row and Col resemble the place where the play was made, and player resembles who did the play.
What's making my mind boggle is the fact that it doesn't recognize a win on all rows and columns, seems so weird to me that i'm just missing where the problem might be.
--[[
Function that checks if there is a win whenever a play is made
]]
function checkWin(row, col, player)
-- check rows. I have the row that the marker was placed. Go through it and see if there is a win.
for c = 1, 3 do
if board[row][c] ~= player then
break
end
if c == 3 then
gWhoWon = player
gameOver = true
end
end
-- check columns. I have the col that the marker was placed. Go through it and see if there is a win.
for r = 1, 3 do
if board[r][col] ~= player then
break
end
if r == 3 then
gWhoWon = player
gameOver = true
end
end
-- check diagonals. Check both diagonals and see if there is a win (can make this more efficient, only looking at
-- diagonals that matter).
-- first diag
for d = 1, 3 do
if board[d][d] ~= player then
break
end
if d == 3 then
gWhoWon = player
gameOver = true
end
end
-- anti diag
for d = 1, 3 do
if board[d][4-d] ~= player then
break
end
if d == 3 then
gWhoWon = player
gameOver = true
end
end
--[[
if turn == 9 then
gameOver = true
end
]]
end
Here's the function in which I initialize my board and where I call the checkWin function:
function PlayState:init()
xTurn = true
gameOver = false
turn = 1
gWhoWon = ""
-- board
board = {
{"", "", ""},
{"", "", ""},
{"", "", ""}
}
end
function PlayState:update(dt)
-- transition to win state when someone wins
if gameOver then
gStateMachine:change('win')
end
-- if there is a left mouse click, insert an "x" or an "o" on that square
if love.mouse.wasPressed(1) then
-- get mouse position
x = love.mouse.getX()
y = love.mouse.getY()
-- iterate through the board
for row = 1, 3 do
for col = 1, 3 do
-- if mouse click was inside a square and it is empty
if isInsideSquare(x, y, row, col) and isEmpty(row, col) then
-- put an "x" on the square
if xTurn then
board[col][row] = 'x'
checkWin(row, col, 'x') -- check if this move makes a win
xTurn = false
-- put an "o" on the square
else
board[col][row] = 'o'
checkWin(row, col, 'o') -- check if this move makes a win
xTurn = true
end
turn = turn + 1
end
end
end
end
end
There is a mix-up in using row and column values for the dimensions of the board matrix:
In the update method you have code like this: board[col][row] = 'x', so where the column is the first dimension of the matrix, but:
In the checkWin function, you have code like board[row][c] ~= player, so where the column is the second dimension of the matrix
This will lead to unexpected results. Make sure to harmonise your code so that each of the two array dimensions are always used for the same axis (row versus column).
Alright, so basically I am to create a tic tac toe game in pseudocode. Which sucks because I can't see output. Anyways,
/*
*Program by: Cory
*Program: Tic Tac Toe game
*
/
Module Main()
Boolean player = true
Constant Integer ROWS = 3, COLS = 3
Declare String values[ROWS][COLS] = "", "", "",
"", "", "",
"", "", ""
Call Module getIntro()
Call Module showBoard(values[][], ROWS, COLS)
Call Module playGame(values[][], COLS, ROWS, player)
End Module
Module getIntro()
Display "Hello, this is a simple tic tac toe game."
Display "It will rotate turns between players one and two,"
Display "While 3,3 would be the bottom right."
Display "Player 1 is X and player 2 is O"
End Module
Module showBoard(String values[][], Integer rows, Integer cols)
Declare Integer row, col
For row = 0 to rows - 1
For col = 0 to cols - 1
Display values[rows][cols]
End For
End For
End Module
Module playGame(String values[][], Integer cols, Integer rows, Boolean player) //places moves, checks for already placed moves
Declare Integer row, col
player = true
For row = 0 to rows - 1
For col = 0 to cols -1
If (player == true)
Display "First player's turn, please input your move"
Input values[row][col]
if (checkMove(values[][], rows, cols) == false)
Display "Invalid move, please try again"
Display "First player's turn again, please input your move"
Input values[row][col]
End If
values[row][col] = "X"
showBoard(values[row][col], rows, cols)
checkWin()
player = false
Else If (player == false)
Display "Second player's turn, please input your move"
Input values[row][col]
if (checkMove(values[][], rows, cols) == false)
Display "Invalid move, please try again"
Display "Second player's turn again, please input your move"
Input values[row][col]
End If
values[row][col] = "O"
showBoard(values[row][col], rows, cols)
checkWin()
player = true
End For
End For
End Module
Function Boolean checkMove(String values[][], Integer cols, Integer rows)
Declare Integer row, col
For row = 0 to rows - 1
For col = 0 to cols - 1
if (values[row][col] != "*")
Display "Player has already placed a move there"
End If
End For
End For
return false
End Function
Module checkWin()
checkRow(values[][], 3)
checkCol(values[][], 3)
checkDiagonal(values[][], 3, 3)
End Module
Module checkRow(String values[][], Integer rows) //checks horizontal win
Declare Integer row, col
For row = 0 to rows - 1
if (values[row][0] == "X")
Display "Player one has won!"
//player1Win = true
Else if (values[row][0] == "O")
Display "Player two has won!"
//player1Win = false
End If
End For
End Module
Module checkCol(String values[][], Integer cols) //checks vertical win
Declare Integer row, col
For col = 0 to cols -1
if (values[0][col] == "X")
Display "Player one has won!"
//player1Win = true
Else if (values[0][col] == "O")
Display "Player two has won!"
//player1Win = false
End If
End For
End Module
Module checkDiagonal(String values[][], Integer cols, Integer rows, Boolean player1Win) //checks Diagonal win
So 1) please look over my code and tell me if I'm doing something wrong or if there's a way I can make it look better
2) I need help checking for diagonal wins.
3) checking for ties
Answering it accordingly:
There are lots of modifications to be done in your code regarding condition checking and other "cases" which might result while playing the game. It will be better if you ask your question a bit more specifically.
As far as the diagonal check is concerned, do the same as in checkCol and checkRow, instead check for values[index][index], where index value will be same for both row and column.
For tie checking you can keep a flag variable which will return false when no rows, columns and diagonals match.
Update:
For the opposite diagonal, you have to check for values[index][SIZE-index-1].
I would like to split a rectangle in cells. In each cell it should be create a random coordinate (y, z).
The wide and height of the rectangle are known (initialW / initalH).
The size of the cells are calculated (dy / dz).
The numbers, in how many cells the rectangle to be part, are known. (numberCellsY / numberCellsZ)
Here my Code in Fortran to split the rectangle in Cells:
yRVEMin = 0.0
yRVEMax = initialW
dy = ( yRVEMax - yRVEMin ) / numberCellsY
zRVEMin = 0.0
zRVEMax = initialH
dz = ( zRVEMax - zRVEMin ) / numberCellsZ
do i = 1, numberCellsY
yMin(i) = (i-1)*dy
yMax(i) = i*dy
end do
do j = 1, numberCellsZ
zMin(j) = (j-1)*dz
zMax(j) = j*dz
end do
Now I would like to produce a random coordinate in each cell. The problem for me is, to store the coodinates in an array. It does not necessarily all be stored in one array, but as least as possible.
To fill the cells with coordinates it should start at the bottom left cell, go through the rows (y-direction), and after the last cell (numberCellsY) jump a column higher (z-dicrection) and start again by the first cell of the new row at left side. That should be made so long until a prescribed number (nfibers) is reached.
Here a deplorable try to do it:
call random_seed
l = 0
do k = 1 , nfibers
if (l < numberCellsY) then
l = l + 1
else
l = 1
end if
call random_number(y)
fiberCoordY(k) = yMin(l) + y * (yMax(l) - yMin(l))
end do
n = 0
do m = 1 , nfibers
if (n < numberCellsZ) then
n = n + 1
else
n = 1
end if
call random_number(z)
fiberCoordZ(m) = zMin(n) + z * (zMax(n) - zMin(n))
end do
The output is not what I want! fiberCoordZ should be stay on (zMin(1) / zMax(1) as long as numberCellsY-steps are reached.
The output for following settings:
nfibers = 9
numberCellsY = 3
numberCellsZ = 3
initialW = 9.0
initialH = 9.0
My random output for fiberCoordY is:
1.768946 3.362770 8.667685 1.898700 5.796713 8.770239 2.463412 3.546694 7.074708
and for fiberCoordZ is:
2.234807 5.213032 6.762228 2.948657 5.937295 8.649946 0.6795220 4.340364 8.352566
In this case the first 3 numbers of fiberCoordz should have a value between 0.0 and 3.0. Than number 4 - 6 a value between 3.0 and 6.0. And number 7 - 9 a value bewtween 6.0 - 9.0.
How can I solve this? If somebody has a solution with a better approach, please post it!
Thanks
Looking at
n = 0
do m = 1 , nfibers
if (n < numberCellsZ) then
n = n + 1
else
n = 1
end if
call random_number(z)
fiberCoordZ(m) = zMin(n) + z * (zMax(n) - zMin(n))
end do
we see that the z coordinate offset (the bottom cell boundary of interest) is being incremented inappropriately: for each consecutive nfibers/numberCellsZ coordinates n should be constant.
n should be incremented only every numberCellsY iterations, so perhaps a condition like
if (MOD(m, numberCellsY).eq.1) n=n+1
would be better.
Thanks francescalus! It works fine.
I added a little more for the case that nfibers > numberCellsY*numberCellsZ
n=0
do m = 1 , nfibers
if (MOD(m, numberCellsY).eq.1 .and. (n < numberCellsY)) then
n=n+1
end if
if (MOD(m, numberCellsY*numberCellsZ).eq.1 ) then
n = 1
end if
call random_number(z)
fiberCoordZ(m) = zMin(n) + z * (zMax(n) - zMin(n))
end do
I have a 2d array of objects, if the object has the property of clicked set to true, then it should be considered as "1" otherwise "0". These are blocks that are selected. I need to check if the selected boxes form a single rectangle. What is the best way to go about this?
High-level:
Keep track of the outer-most 1s.
Count all the 1s.
If the count equals the area encased by the outer-most 1s, we have a rectangle.
Pseudo-code:
left = width + 1
right = 0
top = height + 1
bottom = 0
count = 0
for x = 1 to width
for y = 1 to height
if grid[x][y] == 1
left = min(left , x)
right = max(right , x)
top = min(top , y)
bottom = max(bottom, y)
count++
if count > 0 and count == (right-left+1)*(bottom-top+1)
print "We have a rectangle!"
else
print "We don't have a rectangle!"
You could solve it like that:
Search for the first element which is 1
walk horizontal to the right, then down, then left, then up
if you came back to the origin, you have a rectangle
then ensure that all the other elements are 0.
This algorithm is O(n^2) and works if you only allow one rectangle. If you have multiple rectangles it gets complicated..
I'd do something like this (pseudocode):
// your 2d-array / matrix (N is the number of lines, M the number of columns)
m[N][M] = ...
// x coord of top left object containing 1
baseM = -1
baseFound = false
// expected width of rectangle
width = 0
widthLocked = false
// this is set to true after we started recognizing a rectangle and encounter
// a row where the object expected to be 1 in order to extend the rectangle
// is 0.
heightExceeded = false
// loop over matrix
for i = 1 to N: // lines
// at the beginning of a line, if we already found a base, lock the width
// (it cannot be larger than the number of 1s in the row of the base)
if baseFound: widthLocked = true
for j = 1 to M: // columns
if m[i][j] == 1:
if not baseFound:
baseM = j, baseFound = true
width = 1
else:
if j < baseM:
// not in rectangle in negative x direction
return false
if heightExceeded:
// not in rectangle in y direction
return false
if widthLocked:
// not in rectangle in positive x direction
if j - baseM >= width: return false
else:
width = j - baseM
elseif baseFound:
if widthLocked:
// check if we left the rectangle and memorize it
if j == baseM: heightExceeded = true
if not heightExceeded:
// check if object in rectangle is 0
if j > baseM && j < baseM + width: return false
if baseFound:
return true
else:
// what is the expected result if no rectangle has been found?
return ?
Runs in O(n). Beware of bugs.
Note: Most programming languages have 0-based arrays, so you may need to loop i from 0 to N - 1, same for j.
I read Create a tiff with only text and no images from a postscript file with ghostscript and try to use KenS`s answer.
But this method remove only "black" images - image contain data only in black channel (PDF has colorspace CMYK). How can i remove all images in my case?
This does a better job, but its incomplete. It doesn't deal with images using multiple data sources for example. Its essentially untested, except that I did test your smaller file (pages.pdf) by using ps2write to convert to PostScript and then the PostScript program below, and teh pdfwrite device, to convert back to PDF.
One of the first things you will notice is that almost all the text has vanished from your document. That's because the fonts you are using are bitmap fonts, and the program can't tell the difference between a bitmap representing a character, and any other kind of bitmap. For this file you can solve that by removing the definition of imagemask because all the characters use imagemask, and the other images use 'image'.
I have a sneaky suspicion the formatting of the program is going to get messed up here :-(
8<------------------------------8<--------------------------8<-------------------------
%!
%
% numbytes -file- ConsumeFileData -
%
/ConsumeFileData {
userdict begin
/DataString 256 string def
/DataFile exch def
/BytesToRead exch def
%(BytesToRead = ) print BytesToRead ==
mark
{
DataFile DataString readstring { % read bytes
/BytesToRead BytesToRead 256 sub def % not EOF subtract 256 from required amount.
%(Read 256 bytes) ==
%(BytesToRead now = ) print BytesToRead ==
} {
length
%(Read ) print dup 256 string cvs print (bytes) ==
BytesToRead exch sub /BytesToRead exch def % Reached EOF, subtract length read froom required amount
%(BytesToRead now = ) print BytesToRead ==
exit % and exit loop
} ifelse
} loop
%BytesToRead ==
BytesToRead 0 gt {
(Ran out of image data reading from DataSource\n) ==
} if
cleartomark
end
} bind def
%
% numbytes -proc- ConsumeProcData -
%
/ConsumeProcData {
userdict begin
/DataProc exch def
/BytesToRead exch def
{
DataProc exec % returns a string
length BytesToRead exch sub % subtract # bytes read
/BytesToRead exch def
BytesToRead 0 le {
exit % exit when read enough
} if
} loop
end
} bind def
/image {
(image) ==
dup type /dicttype eq {
dup /MultipleDataSources known {
dup /MultipleDataSources get {
(Can't handle image with multiple sources!) ==
} if
} if
dup /Width get % stack = -dict- width
exch dup /BitsPerComponent get % stack = width -dict- bpc
exch dup /Decode get % stack = width bpc -dict- decode
length 2 div % decode = 2 * num components
exch 4 1 roll % stack = -dict- width bpc ncomps
mul mul % stack = -dict- width*bpc*ncomps
7 add cvi 8 idiv % stack = -dict- width(bytes)
exch dup /Height get % stack = width -dict- height
exch /DataSource get % stack = width height DataSource
3 1 roll % stack = DataSource width height
mul % stack = DataSource widht*height
exch % stack = size DataSource
} {
5 -1 roll
pop % throw away matrix
mul mul % bits/sample*width*height
7 add cvi 8 idiv % size in bytes of data floor(bits+7 / 8)
exch % stack = size DataSource
} ifelse
dup type /filetype eq {
ConsumeFileData
} {
dup type /arraytype eq or
1 index type /packedarraytype eq or {
ConsumeProcData
} {
pop pop % Remove DataSource and size
} ifelse
} ifelse
} bind def
/imagemask {
(imagemask)==
dup type /dicttype eq {
dup /MultipleDataSources known {
dup /MultipleDataSources get {
(Can't handle imagemask with multiple sources!) ==
} if
} if
dup /Width get % stack = -dict- width
7 add cvi 8 idiv % size in bytes of width floor(bits+7 / 8)
exch dup /Height get % stack = width -dict- height
exch /DataSource get % stack = width height DataSource
3 1 roll % stack = DataSource width height
mul % stack = DataSource width*height
exch % stack = size DataSource
} {
5 -1 roll
pop % throw away matrix
mul mul % bits/sample*width*height
7 add cvi 8 idiv % size in bytes of data floor(bits+7 / 8)
exch % stack = size DataSource
} ifelse
dup type /filetype eq {
ConsumeFileData
} {
dup type /arraytype eq or
1 index type /packedarraytype eq or {
ConsumeProcData
} {
pop pop % Remove DataSource and size
} ifelse
} ifelse
} bind def
/colorimage {
(colorimage)==
dup 1 ne {
1 index
{
(Can't handle colorimage with multiple sources!) ==
} if
} {
exch pop % get rid of 'multi'
% stack: w h bpc m d ncomp
3 -1 roll pop % stack: w h bpc d ncomp
exch 5 -1 roll % stack d w h bpc ncomp
mul mul mul % stack: d w*h*bpc*ncomp
7 add cvi 8 idiv exch % stack: bytes datasource
} ifelse
dup type /filetype eq {
ConsumeFileData
} {
dup type /arraytype eq or
1 index type /packedarraytype eq or {
ConsumeProcData
} {
pop pop % Remove DataSource and size
} ifelse
} ifelse
} bind def
That technique should work for images in any colour, because the image operator is used for both colour and monochrome images. Unless your file uses the obselete level 1.5 'colorimage' operator. I can't recall if I redefined that operator in the example, if not then yuo can redefine it in a similar fashion.
In fact I see that I offered redefinitions for image, colorimage and imagemask, so all image types should be elided. Perhaps you could share an example ?