AttributeError: module 'curses' has no attribute 'cur_set' - python-3.x

import random
import curses
s = curses.initscr()
curses.cur_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[0] -= 1
if key == curses.KEY_RIGHT:
new_head[0] += 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)

curses doesn't have a cur_set() method, but curs_set().
curses.curs_set(0)

Related

I'm running a odd/even game in Python and I get stuck once I need to define a winner

#Here I define the user and cpu function
cpu_num = random.randint(1,6)
user_selection = ["Odd", "Even"]
def cpu_choice():
choice = random.randint(1,6)
print("The computer's choice is",choice)
return choice
def user_choice():
while(True):
choice = input("Odd or Even? ")
if choice in user_selection:
print("Your choice is",choice)
return choice
else:
print("You did not write your answer correctly, please try again.")
#In this function I define the result of each round based on previous formulas and two new variables (num_rounds and user_lives) and everything works well
def round_result():
num_rounds = 0
user_lives = 10
while num_rounds < 8 and user_lives > 0:
user_pick = user_choice()
cpu_pick = cpu_choice()
if (cpu_pick % 2 == 0) and (user_pick == "Even"):
print (f'You have {user_lives + cpu_pick} lives left')
num_rounds += 1
user_lives = user_lives + cpu_pick
if (cpu_pick % 2 == 0) and (user_pick == "Odd"):
print (f'You have {user_lives - cpu_pick} lives left')
num_rounds += 1
user_lives = user_lives - cpu_pick
if (cpu_pick % 2 != 0) and (user_pick == "Even"):
print (f'You have {user_lives - cpu_pick} lives left')
num_rounds += 1
user_lives = user_lives - cpu_pick
if (cpu_pick % 2 != 0) and (user_pick == "Odd"):
print (f'You have {user_lives + cpu_pick} lives left')
num_rounds += 1
user_lives = user_lives + cpu_pick
#Everything works well until here, I don't know what am I doing wrong in the winner function
def winner():
user_won = user_lives > 0 and num_rounds == 8
cpu_won = user_lives < 0
game = round_result()
while game:
if user_won is True:
print ('You won')
if cpu_won is True:
print ('Cpu won')

Why doesn't the window update in curses?

