本文整理汇总了Python中snake.Snake.move方法的典型用法代码示例。如果您正苦于以下问题:Python Snake.move方法的具体用法?Python Snake.move怎么用?Python Snake.move使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类snake.Snake
的用法示例。
在下文中一共展示了Snake.move方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: move
# 需要导入模块: from snake import Snake [as 别名]
# 或者: from snake.Snake import move [as 别名]
def move(self):
if self.travel_points:
self.x, self.y = self.travel_points.pop(0)
Snake.move(self, by_dir=False)
#apple location moved, recalculate path to it
if self.apple.pos != self.apple_loc:
self.generate_path()
self.apple_loc = self.apple.pos
示例2: Game
# 需要导入模块: from snake import Snake [as 别名]
# 或者: from snake.Snake import move [as 别名]
class Game(object):
_gamespeed = 0.6
_snake = None
_gameboard = None
_screen = None
def __init__(self):
# Create the screen object
curses.initscr()
self._screen = curses.newwin(20, 20, 0, 0) #curses.initscr()
self._screen.keypad(1)
self._screen.nodelay(1)
self._screen.timeout(150)
self._screen.border(1)
curses.noecho()
curses.cbreak()
self._gameboard = Gameboard((20, 20), self._screen)
self._snake = Snake(self._gameboard)
def run(self):
key = KEY_RIGHT
try:
while 1:
event = self._screen.getch()
key = key if event == -1 else event
s = None
if key == KEY_UP:
s = SnakeMoveDirection.up
elif key == KEY_DOWN:
s = SnakeMoveDirection.down
elif key == KEY_LEFT:
s = SnakeMoveDirection.left
elif key == KEY_RIGHT:
s = SnakeMoveDirection.right
self._snake.move(s)
self._gameboard.draw()
finally:
curses.echo()
curses.nocbreak()
curses.endwin()
示例3: __init__
# 需要导入模块: from snake import Snake [as 别名]
# 或者: from snake.Snake import move [as 别名]
#.........这里部分代码省略.........
x * BLOCK_SIZE + 5,
(HEIGHT + 1) * BLOCK_SIZE + 5,
))
def loop(self):
"""The game's main loop"""
while True:
# check crash or move outside the limits
if self.snake.outside_limits(WIDTH, HEIGHT) or self.snake.crashed:
self.crashsound.play()
return
# draw screen with snake and foods
self.food.draw()
self.snake.draw()
self.draw_walls()
pygame.display.flip()
# check if snake eates
if self.food.get_pos() == self.snake.get_head_pos():
self.eatsound.play()
self.snake.grow()
# food should not appear where the snake is
self.food = Food(self.screen, 1, HEIGHT + 1, 1, WIDTH + 1)
while self.food.get_pos() in self.snake.pos_list:
self.food = Food(self.screen, 1, HEIGHT + 1, 1, WIDTH + 1)
self.eaten += 1
# increase game speed
if self.eaten % SPEED_INC == 0:
self.speed += SPEED_TICK
# game speed control
self.clock.tick(self.speed)
# get the next event on queue
event = pygame.event.poll()
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
actmotdir = self.snake.motion_dir
if event.key == pygame.K_ESCAPE:
sys.exit()
elif event.key == pygame.K_UP and actmotdir != DOWN:
self.snake.motion_dir = UP
elif event.key == pygame.K_DOWN and actmotdir != UP:
self.snake.motion_dir = DOWN
elif event.key == pygame.K_RIGHT and actmotdir != LEFT:
self.snake.motion_dir = RIGHT
elif event.key == pygame.K_LEFT and actmotdir != RIGHT:
self.snake.motion_dir = LEFT
# remove the snake and make movement
self.snake.remove()
self.snake.move()
def game_over(self):
"""When crashed print "game over" and wait for Esc key"""
self.clock.tick(LONG)
self.snake.draw()
self.draw_walls()
for pos in self.snake.pos_list[1:]:
self.screen.blit(self.snake.backblock, (
pos[1] * BLOCK_SIZE,
pos[0] * BLOCK_SIZE,
))
pygame.display.flip()
self.clock.tick(SHORT)
while True:
self.screen.blit(self.gameovertext, (
(WIDTH - 4) * BLOCK_SIZE / 2,
HEIGHT * BLOCK_SIZE / 2,
))
pygame.display.flip()
event = pygame.event.wait()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
sys.exit()
def start(self):
"""The game starts here"""
# press any key to start!!!
self.draw_walls()
self.screen.blit(self.starttext, (
(WIDTH - 10) * BLOCK_SIZE / 2,
HEIGHT * BLOCK_SIZE / 2,
))
pygame.display.flip()
waiting = True
while waiting:
event = pygame.event.wait()
if event.type == pygame.KEYDOWN:
waiting = False
self.screen.fill(BLACK)
# main loop
self.loop()
self.game_over()
示例4: SnakeWidget
# 需要导入模块: from snake import Snake [as 别名]
# 或者: from snake.Snake import move [as 别名]
class SnakeWidget(QWidget):
def __init__(self, parent):
super(SnakeWidget, self).__init__(parent)
self.snake = Snake()
self.newGame()
self.colors = [QtGui.QColor(255, 0, 0, 255),
QtGui.QColor(255, 255, 0, 255),
QtGui.QColor(0, 0, 255, 255),
QtGui.QColor(0, 255, 0, 255)]
def newGame(self):
self.is_paused = False
self.show()
self.timer = QtCore.QTimer(self)
self.timer.timeout.connect(self.move)
self.timer.start(75)
def resizeEvent(self, event):
self._cell_height = self.size().height() // self.snake.field_height
self._cell_width = self.size().width() // self.snake.field_width
def paintEvent(self, event):
canvas = QtGui.QPainter()
canvas.begin(self)
self.drawFood(canvas)
self.drawSnake(canvas)
canvas.end()
def keyPressEvent(self, event):
directions = {QtCore.Qt.Key_Down: "down",
QtCore.Qt.Key_Up: "up",
QtCore.Qt.Key_Right: "right",
QtCore.Qt.Key_Left: "left"}
if self.snake.dead and event.key() == QtCore.Qt.Key_N:
self.newGame()
if event.key() == QtCore.Qt.Key_Escape:
self.die()
self.hide()
if event.key() == QtCore.Qt.Key_Space:
self.pause()
if not self.is_paused and event.key() in directions.keys():
self.snake.key_press(directions[event.key()])
def pause(self):
if not self.snake.dead:
if self.is_paused:
self.pause_label.setText("")
self.is_paused = False
self.timer.start()
else:
self.is_paused = True
self.pause_label.setText("Press Space or arrows to continue")
self.timer.stop()
print(self.snake.score)
def drawSnake(self, canvas):
canvas.setPen(QtCore.Qt.NoPen)
for segment in self.snake.snake_body:
canvas.setBrush(QtGui.QColor(255, 80, 0, 255))
canvas.drawRect(segment[0] * self._cell_width,
segment[1] * self._cell_height,
self._cell_width, self._cell_height)
def drawFood(self, canvas):
canvas.setPen(QtCore.Qt.NoPen)
canvas.setBrush(QtGui.QColor(0, 80, 255, 255))
canvas.drawEllipse(
self.snake.food_coordinates[0] * self._cell_width,
self.snake.food_coordinates[1] * self._cell_height,
self._cell_width, self._cell_height
)
@QtCore.pyqtSlot()
def move(self):
self.snake.move()
self.repaint()
def die(self):
self.timer.stop()
self.dead = True
self.snake.die()
示例5: SnakeGame
# 需要导入模块: from snake import Snake [as 别名]
# 或者: from snake.Snake import move [as 别名]
class SnakeGame(object):
"""
Represents game object, handles snake's movement and drawing,
mice creating, score count, draws everything.
"""
def __init__(self):
secure_screen_size()
pg.init() # initialize pygame module
pg.display.set_caption('PySnake Game')
# height of upper bound line of the drawing frame
self._snake_width = FRAME_SIZE/FRAME_WIDTH_TO_SNAKE_WIDTH
# make main screen surface a little bit higher (for score text)
self._screen = pg.display.set_mode((FRAME_SIZE, FRAME_SIZE + self._snake_width * 2))
# make a subsurface from screen surface. It will be rectangle where snake will move
self._frame = self._screen.subsurface([0, self._snake_width*2, FRAME_SIZE, FRAME_SIZE])
# set of all grid fields: range for x and y go from 0 to SCREEN_WIDTH_TO_SNAKE_WIDTH - 1
# it will be used to pick a place for draw mouse for snake to chase
self._grid_field_list = [(x, y) for x in xrange(FRAME_WIDTH_TO_SNAKE_WIDTH) for y in xrange(FRAME_WIDTH_TO_SNAKE_WIDTH)]
self._grid_field_size = self._screen.get_width() / FRAME_WIDTH_TO_SNAKE_WIDTH # in pixels
# initialize font
self._font = pg.font.SysFont("monospace", self._snake_width*2 - 3)
# create snake
self._snake = Snake(self._frame, self._snake_width)
# Clock object is used to slow down and main loop, it ensures the FPS
self._clock = pg.time.Clock()
# default speed of the game
self._speed = 10
# default speed increment when snake catches mouse
self._speed_inc = 3
# increment score when snake catches the mouse
self._score = 0
def run(self):
# draw the white background onto the surface
self._frame.fill(BLACK)
# draw frame for the game
self._draw_frame_line()
self._draw_score()
self._snake.draw(draw_everything=True)
mouse_pos = self._draw_mouse()
pg.display.update()
running = True
direction = DIR_RIGHT # initial movement direction
while self._snake.move(direction) and running:
self._snake.draw()
self._draw_frame_line()
# check if snake's head is on the mouse field
if self._snake.head() == mouse_pos:
self._delete_score()
self._score += 1
self._snake.grow()
self._delete_mouse(mouse_pos) # snake eats mouse -> remove it from field
mouse_pos = self._draw_mouse() # re-draw mouse again
self._speed += self._speed_inc # increase play speed
self._draw_score()
pg.display.flip()
self._clock.tick(self._speed) # ensure frame rate of the game: higher the FPS -> snake will be faster
for event in pg.event.get():
if event.type is pg.QUIT:
running = False
elif event.type is pg.KEYDOWN:
if event.key == pg.K_ESCAPE:
running = False
elif event.key == pg.K_LEFT:
direction = DIR_LEFT
elif event.key == pg.K_RIGHT:
direction = DIR_RIGHT
elif event.key == pg.K_UP:
direction = DIR_UP
elif event.key == pg.K_DOWN:
direction = DIR_DOWN
def _draw_mouse(self):
"""
Picks random location and draws mouse
:return: mouse location -> tuple (x,y)
"""
pos = self._snake.grid_occupied[0]
while pos in self._snake.grid_occupied:
pos = (randint(0, FRAME_WIDTH_TO_SNAKE_WIDTH-1), randint(0, FRAME_WIDTH_TO_SNAKE_WIDTH-1))
# draw a pink circle onto the surface
center = (pos[0] * self._grid_field_size + self._grid_field_size / 2,
pos[1] * self._grid_field_size + self._grid_field_size / 2)
#.........这里部分代码省略.........
示例6: Game
# 需要导入模块: from snake import Snake [as 别名]
# 或者: from snake.Snake import move [as 别名]
class Game(object):
def __init__(self, window):
self.snake = Snake()
self.apple = Apple()
self.window = window
self.grid = []
self.score = 0
def move_snake(self, key):
"""Manual move of snake"""
if key in [KEY_UP, KEY_DOWN, KEY_LEFT, KEY_RIGHT]:
self.snake.move(key)
else:
self.snake.move(self.snake.last_direction)
if self.snake.head == self.apple.position:
self.snake.eat(self.apple, self.grid)
self.score += 1
if self.snake.is_collide():
self.reset()
def automove(self):
"""Deplace position of the snake with A* algorithm"""
path = find_path(tuple(self.snake.head), tuple(self.apple.position), self.grid)
move = path[0] if path else False
if not move:
move = self.any_possible_move()
if move:
if not self.snake.is_eating:
self.snake.position.pop(0)
self.snake.is_eating = False
self.snake.position.append(move)
self.snake.head = self.snake.position[-1]
self.snake.tail = self.snake.position[0]
if self.snake.head == self.apple.position:
self.snake.eat(self.apple, self.grid)
self.score += 1
if self.snake.is_collide() or not move:
self.reset()
def any_possible_move(self):
"""Return any possible position"""
neighbors = [(0, 1), (0, -1), (1, 0), (-1, 0)]
for i, j in neighbors:
neighbor = self.snake.head[0] + i, self.snake.head[1] + j
if self.grid[neighbor[0]][neighbor[1]] == 0:
return [neighbor[0], neighbor[1]]
return False
def display(self):
"""display game"""
self.grid[:] = []
for line in range(HEIGHT):
self.grid.append([])
for column in range(WIDTH):
if column == 0 or line == 0 or column == WIDTH - 1 or line == HEIGHT - 1:
self.grid[line].append(1)
else:
self.grid[line].append(0)
for line, column in self.snake.position:
self.grid[line][column] = 1
self.window.addstr(line, column, 's')
line, column = self.apple.position
self.window.addstr(line, column, 'a')
def reset(self):
"""Reset game"""
self.apple.reset()
self.snake.reset()
self.score = 0
示例7:
# 需要导入模块: from snake import Snake [as 别名]
# 或者: from snake.Snake import move [as 别名]
pygame.display.flip()
# Pause
clock.tick(1)
while done == False:
for event in pygame.event.get():
if (event.type == pygame.QUIT):
done = True
if (event.type == pygame.KEYDOWN):
if (event.key == pygame.K_LEFT):
direction = 2
if (event.key == pygame.K_RIGHT):
direction = 0
if (event.key == pygame.K_UP):
direction = 1
if (event.key == pygame.K_DOWN):
direction = 3
if (event.key == pygame.K_SPACE):
length += 1
snake.move(direction, length)
# Clear screen
screen.fill(black)
snake.draw(screen)
# Flip screen
pygame.display.flip()
# Pause
clock.tick(1)
pygame.quit()
示例8: SnakeGame
# 需要导入模块: from snake import Snake [as 别名]
# 或者: from snake.Snake import move [as 别名]
class SnakeGame(object):
def __init__(self, tk, speed):
self.food = (randint(0, 20), randint(0, 20))
self.speed = speed
self.snake = Snake()
self.tk = tk
self.button = Button(tk, text="start game!", command=self.run)
self.canvas = Canvas(tk, width=410, height=410, bg="black")
self.button.pack()
self.canvas.pack()
self.tk.bind("<KeyPress-Up>", self.up_event)
self.tk.bind("<KeyPress-Down>", self.down_event)
self.tk.bind("<KeyPress-Right>", self.right_event)
self.tk.bind("<KeyPress-Left>", self.left_event)
def run(self):
if self.snake.eat(self.food):
eat_flag = 1
self.food = None
else:
eat_flag = 0
self.snake.move(eat_flag)
if self.not_over():
self.canvas.delete("all")
self.draw_food()
self.draw_snake()
self.tk.after(self.speed, self.run)
else:
r = tkMessageBox.showinfo("Oh,game over!")
if r == "ok":
sys.exit()
def not_over(self):
if self.is_rush_wall() or self.is_rush_self():
return 0
else:
return 1
def draw_snake(self):
for i in range(0, self.snake.body.__len__()):
x0, y0 = Api.position_to_pix(self.snake.body[i][0], self.snake.body[i][1])
x1 = x0+10
y1 = y0+10
self.canvas.create_rectangle(x0, y0, x1, y1, fill="white", outline=None, width=0)
if i != (self.snake.body.__len__()-1):
x2, y2 = Api.position_to_pix(self.snake.body[i+1][0], self.snake.body[i+1][1])
x3 = (x0 + x2)/2
y3 = (y0 + y2)/2
x4 = x3+10
y4 = y3+10
self.canvas.create_rectangle(x3, y3, x4, y4, fill="white", outline=None, width=0)
def change_snake_direction(self, direction):
r = self.snake.change_direction(direction)
if not r:
print "you can't do that"
def up_event(self, event):
self.change_snake_direction("up")
print "up"
def down_event(self, event):
self.change_snake_direction("down")
print "down"
def right_event(self, event):
self.change_snake_direction("right")
print "right"
def left_event(self, event):
self.change_snake_direction("left")
print "left"
def food_exist(self):
if self.food is None:
return 0
else:
return 1
def draw_food(self):
if not self.food_exist():
world = []
for i in range(0, 21):
for j in range(0, 21):
world.insert(-1, (i, j))
for item in self.snake.body:
world.remove(item)
self.food = world[randint(0, world.__len__()-1)]
x0, y0 = Api.position_to_pix(self.food[0], self.food[1])
x1 = x0+10
y1 = y0+10
self.canvas.create_rectangle(x0, y0, x1, y1, fill="white", outline=None, width=0)
def is_rush_wall(self):
if (self.snake.body[0][0] >= 0) and (self.snake.body[0][0] <= 20):
if (self.snake.body[0][1] >= 0) and (self.snake.body[0][1] <= 20):
return 0
else:
return 1
#.........这里部分代码省略.........
示例9: __init__
# 需要导入模块: from snake import Snake [as 别名]
# 或者: from snake.Snake import move [as 别名]
class Game:
"""
The main game class that holds the gameloop.
"""
def __init__(self, mlhost, mlport):
"""
Create a screen and define some game specific things.
"""
pymlgame.init()
self.screen = pymlgame.Screen(mlhost, mlport, 40, 16)
self.clock = pymlgame.Clock(15)
part = (int(self.screen.width / 2), int(self.screen.height / 2))
self.snake = Snake([(part[0] - 2, part[1]), (part[0] - 1, part[1]),
part], RIGHT, (self.screen.width, self.screen.height))
self.gameover = False
self.apple = self.generate_apple()
self.apple_surface = pymlgame.Surface(1, 1)
self.apple_surface.draw_dot((0, 0), GREEN)
self.oldapple = self.apple
self.score = 0
self.highscore = self.get_highscore()
def update(self):
"""
Update the screens contents in every loop.
"""
if not self.snake.move():
self.gameover = True
if self.snake.get_pos() == self.apple:
self.score += 1
self.oldapple = self.apple
self.apple = self.generate_apple()
def render(self):
"""
Send the current screen content to Mate Light.
"""
self.screen.reset()
# draw snake
surface = pymlgame.Surface(self.screen.width, self.screen.height)
for part in self.snake.parts:
surface.draw_dot(part, pymlgame.locals.RED)
self.screen.blit(surface)
# draw apple
self.screen.blit(self.apple_surface, self.apple)
if self.snake.parts[0] == self.oldapple:
self.snake.grow = True
self.oldapple = None
self.screen.update()
# TODO: accelerate every 5 points by 1 fps
self.clock.tick()
def handle_events(self):
"""
Loop through all events.
"""
for event in pymlgame.get_events():
if event.type == E_NEWCTLR:
print('new ctlr with id:', event.id)
elif event.type == E_KEYDOWN:
if event.button == CTLR_UP:
if self.snake.direction != DOWN:
self.snake.direction = UP
elif event.button == CTLR_DOWN:
if self.snake.direction != UP:
self.snake.direction = DOWN
elif event.button == CTLR_LEFT:
if self.snake.direction != RIGHT:
self.snake.direction = LEFT
elif event.button == CTLR_RIGHT:
if self.snake.direction != LEFT:
self.snake.direction = RIGHT
elif event.type == E_PING:
#print('ping from', event.id)
pass
def gameloop(self):
"""
A game loop that circles through the methods.
"""
try:
while not self.gameover:
self.handle_events()
self.update()
self.render()
print('game over - score:', self.score)
print('current highscore:', self.highscore)
if self.score > int(self.highscore):
self.write_highscore()
end = time.time() + 5
while time.time() < end:
self.screen.reset()
#.........这里部分代码省略.........
示例10: Game
# 需要导入模块: from snake import Snake [as 别名]
# 或者: from snake.Snake import move [as 别名]
class Game():
FOODN = 4
SNAKEN = 8
BOARDSIZE = [16, 16]
STARTINGSIZE = 10
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
def __init__(self):
self.arrayPos = self.__initiatePos()
self.snake = Snake(self.SNAKEN, self.STARTINGSIZE , [0,11], 'r')
self.dir = 'r'
self.food = [1,10]
def __checkEat(self, headPos):
"""
Checks for eats.
Returns True if it ate.
"""
return bool(headPos.tolist() == self.food)
def __updateFood(self, board):
"""
Gives random new coordinates to food from
the available free spaces in board
"""
interm = numpy.where(board!=self.SNAKEN, self.arrayPos, board)
availablePos = numpy.extract(interm!=self.SNAKEN, interm)
self.food = random.choice(availablePos)
print("Food now at: " + str(self.food))
print("Eaten")
def __prepareBoard(self, eaten):
"""
Returns a board ready to print
"""
toprint = numpy.zeros(self.BOARDSIZE, dtype=int)
bodyPositions = self.snake.getBody()
#Place snake
for pos in bodyPositions:
toprint[pos[0],pos[1]] = self.SNAKEN
#Replace food
if eaten:
self.__updateFood(toprint)
#Place food
toprint[self.food[0], self.food[1]] = self.FOODN
return toprint
def __initiatePos(self):
"""
Returns a gameboard-sized array where each
item contains its position in a python list.
[[0,0],[0,1]...]
"""
interm = numpy.empty(self.BOARDSIZE, dtype=object)
for m in range(interm.shape[0]):
for n in range(interm.shape[1]):
interm[m][n] = [m, n]
return interm
def __printBoard(self, board):
"""
Smoothly prints the game board
"""
print('')
for line in board:
lineOut = ''
for num in line:
if not num:
lineOut += str(num)
if num==self.FOODN:
lineOut += self.OKGREEN + str(num) + self.ENDC
elif num==self.SNAKEN:
lineOut += self.OKBLUE + str(num) + self.ENDC
lineOut += ' '
print(lineOut)
print('')
def move(self):
"""
Performs a whole move
"""
#Update moving direction
self.snake.changeDir(self.dir)
#Check for eats in the upcoming move
futHeadPos = self.snake.getBody()[0] + self.snake.getDir()
eaten = self.__checkEat(futHeadPos)
#Move the snake
self.snake.move(eaten)
#.........这里部分代码省略.........
示例11: GameScreen
# 需要导入模块: from snake import Snake [as 别名]
# 或者: from snake.Snake import move [as 别名]
class GameScreen(Screen):
def __init__(self, screen):
Screen.__init__(self, screen)
self.snake = Snake()
self.snake_dir = Directions.RIGHT
self.inPause = False
self.pauseImg = pygame.image.load('assets/img/pause.png').convert();
self.pauseImg.set_colorkey(Defines.COLORKEY)
self.apple = (20,20)
self.score = 0;
self.font = pygame.font.Font("assets/fonts/blogger-sans.ttf", 24)
self.fontL = pygame.font.Font("assets/fonts/blogger-sans.ttf", 48)
self.scoretxt = self.font.render("score %d" % self.score, True, (0, 0, 0))
self.txtloose = self.fontL.render("You Loose", True, (0, 0, 0))
def manageEvents(self, event):
#For testing Keyboard use event.dict['unicode'] because in default keyboard type is in American
if event.type == pygame.KEYDOWN:
if event.dict['unicode'] == "z" or event.key == pygame.K_UP:
self.snake_dir = Directions.UP
elif event.dict['unicode'] == "s" or event.key == pygame.K_DOWN:
self.snake_dir = Directions.DOWN
elif event.dict['unicode'] == "q" or event.key == pygame.K_LEFT:
self.snake_dir = Directions.LEFT
elif event.dict['unicode'] == "d" or event.key == pygame.K_RIGHT:
self.snake_dir = Directions.RIGHT
elif event.key == pygame.K_SPACE:
self.inPause = False if self.inPause else True
def update(self):
if self.snake.inLife:
if not self.inPause:
if self.snake_dir == Directions.RIGHT:
self.snake.move(self.snake.head_x + Defines.SNAKE_SIZE + 1, self.snake.head_y)
elif self.snake_dir == Directions.LEFT:
self.snake.move(self.snake.head_x - Defines.SNAKE_SIZE - 1, self.snake.head_y)
elif self.snake_dir == Directions.UP:
self.snake.move(self.snake.head_x, self.snake.head_y - Defines.SNAKE_SIZE - 1)
elif self.snake_dir == Directions.DOWN:
self.snake.move(self.snake.head_x, self.snake.head_y + Defines.SNAKE_SIZE + 1)
if self.snake.head_x == self.apple[0] and self.snake.head_y == self.apple[1]:
self.score += 10
self.scoretxt = self.font.render("score %d" % self.score, True, (0, 0, 0))
self.apple = (randint(0, 31) * 20, randint(0, 23) * 20)
self.snake.snake_length = self.snake.snake_length + 1
self.snake.snake_coords.insert(0, [self.snake.head_x, self.snake.head_y])
return self
def render(self):
self.snake.render(self.screen)
if not self.snake.inLife:
imgDie = pygame.Surface((640,480))
imgDie.set_alpha(128)
imgDie.fill((255, 0, 0))
self.screen.blit(imgDie, (0, 0))
self.screen.blit(self.txtloose, (320 - self.txtloose.get_width() // 2,200))
self.screen.blit(self.scoretxt, (10, 5))
pygame.draw.rect(self.screen, Defines.RED, [self.apple[0], self.apple[1], Defines.SNAKE_SIZE, Defines.SNAKE_SIZE])
if self.inPause:
self.screen.blit(self.pauseImg, (195, 215))
示例12: Game
# 需要导入模块: from snake import Snake [as 别名]
# 或者: from snake.Snake import move [as 别名]
class Game():
star_cords = (0, 0)
def __init__(self, screen):
self.screen = screen
self.RUNNING = True
self.speed = 1.0
self.place_star()
def speed_up(self):
self.speed /= 2.0
def speed_down(self):
self.speed *= 2.0
def calc_start_loc(self):
y = curses.LINES // 2
x = curses.COLS // 2
return (y, x)
def start(self):
self.snek = Snake(
self.screen,
6,
self.calc_start_loc()
)
self.snek.render()
while self.RUNNING:
try:
time.sleep(self.speed)
self.tick()
except KeyboardInterrupt:
self.RUNNING = False
def place_star(self):
y = random.randint(0, curses.LINES - 1)
x = random.randint(0, curses.COLS - 1)
self.star_cords = (y, x)
def check_star_get(self):
if self.star_cords in [
seg.coordinates
for seg in self.snek.body
]:
self.snek.add_segment()
self.place_star()
def tick(self):
self.screen.clear()
direction = self.screen.getch()
if 258 <= direction <= 261:
if direction == self.snek.direction:
self.speed_up()
elif (direction <= 259 and self.snek.direction <= 259
or direction >= 260 and self.snek.direction >= 260):
self.speed_down()
elif direction < 260:
self.speed_down()
self.snek.direction = direction
else:
self.speed_up()
self.snek.direction = direction
self.snek.move()
self.snek.check_loss()
self.check_star_get()
self.screen.addstr(
self.star_cords[0],
self.star_cords[1],
'*'
)
self.snek.render()
self.screen.refresh()