type error :integer argument expected - python

I am making a snake game in Python by the help of google , but I found some errors which i dont understand why its so happening...my code is
import random
import curses
s = curses.initscr()
curses.curs_set(0)
sh, sw = s.getmaxyx()
w = curses.newwin(sh, sw, 0, 0)
w.keypad(1)
w.timeout(100)
snk_x = sw/4
snk_y = sh/2
snake = [
[snk_y, snk_x],
[snk_y, snk_x-1],
[snk_y, snk_x-2]
]
food = [sh/2, sw/2]
w.addch(food[0], food[1], curses.ACS_PI)
key = curses.KEY_RIGHT
while True:
next_key = w.getch()
key = key if next_key == -1 else next_key
if snake[0][0] in [0, sh] or snake[0][1] in [0, sw] or snake[0] in snake[1:]:
curses.endwin()
quit()
new_head = [ snake[0][0], snake[0][1]]
if key == curses.KEY_DOWN:
new_head[0] += 1
if key == curses.KEY_UP:
new_head[0] -= 1
if key == curses.KEY_LEFT:
new_head[1] -= 1
if key == curses.KEY_RIGHT:
new_head[1] += 1
snake.insert(0, new_head)
if snake[0] == food:
food = None
while food is None:
nf = [
random.randint(1, sh-1),
random.randint(1, sw-1)
]
food = nf if nf not in snake else None
w.addch(food[0], food[1], curses.ACS_PI)
else:
tail = snake.pop()
w.addch(tail[0], tail[1], ' ')
w.addch(snake[0][0], snake[0][1], curses.ACS_CKBOARD)
While running this code I got two errors, i.e.,
Traceback (most recent call last):
File "snakegame.py", line 20, in <module>
w.addch(food[0], food[1], curses.ACS_PI)
TypeError: integer argument expected, got float

