python - 如何为国际象棋pygame程序中的棋子制定规则?
问题描述
我一直在尝试使用 pygame 创建一个国际象棋程序,并且一直在尝试编写棋子应该遵循的规则。我开始只关注国王的作品。这是我的代码:
class Piece(object):
def __init__(self, x_init, y_init, color):
self.x_init = x_init
self.y_init = y_init
self.color = color
self.possible_positions = False
self.width = 60
self.height = 60
self.click = False
self.click_rect = sprites[0].get_rect(topleft=(self.x_init, self.y_init))
self.init1 = True
self.x_newinit = 0
self.y_newinit = 0
self.final_pos = False
def movement(self):
global x, y
for event in ev:
if self.init1:
self.x_newinit = self.x_init
self.y_newinit = self.y_init
if event.type == pygame.MOUSEBUTTONDOWN:
if self.click_rect.collidepoint(event.pos):
self.click = True
self.init1 = True
x, y = event.pos
elif event.type == pygame.MOUSEBUTTONUP:
self.click = False
self.x_init = (((round(self.x_init / 75)) * 75) + 7.5)
self.y_init = (((round(self.y_init / 75)) * 75) + 7.5)
if not self.possible_positions:
self.x_init = self.x_newinit
self.y_init = self.y_newinit
if event.type == pygame.MOUSEMOTION:
self.init1 = False
if self.click:
if 25 < x < 580:
self.x_init = x - 30
if 20 < y < 580:
self.y_init = y - 30
self.click_rect = sprites[0].get_rect(topleft=(self.x_init, self.y_init))
class King(Piece):
def __init__(self, x_init, y_init, color):
super().__init__(x_init, y_init, color)
self.x_init = x_init
self.y_init = y_init
self.color = color
self.final_pos = False
def draw(self, gameWindow):
if not self.final_pos:
gameWindow.blit(sprites[0], (self.x_init, self.y_init)) # draw white king
def draw2(self, gameWindow):
if not self.final_pos:
gameWindow.blit(sprites[6], (self.x_init, self.y_init)) # draw black king
def poss_positions(self):
if self.x_newinit - 37.5 >= self.x_init >= self.x_newinit - 112.5: # move left
self.possible_positions = True
elif self.x_newinit + 37.5 <= self.x_init <= self.x_newinit + 112.5: # move right
self.possible_positions = True
elif self.y_newinit - 37.5 >= self.y_init >= self.y_newinit - 112.5: # move up
self.possible_positions = True
elif self.y_init - 37.5 >= self.y_newinit >= self.y_init - 112.5: # move down
self.possible_positions = True
else:
self.possible_positions = False
国王棋子遵循self.poss_positions
规则,当我试图不正确地移动它们时,它们会被送回它们的起始位置,但随后它们被卡在那里,我无法再次移动它们。我尝试定义新变量并将它们设置为等于self.x_init
并self.y_init
在某些条件下,以便我可以将变量重置为 0self.x_newinit
并self.y_newinit
重置整个过程,但这不起作用。我提出的任何可能的解决方案似乎都不起作用。我需要帮助。
解决方案
推荐阅读
- javascript - 要求、导出和控制台字段的 Javascript eslint 错误
- android - 程序类型已经存在:org.hamcrest.CoreMatchers
- ruby-on-rails - 如何以 Ruby on Rails 守护进程的方式查看服务器日志?
- python - 将 tkinter Filedialog 与 json.dump 结合使用
- javascript - 用文件提交反应表单
- vb.net - sql 过程返回 1 但 vb.net 得到 0
- sql-server - 传递表类型以选择存储过程并使用 LIKE
- php - Laravel 使用请求获取 POSTed 数据
- php - 将 JSON 数据插入 MySQL
- java - 这是在 java 中使用 volatile 变量的好例子吗?