I took this nice example of a simple curses application with a list. I wanted to make it scrollable, so I changed the part of the list that gets shown. However, I can scroll down and back up, but the contents shown doesn't change (only the highlighted line, not the lines shown).
What am I doing wrong?
MVCE
#!/usr/bin/env python
import curses
from curses import panel
class Menu(object):
def __init__(self, items, stdscreen):
self.window = stdscreen.subwin(0, 0)
self.window.keypad(1)
self.panel = panel.new_panel(self.window)
self.panel.hide()
panel.update_panels()
self.position = 0
self.items = items
def navigate(self, n):
self.position += n
if self.position < 0:
self.position = 0
elif self.position >= len(self.items):
self.position = len(self.items) - 1
def display(self):
self.panel.top()
self.panel.show()
self.window.clear()
while True:
self.window.refresh()
curses.doupdate()
start = 0
# The next 3 lines seem not to work as intended
while start + (curses.LINES - 1) < self.position:
start += curses.LINES
for index, item in enumerate(self.items[start:curses.LINES - 1], start=start):
if index == self.position:
mode = curses.A_REVERSE
else:
mode = curses.A_NORMAL
msg = "%d. %s" % (index, item[0])
self.window.addstr(1 + index, 1, msg, mode)
key = self.window.getch()
if key in [curses.KEY_ENTER, ord("\n"), curses.KEY_RIGHT]:
self.items[self.position][1]()
elif key == curses.KEY_UP:
self.navigate(-1)
elif key == curses.KEY_DOWN:
self.navigate(1)
elif key == curses.KEY_LEFT:
break
self.window.clear()
self.panel.hide()
panel.update_panels()
curses.doupdate()
class MyApp(object):
def __init__(self, stdscreen):
self.screen = stdscreen
curses.curs_set(0)
submenu_items = [("beep", curses.beep), ("flash", curses.flash)]
submenu = Menu(submenu_items, self.screen)
main_menu_items = [
("beep", curses.beep),
("flash", curses.flash),
("submenu", submenu.display),
]
for i in range(200):
main_menu_items.append((f"flash {i}", curses.flash))
main_menu = Menu(main_menu_items, self.screen)
main_menu.display()
if __name__ == "__main__":
curses.wrapper(MyApp)
Basically that's because you're not updating the upper limit on the slice used in this loop:
for index, item in enumerate(self.items[start:curses.LINES - 1], start=start):
Here's a better version
MVCE
#!/usr/bin/env python
import curses
from curses import panel
class Menu(object):
def __init__(self, items, stdscreen):
self.window = stdscreen.subwin(0, 0)
self.window.keypad(1)
self.panel = panel.new_panel(self.window)
self.panel.hide()
panel.update_panels()
self.position = 0
self.items = items
def navigate(self, n):
self.position += n
if self.position < 0:
self.position = 0
elif self.position >= len(self.items):
self.position = len(self.items) - 1
def display(self):
self.panel.top()
self.panel.show()
self.window.clear()
while True:
start = 0
self.window.clear()
while start + (curses.LINES - 1) < self.position:
start += curses.LINES
myrow = self.position - start
mycol = 0
for index, item in enumerate(self.items[start:start + curses.LINES - 1], start=start):
if index == self.position:
mode = curses.A_REVERSE
else:
mode = curses.A_NORMAL
msg = "%d. %s" % (index, item[0])
self.window.addstr(index - start, 0, msg, mode)
if index == self.position:
(myrow, mycol) = self.window.getyx()
self.window.move(myrow, mycol)
key = self.window.getch()
if key in [curses.KEY_ENTER, ord("\n"), curses.KEY_RIGHT]:
self.items[self.position][1]()
elif key == curses.KEY_UP:
self.navigate(-1)
elif key == curses.KEY_DOWN:
self.navigate(1)
elif key == curses.KEY_LEFT:
break
self.window.clear()
self.panel.hide()
panel.update_panels()
curses.doupdate()
class MyApp(object):
def __init__(self, stdscreen):
self.screen = stdscreen
curses.curs_set(1)
submenu_items = [("beep", curses.beep), ("flash", curses.flash)]
submenu = Menu(submenu_items, self.screen)
main_menu_items = [
("beep", curses.beep),
("flash", curses.flash),
("submenu", submenu.display),
]
for i in range(200):
main_menu_items.append((f"flash {i}", curses.flash))
main_menu = Menu(main_menu_items, self.screen)
main_menu.display()
if __name__ == "__main__":
curses.wrapper(MyApp)

Class player - Animation stop first frame