In Python 3 / results in floating point results. To get integer results, use integer division //.
food = [sh // 2, sw // 2]
In addition, your snake is initialized with floating point numbers. Again, in order to make sure that snake contains only integers, do this:
snk_x = sw // 4
snk_y = sh // 2
After that, you will see a different crash due to new_head exceeding sw or sh (if you leave the snake move by itself without pressing any keys) but this is unrelated to the original issue.

Modified a bit, no error, but food not coming second time.
import random
import curses
s = curses.initscr()
curses.curs_set(0)
sh, sw = s.getmaxyx()
w = curses.newwin(sh, sw, 0, 0)
w.keypad(1)
w.timeout(100)
snk_x = sw/4
snk_y = sh/2
snake = [
[snk_y, snk_x],
[snk_y, snk_x-1],
[snk_y, snk_x-2]
]
food = [sh/2, sw/2]
w.addch(int(food[0]), int(food[1]), curses.ACS_PI)
key = curses.KEY_RIGHT
while True:
next_key = w.getch()
key = key if next_key == -1 else next_key
if snake[0][0] in [0, sh] or snake[0][1] in [0, sw] or snake[0] in snake[1:]:
curses.endwin()
quit()
new_head = [snake[0][0], snake[0][1]]
if key == curses.KEY_DOWN:
new_head[0] += 1
if key == curses.KEY_UP:
new_head[0] -= 1
if key == curses.KEY_LEFT:
new_head[1] -= 1
if key == curses.KEY_RIGHT:
new_head[1] += 1
snake.insert(0, new_head)
if snake[0] == food:
food = None
while food is None:
nf = [
random.randint(1, sh-1),
random.randint(1, sw-1)
]
food = nf if nf not in snake else None
w.addch(int(food[0]), int(food[1]), curses.ACS_PI)
else:
tail = snake.pop()
w.addch(int(tail[0]), int(tail[1]), ' ')
w.addch(int(snake[0][0]), int(snake[0][1]), curses.ACS_CKBOARD)
enter image description here

This is a bit modified and works fine for me.
import random
import curses
s=curses.initscr()
curses.curs_set(0)
sh,sw=s.getmaxyx()
w=curses.newwin(sh,sw,0,0)
w.keypad(1)
w.timeout(100)
snk_x=sw//4
snk_y=sh//2
snake=[
[snk_y,snk_x],
[snk_y,snk_x-1],
[snk_y,snk_x-2]
]
food=([sh//2,sw//2])
w.addch(food[0],food[1],curses.ACS_PI)
key=curses.KEY_RIGHT
while True:
next_key=w.getch()
key=key if next_key==-1 else next_key
if snake [0][0] in [0,sh] or snake [0][1] in [0,sw] or snake[0] in snake [1:]:
curses.endwin()
quit()
new_head =[snake[0][0],snake[0][1]]
if key ==curses.KEY_DOWN:
new_head[0]+=1
if key==curses.KEY_UP:
new_head[0]-=1
if key==curses.KEY_LEFT:
new_head[1]-=1
if key==curses.KEY_RIGHT:
new_head[1]+=1
snake.insert(0,new_head)
if snake[0]==food:
food=None
while food is None:
nf=[
random.randint(1,sh-1),
random.randint(1,sw-1)
]
food=nf if nf not in snake else None
w.addch(food[0],food[1],curses.ACS_PI)
else:
tail=snake.pop()
w.addch(tail[0],tail[1],' ')
w.addch(snake[0][0],snake[0][1],curses.ACS_CKBOARD)

This should work fine
import random
import curses
s = curses.initscr()
curses.curs_set(0)
sh, sw = s.getmaxyx()
w = curses.newwin(sh, sw, 0, 0)
w.keypad(1)
w.timeout(100)
snk_x = int(sw/4)
snk_y = int(sh/2)
snake = [
[snk_y, snk_x],
[snk_y, snk_x-1],
[snk_y, snk_x-2]
]
food = [sh/2, sw/2]
w.addch(int(food[0]), int(food[1]), curses.ACS_PI)
key = curses.KEY_RIGHT
while True:
next_key = w.getch()
key = key if next_key == -1 else next_key
if snake[0][0] in [0, sh] or snake[0][1] in [0, sw] or snake[0] in snake[1:]:
curses.endwin()
quit()
new_head = [snake[0][0], snake[0][1]]
if key == curses.KEY_DOWN:
new_head[0] += 1
if key == curses.KEY_UP:
new_head[0] -= 1
if key == curses.KEY_LEFT:
new_head[1] -= 1
if key == curses.KEY_RIGHT:
new_head[1] += 1
snake.insert(0, new_head)
if snake[0] == food:
food = None
while food is None:
nf = [
random.randint(1, sh-1),
random.randint(1, sw-1)
]
food = nf if nf not in snake else None
w.addch(food[0], food[1], curses.ACS_PI)
else:
tail = snake.pop()
w.addch(int(tail[0]), int(tail[1]), ' ')
w.addch(int(snake[0][0]), int(snake[0][1]), curses.ACS_CKBOARD)

Other solutions are over-using int() in more places than needed. You only need to use // integer division in the places I've shown.
Also a bit more fun. Diamond back snake.
import random
import curses
s = curses.initscr()
curses.curs_set(0)
sh, sw = s.getmaxyx()
w = curses.newwin(sh, sw, 0, 0)
w.keypad(1)
w.timeout(100)
snk_x = sw//4 # use integer division here
snk_y = sh//2 # use integer division here
snake = [
[snk_y, snk_x],
[snk_y, snk_x-1],
[snk_y, snk_x-2]
]
food = [sh//2, sw//2] # use integer division here
w.addch(food[0], food[1], curses.ACS_PI)
key = curses.KEY_RIGHT
while True:
next_key = w.getch()
key = key if next_key == -1 else next_key
if snake[0][0] in [0, sh] or snake[0][1] in [0, sw] or snake[0] in snake[1:]:
curses.endwin()
quit()
new_head = [snake[0][0], snake[0][1]]
if key == curses.KEY_DOWN:
new_head[0] += 1
if key == curses.KEY_UP:
new_head[0] -= 1
if key == curses.KEY_LEFT:
new_head[1] -= 1
if key == curses.KEY_RIGHT:
new_head[1] += 1
w.addch(snake[0][0], snake[0][1], curses.ACS_DIAMOND)
snake.insert(0, new_head)
if snake[0] == food:
food = None
while food is None:
nf = [
random.randint(1, sh-1),
random.randint(1, sw-1)
]
food = nf if nf not in snake else None
w.addch(food[0], food[1], curses.ACS_PI)
else:
tail = snake.pop()
w.addch(tail[0], tail[1], ' ')
w.addch(snake[0][0], snake[0][1], curses. ACS_CKBOARD)

use // not / because interpret see your parameter in flote values while you want to insert integer values
snk_x = sw//4
snk_y = sh//2
snake = [
[snk_y, snk_x],
[snk_y, snk_x-1],
[snk_y, snk_x-2],]
food = [sh//2, sw//2]

Related

how do i disappear food from inside snake with python?

I want to make the food disappear from the snake when it eats the food but the string stays visible inside snake making the snake look weird with the food in the snake... now what I been trying is this line of code:
Error ( 'tuple' object has no attribute 'replace' )
for food in snake:
food = food.replace(food, ' ')
I just started writting code not too long ago... i only know the basics of python but still confusing and I'm trying to learn as i work in this project to make the game better...
This is the python Script:
import curses
from mimetypes import init
from random import randint
WINDOW_WIDTH = 60
WINDOW_HEIGHT = 20
# Set Up
curses.initscr()
win = curses.newwin(WINDOW_HEIGHT, WINDOW_WIDTH, 0, 0) # y, x
win.keypad(1)
curses.noecho()
curses.curs_set(0)
win.border(0)
win.nodelay(1)
# Snake And Food
snake = [(4, 10), (4, 9), (4, 8)]
food = (10, 10)
win.addch(food[0], food[1], '⊠')
# Game Logic
score = 0
ESC = 27
key = curses.KEY_RIGHT
while key != ESC:
win.addstr(0, 2, 'score ' + str(score) + ' ')
win.timeout(150 - (len(snake)) // 5 + len(snake)//10 % 120)
prev_key = key
event = win.getch()
key = event if event != -1 else prev_key
if key not in [curses.KEY_LEFT, curses.KEY_RIGHT, curses.KEY_UP, curses.KEY_DOWN, ESC]:
prev_key
# Calculating Coordinates
y = snake[0][0]
x = snake[0][1]
if key == curses.KEY_DOWN:
y += 1
if key == curses.KEY_UP:
y -= 1
if key == curses.KEY_LEFT:
x -= 1
if key == curses.KEY_RIGHT:
x += 1
snake.insert(0, (y, x))
# Hit Border Reboot
if y == 0: break
if y == WINDOW_HEIGHT-1: break
if x == 0: break
if x == WINDOW_WIDTH-1: break
# dead.Self Snake
if snake[0] in snake[1:]: break
if snake[0] == food:
# Eat The Food
score += 1
food = ()
while food == ():
food = (randint(1,WINDOW_HEIGHT-2), randint(1,WINDOW_WIDTH-2))
if food in snake:
food = ()
win.addch(food[0], food[1], '⊠')
else:
# Move Snake
last = snake.pop()
win.addch(last[0], last[1], ' ')
win.addch(snake[0][0], snake[0][1], '▇')
# Working in Making the food Disappear inside snake
curses.endwin()
print(f"Final score = {score}")
I'm trying to figure out if it goes at the bottom of the code or somewhere else... I try a few things ex: While, If, and different variables...
P.s. ((I just wrote the code but is not mines I did'nt copy & paste neither...))
Please Help!!....

How do I prevent this Integer expectation error?

I'm making a simple little snake game as coding practice.
While trying to add the tail character to the window, I get this error. I know that I am not giving it integers, but I do not know what to do differently in order to.
Here is the error:
line 56, in <module>
w.addch(tail[0], tail[1], ' ')
TypeError: integer argument expected, got float
Here is the part generating error:
else:
tail = snake.pop()
w.addch(tail[0], tail[1], ' ')
Heres the full code:
import random
import curses
s = curses.initscr()
curses.curs_set(0)
sh, sw = s.getmaxyx()
w = curses.newwin(sh, sw, 0, 0)
w.keypad(1)
w.timeout(100)
snk_x = sw/4
snk_y = sh/2
snake = [
[snk_y, snk_x],
[snk_y, snk_x-1],
[snk_y, snk_x-2]
]
food = [sh/2, sw/2]
w.addch(food[0], food[1], curses.ACS_PI)
key = curses.KEY_RIGHT
while True:
next_key = w.getch()
key = key if next_key == -1 else next_key
if snake[0][0] in [0, sh] or snake[0][1] in [0, sw] or snake[0] in snake[1:]:
curses.endwin()
quit()
new_head = [snake[0][0], snake[0][1]]
if key == curses.KEY_DOWN:
new_head[0] += 1
if key == curses.KEY_UP:
new_head[0] -= 1
if key == curses.KEY_RIGHT:
new_head[1] += 1
if key == curses.KEY_LEFT:
new_head[1] -= 1
snake.insert(0, new_head)
if snake[0] == food:
food = None
while food is None:
nf = [
random.randinit(1, sh-1),
random.randinit(1, sw-1)
]
food = nf if nf not in snake else None
w.addch(food[0], food[1], curses.ACS_PI)
else:
tail = snake.pop()
w.addch(tail[0], tail[1], ' ')
w.addch(snake[0][0], snake[0][1], curses.ACS_CKBOARD)
I cant think of a way to be more direct so this is me filling the text requirements.
reference for code?:
s = screen, snk_x/y = Snake x/y, sw/sh = screen width/height, w = window.
If I can be anymore clear let me know.
addch expects int. But division of integers in python 3 returns float.
You can:
convert the numbers to int w.addch(int(food[0]), int(food[1]), curses.ACS_PI)
or you can use // instead of / to do integer division
You can try just casting the values to integers using int() as follows:
w.addch(int(tail[0]), int(tail[1]), ' ')

Minimax implementation in tic tac toe (Python) not working - no idea why

I am currently trying to make a Tic Tac Toe game with minimax implemented in Python. Another feature that I'm trying to implement is different board sizes. But overall, unfortunately, the algorithm is not working.
As a beginner, this is not a surprise for me, but this case seems hopeless. I tried tweaking quite a lot of things (may seem like a lot just to me) just to end up with the same result - the computer filling up the fields from top left to bottom right.
#Sprawdzenie czy ktos wygral w poziomie lub pionie / straight line check
def winLine(line, letter):
return all(n == letter for n in line)
#Utworzenie nowej listy z elementow przekatnych / diagonal check
def winDiagonal(board, letter):
arr = []
tArr = []
for n in range(boardSize):
arr.append(board[n][n])
tArr.append(board[n][boardSize-n-1])
if winLine(arr, letter):
return True
elif winLine(tArr, letter):
return True
else:
return False
def checkWinner (board):
#Liczenie wolnych pol / checking the available fields
openSpots = 9
for n in range(boardSize):
for m in range(boardSize):
if board[n][m] == '0':
openSpots += 1
#Transpozycja planszy, by mozna bylo latwo zastosowac winLine na kolumach / transposition of the board
for letter in (person, ai):
transPos = list(zip(*board))
#Sprawdzanie w poziomie / horizontal check
if any(winLine(row, letter) for row in board):
#print('winline horizontal')
return letter
#Sprawdzanie w pionie / vertical check
elif any (winLine(col, letter) for col in transPos):
#print('winline vertical')
return letter
#Sprawdzanie po przekatnych / diagonal check
elif winDiagonal(board, letter):
return letter
elif openSpots == 0: return 'tie'
else: return 'none'
#Funkcja sprawdzajaca czy dane pole jest wolne / checks whether the field is available
def available (row, col):
global board
#Sprawdzenie czy pole jest wolne
if board[row][col] == '0':
return True
else:
return False
#Stale dla algorytmu minimax / minimax initial scores to compare against
minTarget = float('inf')
maxTarget = float('-inf')
#Slownik z wartosciami liczbowi dla wynikow, komputer maksymalizuje / a dictionary with scores for particular results
scores = {
'X': 10,
'O': -10,
'tie': 0
}
#Algorytm minimax
def minimax(myBoard, depth, maximizes):
#Sprawdzenie czy zaszla wygrana lub remis / Checking whether there is a win or tie
res = checkWinner(myBoard)
if (res != 'none'):
return scores[res]
#Gracz maksymalizujacy/ Maximizing player
elif maximizes == True:
bestScoreMax = maxTarget
for n in range(boardSize):
for m in range(boardSize):
if board[n][m] == '0':
board[n][m] = person
score = minimax(board, depth + 1, False)
board[n][m] = '0'
bestScoreMax = max([score, bestScoreMax])
return bestScoreMax
#Gracz minimalizujacy / minimizing player
elif maximizes == False:
bestScoreMin = minTarget
for n in range(boardSize):
for m in range(boardSize):
if board[n][m] == '0':
board[n][m] = ai
score = minimax(board, depth + 1, True)
board[n][m] = '0'
bestScoreMin = min([score, bestScoreMin])
return bestScoreMin
def makeMove(row, col):
global board
board[row][col] = ai
def computedMove():
global board
myBoard = board
computedTarget = maxTarget
moveX = 2
moveY = 2
for n in range(boardSize):
for m in range(boardSize):
if myBoard[n][m] == '0':
score = minimax(myBoard, 0, True)
if score > computedTarget:
computedTarget = score
moveX = n
moveY = m
makeMove(moveX, moveY)
#print(str(move.x) + ' ' + str(move.y))
# Funkcja pobierajaca ruch uzytkownika / player input for the move
def getPlayerMove():
global board
res = input('Please type in your move on the form \"x y\", x being the number of the row and y the number of the column of your choosing.\n')
col, row = res.split(" ")
row = int(row)
col = int(col)
if available(row-1, col-1):
board[row-1][col-1] = person
else:
print('You cannot make that move')
getPlayerMove()
def drawBoard():
global board
for n in range(boardSize):
for m in range(boardSize):
if board[n][m] == '0':
print(' - ', end='')
else:
print(' '+board[n][m]+' ', end='')
print('\n')
#Zmienna powiadamiajaca o stanie rozgrywki / variable indicating the state of the game
playing = False
# initializing the variable
boardSize = 0
# initializing the players
person = 'X'
ai = 'O'
#Gracz posiadajacy ruch (a takze rozpoczynajacy) / player who is playing at the moment
currentPlayer = ''
while True:
currentPlayer = person
boardSize = int(input("Please enter the size of the board. (one side)\n"))
global board
board = [['0' for i in range(boardSize)] for i in range(boardSize)]
print("You go first.")
playing = True
while playing:
if currentPlayer == person:
drawBoard()
getPlayerMove()
if checkWinner(board) == person:
drawBoard()
print("Yaay, you won!")
playing = False
else:
if checkWinner(board) == 'tie':
drawBoard()
print('It\'s a tie!')
break
else:
currentPlayer = ai
elif currentPlayer == ai:
computedMove()
if checkWinner(board) == ai:
drawBoard()
print('You lose!')
playing = False
else:
if checkWinner(board) == 'tie':
drawBoard()
print('It\'s a tie!')
break
else:
currentPlayer = person
if not input('Do you want to play again?').lower().startswith('y'):
break
In computedMove, you should first play the ai move then check the scores.
def computedMove():
global board
myBoard = board
computedTarget = maxTarget
moveX = 2
moveY = 2
for n in range(boardSize):
for m in range(boardSize):
if myBoard[n][m] == '0':
myBoard[n][m] = ai #This is added
score = minimax(myBoard, 0, True)
if score > computedTarget:
computedTarget = score
moveX = n
moveY = m
makeMove(moveX, moveY)
Also in minimax function, you should use same variable for myBoard and board.

Error in Python application

I have made a snakes game in Python which was referred from someplace, but am getting error.
The program snakes.py is given below:
import random
import curses
s= curses.initscr()
curses.curs_set(0)
sh, sw = s.getmaxyx()
w = curses.newwin(sh, sw, 0, 0)
w.keypad(1)
w.timeout(100)
snk_x = sw/4
snk_y = sh/2
snake = [
[snk_y, snk_x],
[snk_y, snk_x-1],
[snk_y, snk_x-2]
]
food = [sh/2, sw/2]
w.addch(food[0], food[1], curses.ACS_PI)
key = curses.KEY_RIGHT
while True:
next_key = w.getch()
key = key if next_key == -1 else next_key
if snake[0][0] in [0,sh] or snake[0][1] in [0, sw] or snake[0] in snake[1:]:
curses.endwin()
quit()
new_head = [snake[0][0], snake[0][1]]
if key == curses.KEY_DOWN:
new_head[0] +=1
if key == curses.KEY_UP:
new_head[0] -=1
if key == curses.KEY_LEFT:
new_head[1] -=1
if key == curses.KEY_RIGHT:
new_head[1] +=1
snake.insert(0, new_head)
if snake[0] == food:
food = None
while food is None:
nf = [
random.randint(1, sh-1),
random.randint(1, sw-1)
]
food = nf if nf not in snake else None
w.addch(food[0], food[1], curses.ACS_PI)
else:
tail = snake.pop()
w.addch(tail[0], tail[1], ' ')
w.addch(snake[0][0], snake[0][1], curses.ACS_CKBOARD)
I am getting the following error on w.addch(food[0], food[1], curses.ACS_PI):
TypeError: integer argument expected, got float.
I am also usng python 3.6 version, so how to fix this code.
In Python 3 the slash operator produces a float, even if both its arguments were ints. So your line food = [sh/2, sw/2] produces a list of two floats.
You should use the double-slash operator which produces an int:
food = [sh//2, sw//2]
food = [sh/2, sw/2]
In Python 3, the division / operator always produces floating-point values.
You should consider using the integer division operator, //.

'break' outside loop in snake game

I'm currently making a snake game in python (IDLE 3.6.0) and it keeps coming up with an error called 'break' outside loop. What does that mean? What am I doing wrong. This is the first time I've ever come accross this error.
Here's my code:
# SNAKES GAME
# Use ARROW KEYS to play, SPACE BAR for pausing/resuming and Esc Key for exiting
import curses
from curses import KEY_RIGHT, KEY_LEFT, KEY_UP, KEY_DOWN
from random import randint
curses.initscr()
win = curses.newwin(20, 60, 0, 0)
win.keypad(1)
curses.noecho()
curses.cur_set(0)
win.border(0)
win.nodelay(1)
key = KEY_RIGHT # Initalizing Values
score = 0
snake = [[4,10], [4,9], [4,8]] # Initial snake co-ordinates
food = [10,20] # First food co-ordinates
win.addc(food[0], food[1], '*') # Prints the food
while key != 27:
win.border(0)
win.addstr(0, 2, 'Score :' + str(score) + ' ') # Printing 'Score' and
win.addstr(0, 27, ' SNAKE ') # 'SNAKE' strings
win.timeout(150 - (len(snake)/5 + len(snake)/10)%120)
prevKey = key # Previous key pressed
event = win.getch
key = key if event == -1 else event
if key == ord(' '): # If SPACE BAR is pressed, wait for another
key = -1 # one (Pause/Resume)
while key != ord(' '):
key = win.getch()
key = prevKey
continue
if key not in [KEY_LEFT, KEY_RIGHT, KEY_UP, KEY_DOWN, 27]: # If an invalid key is pressed
key = prevKey
# Calculates the new coordinates of the head of the snake. NOTE: len(snake) increases.
# This is taken care of later at [1].
snake.insert(0, [snake[0][0] + (key == KEY_DOWN and 1) + (key == KEY_UP and -1), snake[0][1] + (key == KEY_LEFT and -1) + (key == KEY_RIGHT and 1)])
# If snake crosses the boundaries, make it enter from the other side
if snake[0][0] == 0: snake[0][0] = 18
if snake[0][1] == 0: snake[0][1] = 58
if snake[0][0] == 19: snake[0][0] = 1
if snake[0][1] == 59: snake[0][1] = 1
# Exit if snake crosses the boundaries (Uncomment to enable)
# if snake[0][0] == 0 or snake[0][0] == 19 or snake[0][1] == 0 or snake[0][1] == 59: break
# If snake runs over itself
if snake[0]in snake[1:]: break
if snake[0] == food:
food = []
score += 1
while food == []:
food = [randint(1, 18), randint(1, 58)]
if food in snake: food = []
win.addch(food[0], food[1], '*')
else:
last = snake.pop()
win.addch(last[0], last[1], ' ')
win.addch(snake[0][0], snake[0][1], '#')
curses.erdwin()
print("\nScore - " + str(score))
print("http://bitemelater.in\n")
I'd be glad if you could help! Thanks!
The line that says if snake[0]in snake[1:]: break is where your error is stemming from. You probably want to use some kind of game ending function to display points and high scores and such:
def end_game():
#do your game ending things here
Then you would call that function here:
if snake[0]in snake[1:]: end_game()
EDIT:
I found this in relation to your curses error: Error no module named curses. It seems as if curses doesn't support Windows machines. Try installing UniCurses or this binary.

Categories

Resources