Quick question. I have my Player Class, working perfectly. Except for a small detail. This is the class:
from dict.entity_dict import player, player_class
from collections import OrderedDict
import pyglet, random
key = pyglet.window.key
class Player(pyglet.sprite.Sprite):
dir_stand = "south"
dir_run = "south"
sprite_stand = 3
sprite_run = 3
image = None
s = 0
def __init__(self, game):
self.game = game
self.keyboard = key.KeyStateHandler()
self.statistics_base = OrderedDict()
self.image_stand = pyglet.resource.image(player.get("player_stand", {'x': None}).get("resource"))
self.image_run = pyglet.resource.image(player.get("player_run", {'x': None}).get("resource"))
self.image_stand_width = player.get("player_stand", {'x': None}).get("width")
self.image_stand_height = player.get("player_stand", {'x': None}).get("height")
self.image_run_width = player.get("player_run", {'x': None}).get("width")
self.image_run_height = player.get("player_run", {'x': None}).get("height")
self.vx = self.game.wd / 2
self.vy = self.game.wh / 2
self.load_sprite()
def class_player(self, type):
self.statistics_base["hp"] = player_class.get(type, {'x': None}).get("hp")
self.statistics_base["atk"] = player_class.get(type, {'x': None}).get("atk")
self.statistics_base["dif"] = player_class.get(type, {'x': None}).get("dif")
self.statistics_base["atk_sp"] = player_class.get(type, {'x': None}).get("atk_sp")
self.statistics_base["dif_sp"] = player_class.get(type, {'x': None}).get("dif_sp")
self.statistics_base["vel"] = player_class.get(type, {'x': None}).get("vel")
for stat in self.statistics_base:
if self.statistics_base[stat] is None:
self.statistics_base[stat] = 10
def animation(self, image, da, width, height):
frame_list = [image.get_region(x=width * i, y=height * da, width=46, height=58) for i in range(22)]
image_animation = pyglet.image.Animation.from_image_sequence(frame_list, 0.10, True)
return image_animation
def direction_sprite(self):
if self.dir_stand == "north":
self.sprite_stand = 7
elif self.dir_stand == "east":
self.sprite_stand = 5
elif self.dir_stand == "south":
self.sprite_stand = 3
elif self.dir_stand == "west":
self.sprite_stand = 1
if self.dir_run == "north":
self.sprite_run = 7
elif self.dir_run == "north-east":
self.sprite_run = 6
elif self.dir_run == "east":
self.sprite_run = 5
elif self.dir_run == "south-east":
self.sprite_run = 4
elif self.dir_run == "south":
self.sprite_run = 3
elif self.dir_run == "south-west":
self.sprite_run = 2
elif self.dir_run == "west":
self.sprite_run = 1
elif self.dir_run == "north-west":
self.sprite_run = 0
def load_sprite(self):
if not self.keyboard[key.W] and not self.keyboard[key.S] and not self.keyboard[key.D] and not self.keyboard[key.A]:
self.keyboard.clear()
img = self.image_stand
img_width = self.image_stand_width
img_height = self.image_stand_height
da = self.sprite_stand
else:
img = self.image_run
img_width = self.image_run_width
img_height = self.image_run_height
da = self.sprite_run
self.direction_sprite()
self.image = self.animation(img, da, img_width, img_height)
self.image.width, self.image.height = img_width, img_height
self.image.anchor_x, self.image.anchor_y = img_width // 2, img_height // 2
self.sprite = pyglet.sprite.Sprite(self.image, batch=self.game.Batch, group=self.game.GroupEntitySprite)
self.sprite.x = self.vx
self.sprite.y = self.vy
def key_player(self):
if self.keyboard[key.W]:
self.vy += 1
self.dir_stand = "north"
self.dir_run = "north"
if self.keyboard[key.S]:
self.vy -= 1
self.dir_stand = "south"
self.dir_run = "south"
if self.keyboard[key.D]:
self.vx += 1
self.dir_stand = "east"
self.dir_run = "east"
if self.keyboard[key.A]:
self.vx -= 1
self.dir_stand = "west"
self.dir_run = "west"
if self.keyboard[key.W] and self.keyboard[key.D]:
random1 = random.randint(1, 2)
if random1 == 1:
self.dir_stand = "north"
else:
self.dir_stand = "east"
self.dir_run = "north-east"
if self.keyboard[key.S] and self.keyboard[key.D]:
random2 = random.randint(1, 2)
if random2 == 1:
self.dir_stand = "south"
else:
self.dir_stand = "east"
self.dir_run = "south-east"
if self.keyboard[key.W] and self.keyboard[key.A]:
random3 = random.randint(1, 2)
if random3 == 1:
self.dir_stand = "north"
else:
self.dir_stand = "west"
self.dir_run = "north-west"
if self.keyboard[key.S] and self.keyboard[key.A]:
random4 = random.randint(1, 2)
if random4 == 1:
self.dir_stand = "south"
else:
self.dir_stand = "west"
self.dir_run = "south-west"
def update(self):
self.key_player()
self.load_sprite()
Since to update the Player's sprite, I need to call the "load_sprite" function, which causes the animation to be constantly called. As a result, the same animation does not appear and remains still at the first frame. So how could I solve?
Edit: Modified the script, including the for loop. If you see, I modified the group, using Batch and OrderedGroup instead. In this way we can clearly see the problem I am having.
The problem I have is due to the fact that pyglet.sprite.Sprite is called in order to update which animation is executed. However, doing so at the same time, the animations are not shown exactly because of the constant call of pyglet.sprite.Sprite.
First, you can change the sprite's animation by setting its image attribute, instead of creating a new Sprite instance. Second, only change its animation when you actually need to. That is when the direction changes.
I've added a simple example (pseudo) code to roughly show what I mean.
def animation(image, da, width, height):
frame_list = [image.get_region(x=width * i, y=height * da, width=46, height=58) for i in range(22)]
image_animation = pyglet.image.Animation.from_image_sequence(frame_list, 0.10, True)
return image_animation
class Player:
def __init__(self, standing_animations, running_animations):
# ... code ...
self.standing_animations = standing_animations # List of animations
self.running_animations = running_animations # List of animations
self.current_animation = standing_animations[0] # Just to have a default animation
self.previous_running_direction = None
self.previous_standing_direction = None
def load_sprite(self):
self.sprite.x = self.vx
self.sprite.y = self.vy
if self.previous_running_direction == self.dir_run and self.previous_standing_direction == self.dir_stand:
return # Don't do anything more in here
if not self.keyboard[key.W] and not self.keyboard[key.S] and not self.keyboard[key.D] and not self.keyboard[key.A]:
self.keyboard.clear()
self.current_animation = self.standing_animations[self.sprite_stand]
else:
self.current_animation = self.running_animations[self.sprite_run]
self.sprite.image = self.current_animation
def update(self):
self.previous_running_direction = self.dir_run
self.previous_standing_direction = self.dir_stand
self.key_player()
self.load_sprite()

Python - Boolean tested while loop is never ending

Hi I am trying to program a raspberry pi Sense hat that moves a pixel around the Matrix using the accelorometer. The idea is to get to the red area to win. If however it hits the green yellow or blue the game will end in a loss. When it finds one of the colours it is suppose to change the boolean varialb e(game_over) to True thus breaking the loop to stop the game.
The problem is when it reads that a colour was hit it changes the variable game_over to True, but then it some how changes back to False when it returns to the while loop. I have tested this using print statements to see what happens.
from sense_hat import SenseHat
from time import sleep
sense = SenseHat()
sense.clear()
r = [150,0,0]
g = [0,150,0]
j = [150,150,0]
b = [0,0,150]
e = [0,0,0]
w = [255,255,255]
v = [125,150,175]
x = 4
y = 4
maze = [[r,r,r,r,r,r,r,b],
[g,r,r,r,r,r,b,b],
[g,g,e,e,e,e,b,b],
[g,g,e,e,e,e,b,b],
[g,g,e,e,e,e,b,b],
[g,g,e,e,e,e,b,b],
[g,g,j,j,j,j,j,b],
[g,j,j,j,j,j,j,j]]
false = [
r,e,e,e,e,e,e,r,
e,r,e,e,e,e,r,e,
e,e,r,e,e,r,e,e,
e,e,e,r,r,e,e,e,
e,e,e,r,r,e,e,e,
e,e,r,e,e,r,e,e,
e,r,e,e,e,e,r,e,
r,e,e,e,e,e,e,r]
def move_marble(pitch,roll,x,y):
new_x = x
new_y = y
if 1 < pitch < 179 and x != 0:
new_x -= 1
elif 359 > pitch > 179 and x != 7 :
new_x += 1
if 1 < roll < 179 and y != 7:
new_y += 1
elif 359 > roll > 179 and y != 0 :
new_y -= 1
x,y = check_wall(x,y,new_x,new_y)
return x,y
def check_wall(x,y,new_x,new_y):
if maze[new_y][new_x] != v:
return new_x, new_y
elif maze[new_y][x] != v:
return x, new_y
elif maze[y][new_x] != v:
return new_x, y
return x,y
game_over = False
def check_win(x,y):
sleep(0.25)
if maze[y][x] == r:
sense.show_message('Vous avez gagner', scroll_speed=0.08)
sleep(1)
game_over = True
elif maze[y][x] == j:
sense.set_pixels(false)
game_over = True
sleep(1)
sense.show_message('Vous avez perdu', scroll_speed=0.08)
elif maze[y][x] == b:
sense.set_pixels(false)
game_over = True
sleep(1)
sense.show_message('Vous avez perdu', scroll_speed=0.08)
elif maze[y][x] == g:
sense.set_pixels(false)
game_over = True
sleep(1)
sense.show_message('Vous avez perdu', scroll_speed=0.08)
while game_over == False:
pitch = sense.get_orientation()['pitch']
roll = sense.get_orientation()['roll']
x,y = move_marble(pitch,roll,x,y)
check_win(x,y)
maze[y][x] = w
sense.set_pixels(sum(maze,[]))
sleep(0.1)
maze[y][x] = e
sense.clear()
I'm sure it is something small, I just can not seem to find it.

TSP using genetic algorithm

How do I implement 'insert mutation' and 'cycle recombination' for a TSP problem using genetic algorithm in Python3?
Assume I have done the selection steps and now I have two parents for reproduction.
This is what I have done so far:
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 13 14:15:31 2016
#author: niloo
"""
import pandas as pd
import random
import numpy as np
from geopy.distance import great_circle as gcy
def read(file_name):
data = pd.DataFrame.from_csv(file_name, sep=" ")
data = np.array(data)
return data
def Dist(data):
# distance = []
for i in range(len(data)):
temp = []
for j in range(len(data)):
if j < i:
temp.append(distance[j][i])
elif i == j:
temp.append(0)
else:
temp.append(gcy((data[i][0], data[i][1]), (data[j][0], data[j][1])).km)
distance.append(temp)
#print(distance[1][2])
return distance
def k_fitness():
k = 50
t = 3
first_gener = []
how_fit = []
for i in range(0, k):
temp = np.random.permutation(535)
first_gener.append(temp)
for i in range(len(first_gener)):
sum_dis = 0
for j in range(0, 534):
temp1 = first_gener[i][j]
temp2 = first_gener[i][j + 1]
sum_dis += distance[int(temp1)][int(temp2)]
how_fit.append(sum_dis)
# print(how_fit)
race1 = np.random.randint(k, size=t)
winner1 = 9999999999999999999
for i in range(0, t):
if how_fit[int(race1[i])] < winner1:
winner1 = how_fit[int(race1[i])]
mom = first_gener[int(race1[i])]
#print (mom)
race2 = np.random.randint(k, size=t)
winner2 = 9999999999999999999
for i in range(0, t):
if how_fit[int(race2[i])] < winner2:
winner2 = how_fit[int(race2[i])]
dad = first_gener[int(race2[i])]
return mom, dad
def cross_over(mom , dad):
#mom = [1,2,3,4,5,6,7,8,9]
#dad = [9,3,7,8,2,6,5,1,4]
if len(mom) != len(dad):
print ('error')
else:
child1 = [0] * len(mom)
child2 = [0] * len(mom)
flag = False
index = [0] * len(mom)
while True:
ind = -1
for i in range(len(mom)):
if index[i] == 0:
ind = i
break
if ind == -1:
break
temp = ind
while True:
index[temp] = 1
if flag == False:
child1[temp] = mom[temp]
child2[temp] = dad[temp]
else:
child1[temp] = dad[temp]
child2[temp] = mom[temp]
val = dad[temp]
for i in range(len(dad)):
if mom[i] == val:
temp = i
break
if ind == temp:
break
if flag == False:
flag = True
else:
flag = False
#print child1
#print child2
return [child1 , child2]
def mutation(offspring):
if random.random() <= 0.02:
index1 = random.randint(534)
index2 = random.randint(534)
if index1 != index2:
ind1 = min(index1 , index2)
ind2 = max(index1 , index2)
temp = offspring [ : ind1+1]
temp += offspring [ind2 : ind2+1]
temp += offspring [ind1+1 : ind2]
temp += offspring [ind2+1 : ]
offspring = temp
return offspring
else:
return offspring
dat = read('ali535.tsp')
distance = []
Dist(dat)
k_fitness()

Resources